15 min read
What is SQL: SELECT queries from scratch
In one sentence: SQL is the language you use to talk to a database: you write what data you want, not how to find it, and it answers with a table. With SELECT you read, and with INSERT, UPDATE and DELETE you add, change and delete rows.
What you will learn
- Read a table as rows and columns with their type, and ask for its data with SELECT, WHERE, ORDER BY and LIMIT.
- Explain what NULL is and why you search for it with IS NULL and never with = NULL.
- Add, change and delete rows with INSERT, UPDATE and DELETE, and read how many each command touched.
- Avoid the UPDATE or DELETE without WHERE, with the habit of trying the SELECT first.
Before you start, read: 00-introduction.md
The problem
Section titled “The problem”Luis packs the shop’s parcels every morning. He wants to know which orders are still pending, from oldest to newest. In a spreadsheet he’d put a filter on the “status” column and sort by date, with a couple of clicks.
Since the introduction, the shop’s data lives in PostgreSQL. A DatabaseA program that stores data in an organized way and lets you search and change it quickly, even when many people use it at once. The backend keeps in it whatever needs to last.Go to definition has no buttons: you ask it in writing, in a language it understands. That language is SQLSQL stands for Structured Query Language.The language for asking a database to read, add, change or delete the data in its tables. It reads almost like an English sentence, such as SELECT name FROM products, and it says what data you want, not how to find it.Go to definition, and it’s the same one your server will use when someone asks for GET /v2/orders?status=pending.
Writing has a risk a click doesn’t. With one line of SQL you can change one order or all 40,000 at once, and PostgreSQL doesn’t ask if you’re sure. In this lesson you learn to read data, to change it and to avoid that scare.
The analogy
Section titled “The analogy”The analogy
Think of a city hall’s records office. You don’t go in and search the shelves: you fill in a slip at the counter. “From the orders box, I want the number and the date. Only the pending ones. From oldest to newest. Five at most.”
The archivist knows where each box is and the shortest way to it. You say what you want, not how to find it, and she hands you a photocopy with just that. SQL is that slip, and PostgreSQL, the archivist.
Where the analogy breaks down
- An archivist understands “Pending” even if it’s capitalized. PostgreSQL compares letter by letter:
'Pending'and'pending'are different texts, and it doesn’t warn you that it found nothing. - With SQL you can also write “throw out everything in this box.” Nobody asks if you’re sure, and there’s no trash can.
- The answer to a
SELECTis always a table, even if it holds a single value.
How it really works
Section titled “How it really works”You can try every query in this section in the playground in Try it, or in psql (open psql -d shop, as in the introduction). The outputs are from PostgreSQL 18.6, with the data from shop.sql freshly loaded.
A table is a spreadsheet with rules
Section titled “A table is a spreadsheet with rules”This is the shop’s products table:
SELECT * FROM products; id | name | price_cents----+---------+------------- 1 | T-shirt | 2000 2 | Mug | 850 3 | Hoodie | 3500 4 | Cap | 1500(4 rows)A TableWhere a database stores one kind of thing, such as products. Each row is one of those things and each column a piece of data they all have, with its type (a number, some text, a date). It looks like a spreadsheet, but it doesn’t accept data of the wrong type.Go to definition stores one kind of thing, like the products. Each row is one of those things (the Mug), and each column, a piece of data they all have (its name). So far, a spreadsheet.
The difference is the rules. Each column has a type, and PostgreSQL won’t let you put in another one. In a spreadsheet you can write “free” in the price column; here, you can’t. These are the types you’ll see in the shop:
| Type | What it stores | In the shop |
|---|---|---|
integer |
A whole number | id, price_cents, quantity |
text |
Text, of any length | name, status |
timestamptz |
An instant: date and time, which PostgreSQL writes in a time zone | created_at, when an order was placed |
Prices are in cents: €8.50 is 850. Your project has stored them that way since lesson 4 of Phase 4: v2 returns them in priceCents, and v1 still turns them into euros, in price. Decimals aren’t always exact in a computer (lesson 2 of Phase 3), and a whole number is.
The shop has four tables: products, orders, categories and product_categories. This lesson uses the first two. This is how the 25 orders start:
| id | product_id | quantity | status | created_at |
|---|---|---|---|---|
| 1 | 2 | 2 | shipped | 2026-10-01 09:00:00+00 |
| 2 | 3 | 3 | shipped | 2026-10-01 16:00:00+00 |
| 3 | 1 | 4 | shipped | 2026-10-01 23:00:00+00 |
product_id says which product each order is for: order 1 is for the Mug, product 2. You’ll see how to put the two tables together in lesson 2, “JOIN”.
SELECT and FROM: which columns and from which table
Section titled “SELECT and FROM: which columns and from which table”A QueryA command written in SQL for a database. Mostly the ones that ask for data (SELECT), whose answer is another table, although the ones that add, change or delete rows are called that too.Go to definition is a command written in SQL. The shortest one asks for some columns of a table:
SELECT name, price_cents FROM products; name | price_cents---------+------------- T-shirt | 2000 Mug | 850 Hoodie | 3500 Cap | 1500(4 rows)Word by word:
SELECTsays which columns you want, separated by commas. With*, all of them.FROM productssays from which table.;ends the command. Inpsqlit’s required: without it,psqlthinks you haven’t finished and waits for more lines.(4 rows)is added bypsql: how many rows the answer brings.
SQL’s words go in capitals by convention, to tell them apart from the names; select works too. Table and column names go in lowercase with _ between words, because PostgreSQL turns names that aren’t in quotes into lowercase.
WHERE: only the rows that meet a condition
Section titled “WHERE: only the rows that meet a condition”For Luis’s pending orders, a filter is missing:
SELECT id, quantity, status FROM orders WHERE status = 'pending'; id | quantity | status----+----------+--------- 21 | 2 | pending 22 | 3 | pending 23 | 4 | pending 24 | 1 | pending 25 | 2 | pending(5 rows)WHEREgoes afterFROMand carries a condition. PostgreSQL looks at each row and keeps the ones that meet it.=compares, with a single sign (in JavaScript it was three,===). Not equal is<>, and there are also<,>,<=and>=.'pending'is text, and text goes in single quotes. Numbers, without quotes:quantity >= 3.
Double quotes exist, but they’re for column and table names. If you use them for text, PostgreSQL looks for a column with that name:
SELECT * FROM products WHERE name = "Mug";ERROR: column "Mug" does not existLINE 1: SELECT * FROM products WHERE name = "Mug"; ^ERROR: says what failed (the column “Mug” doesn’t exist), and the ^ points to where.
Dates can be compared too, written as text: WHERE created_at >= '2026-10-08' gives orders 24 and 25.
AND and OR: several conditions
Section titled “AND and OR: several conditions”AND requires both conditions to be met; OR, at least one:
SELECT id, product_id, quantity FROM orders WHERE status = 'paid' AND quantity >= 3; id | product_id | quantity----+------------+---------- 14 | 3 | 3 15 | 1 | 4 18 | 1 | 3 19 | 2 | 4(4 rows)Paid, and 3 units or more. With OR, you’d get all the paid ones and, on top of that, all the ones of 3 or more, whatever their status.
If you mix the two, AND goes before OR, like multiplication before addition. Use parentheses so that what you mean wins: WHERE status = 'paid' AND (product_id = 1 OR quantity >= 4) means the paid orders that are for the T-shirt or have 4 units, and gives orders 15, 18 and 19.
ORDER BY and LIMIT: in what order and how many
Section titled “ORDER BY and LIMIT: in what order and how many”SELECT name, price_cents FROM productsWHERE price_cents > 1000ORDER BY price_cents DESCLIMIT 2; name | price_cents---------+------------- Hoodie | 3500 T-shirt | 2000(2 rows)A query can take up several lines: it ends at the ;.
ORDER BY price_centssorts by that column, from lowest to highest.DESC(for descending) turns it around: from highest to lowest.LIMIT 2keeps the first two rows.
You can read it as a chain, where each step works with what the previous one leaves:
- FROM products4 rows
WHERE price_cents > 1000
- T-shirt, Hoodie and Cap3 rows
ORDER BY price_cents DESC
- Hoodie, T-shirt and Capthe same ones, in order
LIMIT 2
- Hoodie and T-shirt2 rows
The parts are always written in this order: SELECT, FROM, WHERE, ORDER BY and LIMIT. The order in which PostgreSQL really runs them has some subtleties, which you’ll see in lesson 3, “GROUP BY”.
Without ORDER BY, the order of the rows isn’t guaranteed. Today they come out by id because nobody has touched the tables, but changing one row is enough for that to stop: you’ll see it in Try it. A LIMIT without ORDER BY gives you any rows at all.
NULL: the missing value
Section titled “NULL: the missing value”Imagine a customers table with a phone column, and someone who didn’t give theirs. That cell doesn’t hold a 0 or an empty text: it holds NULL, which means “unknown.”
NULL changes how comparisons work. Is one unknown phone equal to another unknown one? That’s unknown too:
SELECT NULL = NULL AS equal, NULL IS NULL AS is_null; equal | is_null-------+--------- | t(1 row)AS equalgives the column of the answer a name.NULL = NULLdoesn’t give true: it givesNULL, another “unknown.”psqlwrites it as a blank; the playground writesNULL.NULL IS NULLgivest, true (false isf). True or false is another type,boolean.
WHERE only keeps the rows whose condition is true, and “unknown” isn’t true. That’s why WHERE phone = NULL never finds anything, even if there are a hundred customers without a phone. You write WHERE phone IS NULL, and the opposite, IS NOT NULL.
In the shop, every column is required: none allows NULL. You’ll see it when you add a product without a price, in the next section. And in lesson 2, “JOIN”, NULLs will show up where you least expect them: in the Cap, which nobody has ever ordered.
INSERT: adding a row
Section titled “INSERT: adding a row”Ana wants to sell a tote bag for €12:
INSERT INTO products (name, price_cents) VALUES ('Bag', 1200);INSERT 0 1INSERT INTO productssays into which table.(name, price_cents)are the columns you’re going to give, andVALUES (…), their values, in the same order.- You don’t give the
id: PostgreSQL puts in the next number. You’ll see how in lesson 2. INSERT 0 1says that 1 row went in. The0is left over from old versions of PostgreSQL, and it’s always 0.
Check it with SELECT * FROM products WHERE name = 'Bag';: it comes out with id 5.
If a required value is missing, the row doesn’t go in:
INSERT INTO products (name) VALUES ('Keychain');ERROR: null value in column "price_cents" of relation "products" violates not-null constraintDETAIL: Failing row contains (6, Keychain, null).The column you don’t give is left as NULL, and the table says NOT NULL. DETAIL: shows the row that would have gone in. You’ll design those rules of each column, the ConstraintA rule the database checks on every change, such as the price being greater than zero or no two categories having the same name. Data that breaks it doesn’t get in, wherever it comes from.Go to definition, in lesson 4, “Modeling”.
Notice the 6 in DETAIL: the attempt used up that number even though it failed. The next product to go in will be 7. Ids don’t have to be consecutive.
UPDATE and DELETE: changing and deleting rows
Section titled “UPDATE and DELETE: changing and deleting rows”The bag goes down to €10:
UPDATE products SET price_cents = 1000 WHERE name = 'Bag';UPDATE 1UPDATE productssays which table.SET price_cents = 1000says which column changes and to what value. Several go separated by commas.WHERE name = 'Bag'says which rows. It’s the sameWHEREas inSELECT.UPDATE 1: it changed 1 row. Always look at that number: it’s how many rows you touched.
In the end, Ana doesn’t sell it:
DELETE FROM products WHERE name = 'Bag';DELETE 1DELETE FROM products deletes whole rows, the ones that meet the WHERE. If you repeat it, the answer is DELETE 0: no row met the condition. It isn’t an error; PostgreSQL is telling you it found nothing to delete.
The classic mistake: an UPDATE or a DELETE without WHERE
Section titled “The classic mistake: an UPDATE or a DELETE without WHERE”The WHERE is optional. Without it, SELECT reads every row, and UPDATE and DELETE change or delete all of them.
Imagine Luis wants to cancel order 17 and, in a hurry, writes this:
UPDATE orders SET status = 'cancelled';UPDATE 25All 25 of the shop’s orders, cancelled. PostgreSQL didn’t ask anything, and in psql there’s no undo: the change is saved as soon as the command finishes. With DELETE FROM orders; it would be worse: the orders would be gone. It’s SQL’s classic mistake, and it happens to people with years of experience too. Don’t try it in psql: in Try it you’ll do it in the playground, which resets with a button.
Two habits prevent it:
- Write the
SELECTfirst with theWHEREyou’re going to use:SELECT * FROM orders WHERE id = 17;. If the rows you want to change come out, and only those, swapSELECT *forUPDATE orders SET …or forDELETE, without touching theWHERE. - Write the
WHEREbefore the rest. In the playground and in many programs, Ctrl + Enter runs whatever is written, even if you haven’t finished. If the command goes out half done, better that it’s missing theSETthan theWHERE:UPDATE orders WHERE id = 17;givesERROR: syntax error at or near "WHERE", a syntax error, and changes nothing.
And read the number in the answer: if you expected UPDATE 1 and get UPDATE 25, you know what happened. In lesson 8, “Transactions”, you’ll see one more safety net: make the change, look at the result and undo it if it wasn’t what you wanted.
Try it
Section titled “Try it”The goal: put together Luis’s list, find the biggest pending order and then break the data on purpose and fix it.
Luis’s list
Section titled “Luis’s list”This playground is a real PostgreSQL inside your browser, with the shop’s data. The first time, it downloads about 5 MB. Press “Run”:
playground · PostgreSQL in your browser
A real PostgreSQL, with the shop’s data. What you change stays on this page.
Now change it: the paid ones instead of the pending ones, from newest to oldest (DESC), and only three (LIMIT 3). If you get an error, read the line with the ^: it’s almost always a comma or a quote.
The same query, in your terminal. Open psql -d shop and, at the shop=> prompt, type:
Luis’s list, in psql
SELECT id, product_id, quantity, created_atFROM ordersWHERE status = 'pending'ORDER BY created_at;What you will see:
id | product_id | quantity | created_at----+------------+----------+------------------------21 | 1 | 2 | 2026-10-07 05:00:00+0022 | 2 | 3 | 2026-10-07 12:00:00+0023 | 3 | 4 | 2026-10-07 19:00:00+0024 | 1 | 1 | 2026-10-08 02:00:00+0025 | 2 | 2 | 2026-10-08 09:00:00+00(5 rows)Look at the end of created_at: +00 is the time zone, UTC, the one you gave the shop role in the introduction. If the first one shows something like 2026-10-07 01:00:00-04, you’re missing that setting: it’s the same instant, in New York time. If you get relation "orders" does not exist, you haven’t loaded shop.sql: go back to the introduction. You leave psql with \q.
Challenge: which pending order has the most units? Write a query that returns only that one.Show answer
Sort by quantity from highest to lowest and keep the first one:
SELECT id, quantity FROM ordersWHERE status = 'pending'ORDER BY quantity DESCLIMIT 1; id | quantity----+---------- 23 | 4(1 row)Order 23, with 4 units. Without the WHERE, the paid and shipped ones would have competed too.
Change one order, and then all of them
Section titled “Change one order, and then all of them”Luis gets paid for order 21. First the SELECT, then the change, and then the SELECT again to check it. The playground runs the three commands in a row and shows the answer to each one:
playground · PostgreSQL in your browser
A real PostgreSQL, with the shop’s data. What you change stays on this page.
Look at “Done: 1 row changed.”: it’s psql’s UPDATE 1. Now delete WHERE id = 21 from the UPDATE and run it again: “Done: 25 rows changed.”, and the last SELECT says paid, like the other 24. Press “Reset data” to go back to the shop as it was at the start. Your database doesn’t have that button.
In psql, the same:
Order 21, paid
SELECT id, status FROM orders WHERE id = 21;UPDATE orders SET status = 'paid' WHERE id = 21;SELECT id, status FROM orders WHERE id = 21;What you will see:
id | status----+---------21 | pending(1 row)
UPDATE 1id | status----+--------21 | paid(1 row)Before and after the change. If you get UPDATE 0, no order has id 21: you deleted rows in another test.
Now type SELECT id FROM orders;, without ORDER BY: 21 comes out last, after 25. PostgreSQL stored the changed row at the end, and without ORDER BY it gives them as it has them stored.
Before lesson 2, go back to the starting data: load shop.sql again as in the introduction, which drops the four tables and creates them again.
You have already seen it
Section titled “You have already seen it”- A spreadsheet’s filters are a
WHERE, and “sort Z to A”, anORDER BY … DESC. Google Sheets even has a function,QUERY, that’s written almost like SQL:=QUERY(A1:C10, "select A where C > 100"). - The Phase 4 API:
GET /v2/orders?status=pending&limit=5is aWHEREand aLIMIT, andGET /v2/products?sort=-price, anORDER BY … DESC. In lesson 5, “Node and PostgreSQL”, the API turnsstatusandsortinto SQL, and in lesson 7, “Indexes”,limittoo. - Your phone: Android and iOS come with SQLite, a small database that keeps many apps’ data in a file. It speaks SQL too.
Common mistakes
Section titled “Common mistakes”- An
UPDATEor aDELETEwithoutWHERE. It changes or deletes every row. Write theSELECTfirst. - Text in double quotes.
"Mug"is the name of a column; the text is'Mug'. - Searching with
= NULL. It never finds anything: you writeIS NULL. - Trusting the order without
ORDER BY. The rows can come out in any order, and aLIMITwithoutORDER BYgives you any rows at all. - Capitals in the data.
status = 'Pending'gives(0 rows), with no error: the data sayspending. - Mixing
ANDandORwithout parentheses.ANDgoes first, and the condition ends up being a different one.
Summary
Section titled “Summary”- A table stores rows, one per thing, and columns, one per piece of data, each with its type:
integer,text,timestamptz. SELECT columns FROM table WHERE condition ORDER BY column LIMIT nreads data, written in that order. Text goes in single quotes, and withoutORDER BYthere’s no guaranteed order.NULLis “unknown”: comparing it with=givesNULL, and you search for it withIS NULL.INSERTadds rows,UPDATEchanges them andDELETEdeletes them. The answer says how many rows it touched: read it.- Before an
UPDATEor aDELETE, run theSELECTwith the sameWHERE.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- PostgreSQL’s SQL tutorial: the official chapter to get started, with
SELECT,INSERT,UPDATEandDELETE. - SELECT (PostgreSQL documentation): everything it accepts, for when you want to go further.
- Comparison operators and NULL (PostgreSQL documentation): the comparisons, and why
= NULLdoesn’t work. - SQLBolt: short SQL exercises in the browser, one per idea.