Explain it simply
Explain it simply
This lesson adds no new theory. Just as a footballer practises penalties again and again before a match, you drill the basic queries until they feel natural. You use the Bookstore project's Books and Customers tables, so the data is already familiar.
Follow one rule for every task: write the query, write down how many rows you expect and in what order, and only then run it. Wherever your prediction and the result differ, there is something to learn.
Problem → Why → Solution
The problem: wrong results with no error
Look at a beginner's first attempts. They want the most expensive books first, but without DESC the cheapest book, Myanmar Sarpay, ends up on top. The search for Yangon customers writes "Yangon" in double quotes and fails with column "Yangon" does not exist.
The third query is the sneakiest. The original exercise asked for titles containing 'a', but all five titles contain an 'a', so the filter removes nothing. Five rows come back and the query seems to work, yet the condition was never really tested.
SELECT Title, Price FROM Books ORDER BY Price;
-- wanted highest first, got Myanmar Sarpay (5000.00) on top
SELECT CustomerName FROM Customers WHERE City = "Yangon";
-- ERROR: column "Yangon" does not exist
SELECT Title FROM Books WHERE Title LIKE '%a%';
-- 5 rows: every title has an "a", so the filter proves nothingWhy predicting first matters
SQL does exactly what you wrote and never says "I don't think you meant that". Syntax errors show up immediately, but logic errors hide behind results that look believable. Only a prediction made in advance lets you notice them.
Core concept: read a SELECT in stages
Every query in this set has the same shape: SELECT columns FROM table WHERE condition ORDER BY column. The order you write it in is not the order PostgreSQL runs it: FROM fetches the table, WHERE filters rows, SELECT picks columns, DISTINCT removes duplicates, and ORDER BY sorts last. When you predict a result, run the query in your head in that order.
1. WHERE tests each row for true or false
Price > 10000 keeps a row only when the condition is true. BETWEEN 10000 AND 14000 includes both ends (>= AND <=), and IN ('Yangon', 'Bago') is shorthand for several ORs. A condition that evaluates to NULL drops the row.
2. AND binds tighter than OR
PostgreSQL reads Price > 10000 OR Stock > 5 AND Price < 6000 as Price > 10000 OR (Stock > 5 AND Price < 6000). When in doubt, add parentheses.
3. LIKE is case-sensitive, ILIKE is not
% matches any number of characters and _ matches exactly one. In PostgreSQL Title LIKE '%wood%' misses 'Norwegian Wood' because of the capital W, while ILIKE '%wood%' finds it. ILIKE is PostgreSQL-only; elsewhere write LOWER(Title) LIKE '%wood%'.
4. Without ORDER BY, order is not guaranteed
ORDER BY defaults to ASC, lowest first. With no ORDER BY at all rows often come back in insertion order, but that is luck. A query like DISTINCT City can change its order after a data or plan change, so add ORDER BY. If two books could share a price, add a second sort key such as Title, so tied rows also come out in the same order every time you run the query.
- Read the task, write the query
- Predict row count and order
- Run it and compare
- If they differ, reread the condition
If a filter removes no rows, or all of them, suspect the test data.
General pattern
SELECT [DISTINCT] column_a, column_b
FROM table_name
WHERE column_a > value
AND column_b BETWEEN low AND high
AND column_c IN ('x', 'y')
AND text_col ILIKE '%part%'
ORDER BY column_a [ASC | DESC]
LIMIT n;Combine conditions in WHERE with AND/OR. ORDER BY defaults to ASC, and LIMIT comes after ORDER BY. String values take single quotes.
Sample answers to the four tasks
The tasks: (1) title and price of books above 10000, (2) every city customers live in, once each, (3) books whose title contains "wood" in any letter case, (4) all books, most expensive first. Write your own answers and predict the row counts before you look. Task 3 replaces the original "titles containing 'a'", because every book has an 'a' and that filter tests nothing. Tasks 1 and 2 gained an ORDER BY so the result is stable.
-- Task 1: books priced above 10000, cheapest first
SELECT Title, Price FROM Books WHERE Price > 10000 ORDER BY Price;
-- Task 2: each city once, alphabetically
SELECT DISTINCT City FROM Customers ORDER BY City;
-- Task 3: titles containing "wood", in any letter case
SELECT Title FROM Books WHERE Title ILIKE '%wood%';
-- Task 4: every book, most expensive first
SELECT Title, Price FROM Books ORDER BY Price DESC;Code breakdown
- Strictly greater than
WHERE Price > 10000Because it is >, a book priced exactly 10000 would be excluded; use >= to include it. Only Myanmar Sarpay (5000) is removed, leaving four rows.
- Remove duplicate cities
SELECT DISTINCT City FROM Customers ORDER BY City;Two of the three customers live in Yangon, so DISTINCT leaves two rows. With DISTINCT, the ORDER BY columns must appear in the SELECT list.
- Case-insensitive pattern
WHERE Title ILIKE '%wood%'Matches wood, Wood or WOOD anywhere in the title. With LIKE '%wood%' you would get zero rows.
- Highest first
ORDER BY Price DESC;DESC sorts from highest to lowest; forget it and the default ASC puts 5000 on top.
-- Task 1
title | price
--------------------+----------
Norwegian Wood | 12000.00
Kafka on the Shore | 13000.00
Fantastic Beasts | 14000.00
Harry Potter | 15000.00
(4 rows)
-- Task 2
city
----------
Mandalay
Yangon
(2 rows)
-- Task 3
title
----------------
Norwegian Wood
(1 row)
-- Task 4
title | price
--------------------+----------
Harry Potter | 15000.00
Fantastic Beasts | 14000.00
Kafka on the Shore | 13000.00
Norwegian Wood | 12000.00
Myanmar Sarpay | 5000.00
(5 rows)Bonus drill: when a NULL shows up
The sample data has no NULLs, which makes this practice set easy. Add a new customer, Mya Mya, whose city is not known yet, and look for customers who do not live in Yangon. City <> 'Yangon' returns only Ko Ko: NULL <> 'Yangon' is not true but NULL (unknown), so Mya Mya disappears.
To treat NULL as "different" too, use PostgreSQL's IS DISTINCT FROM, or add OR City IS NULL. DISTINCT, on the other hand, treats all NULLs as one value, so the result gains one empty row, and in ascending order PostgreSQL puts NULL last.
INSERT INTO Customers VALUES (4, 'Mya Mya', 'myamya@mail.com', NULL);
SELECT CustomerName FROM Customers WHERE City <> 'Yangon';
-- Ko Ko only (Mya Mya's NULL city is "unknown", not "different")
SELECT CustomerName FROM Customers
WHERE City IS DISTINCT FROM 'Yangon'
ORDER BY CustomerName;
-- Ko Ko, Mya Mya
SELECT DISTINCT City FROM Customers ORDER BY City;
-- Mandalay, Yangon, then one empty (NULL) row lastIn real projects
In real projects
Every online shop's product listing page is built from the queries in this lesson: a price-range filter (BETWEEN), a category picker (IN), a search box (ILIKE) and a "price: high to low" sort button (ORDER BY ... DESC). The city dropdown on a shipping form is often filled with SELECT DISTINCT City.
Experienced developers prepare test data on purpose: they make sure a filter keeps some rows and removes others, include boundary values such as exactly 10000, and add NULLs. Analysts likewise make a habit of predicting the row count before sending a report out. When the count surprises them, they stop and investigate before anyone makes a decision based on the numbers.
Common mistakes
Common mistakes
Forgetting DESC and thinking sorting is broken
ORDER BY Price is working; the default is ASC, so the cheapest book comes first. Whenever a task says "highest" or "newest", ask whether you need DESC.
Writing strings in double quotes
In PostgreSQL double quotes are for identifiers (table and column names). WHERE City = "Yangon" looks for a column named Yangon and fails. Write values in single quotes, like 'Yangon'.
Mixing AND and OR without parentheses
WHERE Price > 10000 OR Stock > 5 AND Price < 6000 returns the four expensive books plus Myanmar Sarpay, because AND is evaluated first. If you mean (A OR B) AND C, write the parentheses yourself.
Trusting a filter that removes nothing
If a condition like LIKE '%a%' matches every row in the data, a mistake in it can never show. Choose test cases where some rows stay and some are removed.
Mini challenge
Practice set 1 - three bonus tasks
Write one query per task. Before running anything, write your predicted row count in a comment.
- A: Title, Price and Stock of books priced 10000 to 14000 inclusive that are in stock, most expensive first
- B: names and emails of customers in Yangon or Bago, using IN, sorted by name
- C: Title and Price of the two most expensive books
-- Task A (predicted rows: ?)
SELECT Title, Price, Stock
FROM Books
-- TODO: price range including both ends, and only books in stock
-- TODO: most expensive first
;
-- Task B (predicted rows: ?)
SELECT CustomerName, Email
FROM Customers
-- TODO: city is Yangon or Bago (use IN), sorted by name
;
-- Task C (predicted rows: 2)
-- TODO: the two most expensive booksExpected: A: Kafka on the Shore (13000.00, 5) and Norwegian Wood (12000.00, 8). B: Hla Hla and Su Su. C: Harry Potter (15000.00) and Fantastic Beasts (14000.00).
Show hint
Fantastic Beasts is inside the price range but has Stock 0, so it must not appear in Task A. No customer lives in Bago yet, but listing it in IN is not an error. For Task C combine ORDER BY ... DESC with LIMIT.
Show solution
-- Task A (predicted rows: 2)
SELECT Title, Price, Stock
FROM Books
WHERE Price BETWEEN 10000 AND 14000
AND Stock > 0
ORDER BY Price DESC;
-- Task B (predicted rows: 2)
SELECT CustomerName, Email
FROM Customers
WHERE City IN ('Yangon', 'Bago')
ORDER BY CustomerName;
-- Task C (predicted rows: 2)
SELECT Title, Price
FROM Books
ORDER BY Price DESC
LIMIT 2;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Predict the row count and order before running a query
- BETWEEN includes its ends, IN is shorthand for OR, and AND binds before OR
- In PostgreSQL LIKE is case-sensitive and ILIKE is not
- Single quotes for strings, double quotes for identifiers
- Whenever order matters, always add ORDER BY
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group