Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 02 / Stage 1

Reading data

Goal: Get exactly the rows and columns you want from one table — filtering, sorting, de-duplicating and limiting, and knowing the order PostgreSQL actually evaluates your query in. Time: ~1.5 hours

What you will learn

  • SELECT and FROM, and what * really means
  • Calculated columns, AS aliases, and double-quoted names
  • Filtering with WHERE and the comparison operators
  • Combining conditions: AND, OR, NOT and parentheses
  • Shortcuts: IN, BETWEEN, LIKE and ILIKE
  • DISTINCT, and Postgres's own DISTINCT ON
  • Sorting with ORDER BY, including where NULLs go
  • Top-N and paging: LIMIT, OFFSET, FETCH FIRST ... WITH TIES
  • The logical order a query is evaluated in — and the alias trap it explains

Every query here runs against shopdb. Data drifted while experimenting? psql -d shopdb -f shopdb.sql rebuilds it.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

The store manager's question list. Try each in psql against shopdb first; then check the solution.


Exercise 1: The budget shelf

What to do: List the name, price and stock of every product that costs under 100 and is actually in stock, cheapest first.

Sample output:

        name        | price | stock 
--------------------+-------+-------
 USB-C Cable        | 15.00 |   200
 SQL for Beginners  | 35.00 |   100
 Desk Lamp          | 45.00 |    12
 Postgres Deep Dive | 55.00 |    60
 Chef Knife         | 80.00 |    30
(5 rows)

💡 Hint: two conditions joined with AND; ORDER BY price.


Show the solution to Exercise 1
-- Exercise 1: The budget shelf
SELECT name, price, stock
FROM products
WHERE price < 100 AND stock > 0
ORDER BY price;

Exercise 2: Phone hunt

What to do: A customer asks "what phones do you have?" — find every product whose name contains phone, in any letter case. Then check: would LIKE '%phone%' have found them?

Sample output:

    name    | price  
------------+--------
 Phone X    | 799.00
 Phone Lite | 399.00
(2 rows)

💡 Hint: ILIKE with % on both sides. (The LIKE version finds nothing — capital P.)


Show the solution to Exercise 2
-- Exercise 2: Phone hunt
-- ILIKE folds case; plain LIKE '%phone%' misses the capital P names.
SELECT name, price FROM products WHERE name ILIKE '%phone%';
-- Proof that LIKE finds nothing here:
SELECT count(*) AS like_matches FROM products WHERE name LIKE '%phone%';

Exercise 3: Where do our customers live?

What to do: One query: every distinct city, including the "no city on file" entry, with the missing one shown first.

Sample output:

  city   
---------
 
 Chennai
 Delhi
 London
 Pune
(5 rows)

💡 Hint: DISTINCT, then ORDER BY city NULLS FIRST.


Show the solution to Exercise 3
-- Exercise 3: Where do our customers live?
SELECT DISTINCT city FROM customers ORDER BY city NULLS FIRST;

Exercise 4: The newest faces

What to do: Show the first name and signup date of the three most recently signed-up customers.

Sample output:

 first_name | signup_date 
------------+-------------
 Vikram     | 2025-04-02
 Sara       | 2025-03-15
 John       | 2025-02-28
(3 rows)

💡 Hint: ORDER BY ... DESC, LIMIT 3.


Show the solution to Exercise 4
-- Exercise 4: The newest faces
SELECT first_name, signup_date
FROM customers
ORDER BY signup_date DESC
LIMIT 3;

Exercise 5: Precedence repair

Scenario: This query is supposed to show laptops and phones under 800, but it returns a 1200.00 laptop:

SELECT name, price FROM products
WHERE category_id = 4 OR category_id = 5 AND price < 800;

What to do: First explain the bug in one sentence (which condition does the AND actually attach to?). Then fix it two ways: once with parentheses, once with IN.

Sample output (both fixes):

    name    | price  
------------+--------
 Phone X    | 799.00
 Phone Lite | 399.00
(2 rows)

💡 Hint: (category_id = 4 OR category_id = 5) AND price < 800, or category_id IN (4, 5) AND price < 800.


Show the solution to Exercise 5
-- Exercise 5: Precedence repair
-- The bug: AND binds tighter than OR, so the price condition applied
-- only to category 5 and every category-4 product sailed through.
SELECT name, price FROM products
WHERE (category_id = 4 OR category_id = 5) AND price < 800;
-- Same fix, tidier with IN:
SELECT name, price FROM products
WHERE category_id IN (4, 5) AND price < 800;

Exercise 6: Shelf value, fixed

Scenario: This fails: SELECT name, price * stock AS shelf_value FROM products WHERE shelf_value > 10000; What to do: Explain why in one sentence, then make it work, highest shelf value first.

Sample output:

     name      | shelf_value 
---------------+-------------
 Phone X       |    19975.00
 Laptop Pro 14 |    18000.00
 Phone Lite    |    15960.00
(3 rows)

💡 Hint: WHERE runs before SELECT — repeat the expression. ORDER BY may use the alias.


Show the solution to Exercise 6
-- Exercise 6: Shelf value, fixed
-- WHERE is evaluated before SELECT, so the alias doesn't exist yet;
-- repeat the expression in WHERE. ORDER BY runs after SELECT, so the
-- alias is fine there.
SELECT name, price * stock AS shelf_value
FROM products
WHERE price * stock > 10000
ORDER BY shelf_value DESC;

Exercise 7: One per supplier

What to do: Using DISTINCT ON, show each supplier's single most expensive product: supplier_id, product name, price. Skip products with no supplier.

Sample output:

 supplier_id |        name        |  price  
-------------+--------------------+---------
           1 | Laptop Pro 14      | 1200.00
           2 | Postgres Deep Dive |   55.00
           3 | Coffee Maker       |  120.00
(3 rows)

💡 Hint: DISTINCT ON (supplier_id) with ORDER BY supplier_id, price DESC, and a WHERE supplier_id IS NOT NULL. (IS NOT NULL is formally Part 3 material — consider this a preview.)


Show the solution to Exercise 7
-- Exercise 7: One per supplier
-- ORDER BY starts with the DISTINCT ON column; price DESC decides the winner.
SELECT DISTINCT ON (supplier_id)
       supplier_id, name, price
FROM products
WHERE supplier_id IS NOT NULL
ORDER BY supplier_id, price DESC;

Exercise 8: Page two

What to do: The site shows products 3 per page, priciest first. Write the query for page 2 — twice: once with LIMIT/OFFSET, once with FETCH FIRST.

Sample output:

     name     | price  
--------------+--------
 Phone Lite   | 399.00
 Coffee Maker | 120.00
 Chef Knife   |  80.00
(3 rows)

💡 Hint: skip 3, take 3: OFFSET 3 LIMIT 3 / OFFSET 3 ROWS FETCH FIRST 3 ROWS ONLY.

Show the solution to Exercise 8
-- Exercise 8: Page two
SELECT name, price FROM products
ORDER BY price DESC
LIMIT 3 OFFSET 3;
-- Standard spelling, same result:
SELECT name, price FROM products
ORDER BY price DESC
OFFSET 3 ROWS FETCH FIRST 3 ROWS ONLY;

Common mistakes

Mistake What happens Fix
Using a SELECT alias in WHERE column does not exist Repeat the expression in WHERE
Mixing AND and OR without parentheses Silently wrong rows (AND binds tighter) Parenthesise the OR part
LIKE 'phone%' missing Phone X LIKE is case-sensitive ILIKE, or lower(name) LIKE
Top-N without ORDER BY Arbitrary n rows LIMIT only means "top" with ORDER BY
Double quotes around text values column "..." does not exist Single quotes for values
Expecting city <> 'Pune' to include NULL cities NULL rows match neither = nor <> IS NULL — the Part 3 lesson

Quick recap

  • SELECT columns FROM table is the base shape; name your columns in real code, and build calculated columns from expressions with AS.
  • WHERE filters rows with =, <>, <, >, <=, >=; AND/OR/NOT combine; parenthesise mixed AND/OR.
  • Use IN for lists, BETWEEN for inclusive ranges, and LIKE/ILIKE for patterns built from % and _.
  • DISTINCT de-duplicates values; DISTINCT ON keeps one row per group (Postgres-only).
  • ORDER BY is the only row-order guarantee; NULLs sort last ascending and first descending, and NULLS FIRST/LAST overrides that.
  • LIMIT/OFFSET and standard FETCH FIRST ... WITH TIES cap results.
  • Evaluation order FROM → WHERE → ... → SELECT → ORDER BY → LIMIT explains the alias trap.

Checklist

Before Part 3, make sure you can:

  • Pull exactly the columns you want, with calculated columns named via AS.
  • Write a WHERE mixing AND/OR correctly with parentheses.
  • Use IN, BETWEEN and ILIKE without looking them up.
  • Explain where NULLs sort, and force them to the top.
  • Write a top-N query properly (ORDER BY + LIMIT), and page with OFFSET.
  • Recite the logical evaluation order, and explain the alias-in-WHERE error with it.

Read more: the official queries chapter and the SELECT reference.

Search the guide