Skip to the content

Lesson 213 of 296

SELECT, WHERE, ORDER BY and LIMIT

What you will learn

  • Reading data with SELECT
  • Filtering with WHERE and its operators
  • Sorting with ORDER BY
  • Limiting results
  • DISTINCT and aliases
  • The order SQL actually runs a query in
On this page

SELECT

SQL
SELECT name, city FROM customers WHERE city = 'London' ORDER BY name;
namecity
Aisha KhanLondon
Chen LiLondon
  • SELECT lists the columns you want. SELECT * means all columns: fine for exploring, but in application code name the columns (less data, and code does not break when columns are added).
  • FROM names the table.
  • WHERE keeps only rows where the condition is true.
  • ORDER BY sorts. Without ORDER BY, the order of rows is not guaranteed, even if it looks stable.

WHERE operators

OperatorExample
=, <> (or !=), <, >, <=, >=price_pence >= 1000
AND, OR, NOTcategory = 'Stationery' OR price_pence > 3000
IN (...)status IN ('paid', 'pending')
BETWEEN a AND bInclusive at both ends
LIKE / ILIKEPattern match: % any characters, _ one character. ILIKE ignores case (PostgreSQL)
IS NULL / IS NOT NULLMissing values (never = NULL, Lesson 219)
SQL
SELECT name, price_pence FROM products
WHERE category = 'Stationery' OR price_pence > 3000
ORDER BY price_pence DESC;
nameprice_pence
Kettle3499
Pen Set1250
Notebook450
SQL
SELECT name, price_pence FROM products WHERE price_pence BETWEEN 800 AND 1500 ORDER BY price_pence;
nameprice_pence
Mug899
Pen Set1250
SQL
SELECT name FROM customers WHERE name LIKE 'A%' OR name ILIKE '%li';
name
Aisha Khan
Chen Li

Use brackets when mixing AND and OR: AND binds tighter, so a OR b AND c means a OR (b AND c).

A NULL trap already

SQL
SELECT name FROM customers WHERE city <> 'London';
name
Ben Smith
Eve Jones

Dara Patel is missing, although her city is certainly not London. Her city is NULL (unknown), and NULL <> 'London' is not true, it is unknown, so WHERE drops the row. Lesson 219 explains this fully. To include her: WHERE city <> 'London' OR city IS NULL, or WHERE city IS DISTINCT FROM 'London'.

ORDER BY and LIMIT

SQL
SELECT name, price_pence FROM products ORDER BY price_pence DESC LIMIT 2;
nameprice_pence
Kettle3499
Desk Lamp2999
  • ASC (default) or DESC; sort by several columns: ORDER BY category, price_pence DESC.
  • LIMIT n returns at most n rows; OFFSET m skips m rows first (and has problems for paging, Lesson 222). The SQL standard form is FETCH FIRST 2 ROWS ONLY; SQL Server uses TOP 2.
  • NULLs sort last in ascending order in PostgreSQL (NULLS FIRST / NULLS LAST changes it).

DISTINCT and aliases

SQL
SELECT DISTINCT category FROM products ORDER BY category;
category
Home
Kitchen
Stationery

An alias renames a column or table in the result: SELECT price_pence / 100.0 AS price_pounds FROM products p. Table aliases (p) make joins shorter (Lesson 215).

The logical order of a query

You write clauses in one order, but the database processes them in another. This explains many errors:

Written orderLogical processing order
1. SELECT1. FROM (and JOINs)
2. FROM2. WHERE
3. WHERE3. GROUP BY
4. GROUP BY4. HAVING
5. HAVING5. SELECT (and window functions)
6. ORDER BY6. DISTINCT
7. LIMIT7. ORDER BY
8. LIMIT / OFFSET

So you cannot use a SELECT alias in WHERE (WHERE runs before SELECT), but you can use it in ORDER BY. And WHERE cannot filter on aggregates like COUNT(*); that is what HAVING is for (Lesson 216). A classic interview question.

How to say it in an interview

"SELECT chooses columns, FROM the table, WHERE filters rows, ORDER BY sorts and LIMIT restricts the count; without ORDER BY the order is not guaranteed. WHERE supports comparisons, AND and OR with brackets, IN, BETWEEN, LIKE and IS NULL. Logically the database runs FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, then LIMIT, which is why a SELECT alias works in ORDER BY but not in WHERE. I also remember that comparisons with NULL are unknown, so not-equal filters silently drop NULL rows."

Key words

WordMeaning
SELECT / FROM / WHEREColumns / table / row filter
ORDER BYSort the result
LIMIT / OFFSETReturn at most n rows / skip rows
LIKE / ILIKEPattern matching / case-insensitive pattern matching
DISTINCTRemove duplicate rows
AliasA temporary name for a column or table
Logical query orderThe order the database processes clauses

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.