📖
Notes
  • 🙌Welcome!
  • CyberSecurity
    • Penetration Testing
      • ELearnSecurity
        • eJPT
          • Footprinting & Scanning
            • Port Scanning
            • Mapping Networks
          • Information Gathering
            • Subdomain Enumeration
          • Network Attacks
            • Arp Poisoning
            • Null Sessions
            • Windows Shares
            • Authentication Cracking
          • Networking
            • Python Server to Receive Exfiltrated Data
            • CLI Tool to interact with HTTP/HTTPS
          • Programming
            • C++ Keylogger
            • C++ Information Stealer
          • System Attacks
            • Pivoting
            • Backdoor
          • Vulnerability Assessment
          • Web Attacks
            • SQL Injection
            • HTTP Verbs
            • Web Server Fingerprinting
      • PortSwigger
        • Cross-origin resource sharing (CORS)
          • Access-Control-Allow-Origin response header
          • Vulnerabilities arising from Misconfigurations
            • Server-generated ACAO header from client-specified Origin header
            • Errors parsing Origin headers
            • Whitelisted null origin value
            • Exploiting XSS via CORS trust relationships
            • Breaking TLS with poorly configured CORS
            • Intranets and CORS without credentials
            • Mitigations
        • Sql Injection
          • Examining the database
          • Retrieving data from other database tables
          • Blind SQL injection
          • Mitigation
      • TryHackMe
        • Main Methodology
          • 1. Reconnaissance
            • Google Dorking
            • Metadata Reader/Writer
            • Steghide - Stegnography
            • OSINT Framework
          • 2. Enumeration/Scanning
            • NFS Enumeration Tools
            • NMAP - Port Scanning
            • Web Enumeration Tools
            • SMB Enumeration Tools
            • SMTP Enumeration Tools
            • Shodan - IOT Search Engine
            • FTP Enumeration Tools
            • Wordpress Enumeration Tools
            • OWASP ZAP - WebApp Testing
            • BurpSuite - WebApp Testing
            • MySQL Enumeration Tools
            • Wordlists
          • 3. Gaining Access / Exploitation
            • Buffer Overflow
              • 1. Immunity Debugger
              • 2. Mona Setup
              • 3. Spiking
              • 4. Fuzzing
              • 5. Crash Replication & Controlling EIP
              • 6. Finding Bad Characters
              • 7. Find a Jump Point
              • 8. Generate Payload
              • 9. Prepend NOPs
              • 10. Final Buffer
            • Cryptography
              • Hash Crack Tools
              • Online Password Cracking Tools
              • Encryption
              • John the Ripper
            • Evasion Techniques
            • Shells
              • Powershell
              • Msfvenom
              • Meterpreter
              • Metasploit -- multi/handler
              • Netcat
              • Socat
            • Web Applications
              • OWASP Top 10
              • File Upload Vulnerabilities
              • Authentication Vulnerability
              • XML External Entity (XXE)
              • Cross-Site Scripting (XSS)
              • ZTH: Obscure Web Vulns
              • Server Side Request Forgery (SSRF)
              • Insecure Direct Object Reference (IDOR)
              • ZTH : Continued
              • File Inclusion Vulnerability
                • Local File Inclusion (LFI)
                • Log Poisoning Attack (LFI to RCE via Log files)
            • Windows Applications
              • Jenkins
              • Windows Active Directory
                • Impacket's secretsdump.py
                • Kerberos
                  • Enumerating Users with Kerbrute
                  • Enumerating SPN Accounts with Powershell
                  • Get SPN Account Ticket with Invoke-Kerberoast
                  • Kerberoasting with Rubeus & Impacket
                  • AS-REP Roasting with Rubeus/GetNPUsers.py
                  • Pass the Ticket with mimikatz
                  • Golden/Silver Ticket Attacks with mimikatz
                  • Kerberos Backdoors with mimikatz
                  • Harvesting and Brute-Forcing with Rubeus
                  • Conclusion and Resources
          • 4. Post Exploitation
            • Privilege Escalation
              • Linux
                • 1. Introduction
                • 2. Scripts
                • 3. Kernel Exploits
                • 4. Service Exploits
                • 5. Weak File Permissions
                • 6. Sudo
                • 7. Cron jobs
                • 8. SUID/SGID Executable
                • 9. CAP_SETUID Capabilities Executable
                • 10. Passwords & Keys
                • 11. NFS
                • PrivEsc CTF Checklists
              • Windows
                • Token Impersonation
                • PrivEsc CTF Checklists
                • Permission
                • Scripts
                • Unquoted Service Path
            • Tools
              • Meterpreter Modules
              • Impacket's Psexec
              • Impacket's mssqlclient.py
              • Firefox Decryptor
              • Socat - Reverse TCP Tunnel
            • Windows Active Directory
              • Enumeration with Powerview
              • Enumeration with Bloodhound (GUI)
              • Dumping Hashes with mimikatz
              • Golden Ticket Attacks with mimikatz
              • Enumeration with Server Manager
              • Maintaining Access
              • Additional Resources
          • 5. Covering Tracks
          • 6. Reporting
        • Networking Concepts
          • SSH Reverse Tunnels
        • Scripting
          • Curl
          • Powershell
            • Basic Powershell Commands
            • Enumeration
        • Web Extensions
          • Shodan
          • Wappalyzer
      • Miscellaneous
        • SMTP Enumeration
        • Nmap Advanced Scanning
        • Persistence via Meterpreter
        • DNS Enumeration
        • NetBIOS & SMB
        • DHCP Starvation
        • Packet Manipulation
        • Hash Cracking
        • MITM
        • Msfvenom Payload in APK (Manual Embedding)
    • Blue Teaming
      • Digital Forensics & Incidence Response
        • Memory Acquisition with LIME
        • Disk Analysis with Autopsy
        • Data and Memory Collection with FireEye Redline
        • Memory Forensice with Volatility
      • Intrusion Detection
        • Intrusion Detection Systems (IDS)
        • Threat Monitoring with Security Information & Event Management (SIEM)
        • Security Event Monitoring
        • Host Based Intrusion Detection System (HIDS) - OSSEC
      • Miscellaneous
        • Docker Image Security Analysis with Trivy
  • DevOps
    • Infrastructure as a Code (IaC)
      • Ansible
        • 1. Playbooks
        • 2. Modules
        • 3. Inventory
        • 4. Roles
        • 5. Ansible Tower
      • Terraform
        • 1. Overview
        • 2. Modify Resources
        • 3. Delete Resources
        • 4. Reference Resources
        • 5. Terraform Files
        • 6. Terraform State Commands
        • 7. Terraform Output
        • 8. Target Resources
        • 9. Terraform Variables
        • 10. Expressions + Functions
        • 11. Meta-Arguments
        • 12. Modules
        • 13. Managing Multiple Environments
        • 14. Testing Terraform Code
        • 15. Final Thoughts
    • Orchestration
      • Kubernetes
        • 1. Main K8s Components
        • 2. K8s Architecture
        • 3. Minikube & Kubectl
        • 4. YAML Configuration File
        • 5. K8s Namespaces
        • 6. K8s Ingress
        • 7. Helm - Package Manager of K8s
        • 8. K8 Volumes
        • 9. K8 StatefulSet
        • 10. K8 Services
  • Development
    • Blockchain
      • FreeCodeCamp Course
        • 1. Introduction
        • 2. Solidity Basics
        • 3. Storage Factory
        • 4. Fund Me
        • 5. Ethers.js
        • 6. Hardhat
        • 7. Hardhat | Fund Me
        • 8. Contract Lottery | Raffle
        • 9. IPFS
        • 10. ERC20s
        • 11. DeFi & Aave
        • 12. NFTs | Encoding
        • 13. Reentrancy Attack
    • Backend
      • NodeJs
        • Introduction
        • Additional Concepts
        • ExpressJs
    • Database
      • SQL
        • Basics
          • 1. Querying Data
          • 2. Filtering Data
          • 3. Joining Multiple Tables
          • 4. Grouping Data
          • 5. Set Operations
          • 6. Grouping Sets, Cube, and Rollup
          • 7. Subquery
          • 8. Common Table Expressions
          • 9. Modifying Data
          • 10. Transactions
          • 11. Import & Export Data
          • 12. Managing Tables
    • Testing
      • Test Driven Development (TDD)
      • Jest js
      • Cypress js
Powered by GitBook
On this page
  • Where
  • Limit
  • Fetch
  • In
  • Between
  • Like
  • Is Null
  1. Development
  2. Database
  3. SQL
  4. Basics

2. Filtering Data

Previous1. Querying DataNext3. Joining Multiple Tables

Last updated 1 year ago

Where

(filter rows based on a specified condition)

  • SELECT statement returns all rows from one or more columns in a table. To select rows that satisfy a specified condition, we use a WHERE clause

  • It appears right after FROM clause.

  • The condition must evaluate to true, false or unkown. It can be used with boolean expressions like AND and OR operators

  • It order of evalutation is as follows

  • NOTE: You can't use COLUMN ALIAS with WHERE clause

Comparison Operators

Operator
Description

=

Equal

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

<> or !=

Not equal

AND

logitcal operator AND

OR

logical operator OR

IN

Return true if a value matches any value in a list

BETWEEN

Retruns true if a value is between a range of values

LIKE

Returns true if a value matches a pattern

IS NULL

Returns true if a value is NULL

NOT

Negate the result of other operators

Example 1 (Using WHERE with IN operator)

SELECT
	first_name,
	last_name
FROM
	customer
WHERE
	first_name IN ('Noman','Ali');

Example 2 (Using WHERE with LIKE operator)


SELECT
	first_name,
	last_name
FROM
	customer
WHERE
	first_name LIKE 'Al%';

The % is called a wildcard that matches any string

Example 3 (Using WHERE with BETWEEN operator)


SELECT
	first_name,
	LENGTH(first_name) name_length
FROM
	customer
WHERE
	first_name LIKE 'A%' AND
	LENGTH(first_name) BETWEEN 3 AND 5
ORDER BY
	name_length;

Limit

(get a subset of rows generated by a query)

  • It is the optional clause of the SELECT statement that contraints no of rows returned by the query

  • If we want to skip number of rows before returning the limited rows, we can use the OFFSET clause placed after the LIMIT clause

Example 1

SELECT
	film_id
FROM
	film
ORDER BY
	film_id
LIMIT 5;

Example 2

SELECT
	film_id
FROM
	film
ORDER BY
	film_id
LIMIT 4 OFFSET 3;

Fetch

(limit the number of rows returned by a query)

  • LIMIT clause is not a SQL-standard, FETCH is a SQL standard

  • If you plan to make your application compatible with other database systems, you should use the FETCH clause because it follows the standard SQL.

  • Its syntax is like this

    •  OFFSET start { ROW | ROWS }
       FETCH { FIRST | NEXT } [ row_count ] { ROW | ROWS } ONLY
      • ROW is the synonym for ROWS, FIRST is the synonym for NEXT. So you can use them interchangeably

      • The start is an integer that must be zero or positive. By default, it is zero if the OFFSET clause is not specified. In case the start is greater than the number of rows in the result set, no rows are returned;

      • The row_count is 1 or greater. By default, the default value of row_count is 1 if you do not specify it explicitly.

Example 1

SELECT
	film_id,
	title
FROM
	film
ORDER BY
	title
FETCH FIRST 5 ROW ONLY;

Example 2

SELECT
	film_id,
	title
FROM
	film
ORDER BY
	title
OFFSET 5 ROWS
FETCH FIRST ROW ONLY;

In

(select data that matches any value in a list of values)

  • You use IN operator in the WHERE clause to check if a value matches any value in a list of values.

  • The list of values can be list of literal values such as numbers, strings or a result or SELECT statement like this

    • value IN (SELECT column_name FROM table_name);

Example 1

SELECT customer_id,
	rental_id,
	return_date
FROM
	rental
WHERE
	customer_id IN (1, 2)
ORDER BY
	return_date DESC;

Example 2 (Get Customers information from customer table whose return date from rental table is '2005-05-27')

The following query returns a list of customer ids from the rental table with the return date is 2005-05-27

SELECT customer_id
FROM rental
WHERE CASE (return_date AS DATE) = '2005-05-27'
ORDER BY customer_id;

Because, it returns a list of values, we can use it in input of IN operator

SELECT
	customer_id,
	first_name,
	last_name
FROM
	customer
WHERE
	customer_id IN (
		SELECT customer_id
		FROM rental
		WHERE CASE (return_date AS DATE) = '2005-05-27'
	)
ORDER BY customer_id;

Between

(select data that is a range of values)

  • You use the BETWEEN operator to match a value against a range of values. The following illustrates the syntax of the BETWEEN operator:

    • value BETWEEN low AND high;

Example 1

SELECT
	customer_id,
	payment_id,
	amount,
	payment_date
FROM
	payment
WHERE
	payment_date BETWEEN '2007-02-07' AND '2007-02-15';

Like

(filter data based on pattern matching)

  • It is used for string pattern matching

  • Percent sign % matches any sequence of zero or more characters.

  • Underscore sign _ matches any single character.

  • PostgreSQL supports the ILIKE operator that works like the LIKE operator. In addition, the ILIKE operator matches value case-insensitively.

  • PostgreSQL also provides some operators that act like the LIKE, NOT LIKE, ILIKE and NOT ILIKE operator as shown below:

Example 1

SELECT
	'foo' LIKE 'foo', -- true
	'foo' LIKE 'f%', -- true
	'foo' LIKE '_o_', -- true
	'bar' LIKE 'b_'; -- false

Example 2

SELECT
	first_name,
	last_name
FROM
	customer
WHERE
	first_name ILIKE 'BAR%';

Is Null

(check if a value is null or not)

  • Used for NULL comparison

Example 1 (Find all contacts whose phone number is NULL)

SELECT
    id,
    first_name,
    last_name,
    email,
    phone
FROM
    contacts
WHERE
    phone = NULL;