Menu

Filtering, Sorting, and Limiting Results

Lesson 2: Filtering, Sorting, and Limiting Results

What do WHERE and ORDER BY do?

Clause

Purpose

WHEREKeeps only rows that meet a condition
ORDER BYSorts the result (ASC = ascending, the default; DESC = descending)
LIMITRestricts how many rows are returned

Row-limiting syntax differs by system:

System

Syntax

PostgreSQL, MySQL, SQLite, BigQueryLIMIT 10
SQL ServerSELECT TOP 10 …
Oracle (12c+), PostgreSQL, Db2FETCH FIRST 10 ROWS ONLY

Example

SELECT order_id, total_amount
FROM orders
WHERE total_amount >= 1000
ORDER BY total_amount DESC
LIMIT 10;

How it works

  1. Reads the orders table
  2. Keeps orders worth at least 1,000
  3. Sorts them highest first
  4. Returns the first ten rows
  • Use single quotes around text values: WHERE region = 'South'
  • Use date literals in a standard format: WHERE order_date >= '2026-07-01'

Useful conditions

Operator

Meaning

Example

=, <> (or !=)Equal, not equalregion = 'South'
>, <, >=, <=Comparisonstotal_amount > 500
ANDAll conditions trueregion = 'South' AND total_amount > 500
ORAt least one trueregion = 'South' OR region = 'East'
INMatches any value in a listregion IN ('South', 'East')
BETWEENInclusive rangetotal_amount BETWEEN 500 AND 1000
LIKEPattern match (% = any characters)customer_name LIKE 'A%'
IS NULL / IS NOT NULLMissing / present valuesemail IS NULL
NOTNegates a conditionregion NOT IN ('North')

Common mistakes

  • NULL is not zero or an empty string. It means "unknown".
    • ✅ WHERE email IS NULL
    • ❌ WHERE email = NULL (never true)
  • Mixing AND and OR without parentheses:
    • ❌ WHERE region = 'South' OR region = 'East' AND total_amount > 500
    • ✅ WHERE (region = 'South' OR region = 'East') AND total_amount > 500
    • AND is evaluated before OR, so the first version doesn't do what it looks like.
  • BETWEEN with timestamps: BETWEEN '2026-07-01' AND '2026-07-31' may miss events on 31 July after midnight. Use >= '2026-07-01' AND < '2026-08-01' instead.

Try it: Find orders from the South region with amounts above 500, sorted from newest to oldest.


Data Analytics Tutorial



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details