your first query
SELECT, FROM, a semicolon. what the result grid is telling you, and why you said what, not how.
- address
- everything.start.first_query
- part
- part 1, start here
- chapter
- chapter 4 of 7
- reading time
- 7 min
a query is a question, and the answer is always a table. SELECT says which columns you want, FROM says which table, WHERE (optional) says which rows, and a semicolon ends it.
you describe what you want. postgres decides how to get it.
the picture
you know how in most programming languages you tell the computer every step: open this, loop over that, if this then that? SQL doesn't work that way, and it's the first thing that feels strange.
think of ordering at a restaurant. the menu is the schema (what tables and columns exist). your order is the query ("the soup, no onions"). the kitchen is the planner and executor: they decide which pot, which burner, in what order. you never walk into the kitchen. you get a plate, and the plate is always the same shape: a table.
here's a whole query. step through its parts:
now run it. this is a real postgres, in your browser, on the shop's real data:
SELECT name, city
FROM customers
WHERE id = 42;| nametext | citytext |
|---|---|
| Ada Lovelace | London |
that's Ada. she's customer 42 on every page of this book.
smaller than that
a SELECT doesn't even need a table. this is the smallest query there is, and it's a fine way to check that a connection works:
SELECT 1;| ?column?int4 |
|---|
| 1 |
the select list can hold any expression, and AS names the column it makes:
SELECT 'hello' AS greeting, 6 * 7 AS answer, upper('ada') AS shouting;| greetingtext | answerint4 | shoutingtext |
|---|---|---|
| hello | 42 | ADA |
and * means every column, in the order the table declares them. ORDER BY id sorts the rows and LIMIT 5 keeps the first five; both get their own chapters later.
SELECT *
FROM customers
ORDER BY id
LIMIT 5;| idint4 | nametext | emailtext | citytext | countrychar | created_attimestamptz |
|---|---|---|---|---|---|
| 1 | Maya Chen | maya.chen@example.com | San Francisco | US | 2024-01-01 09:12:00+00 |
| 2 | Grace Okafor | null | Lagos | NG | 2024-01-02 14:40:00+00 |
| 3 | Sam Lee | sam.lee@example.com | Toronto | CA | 2024-01-03 08:05:00+00 |
| 4 | Zoë Martin | Zoe.Martin@Example.com | Paris | FR | 2024-01-03 19:30:00+00 |
| 5 | Zoe Martin | zoe.martin@example.com | Lyon | FR | 2024-01-04 11:11:00+00 |
* is handy for looking around. in a program, name the columns: it's clearer, and it doesn't change under you when someone adds one. picking columns has the rest.
reading the result grid
the answer comes back as a grid, drawn the way psql draws one (more on psql in psql and a real server). there's more in it than it looks:
- SELECT id, name, email, city
- FROM customers
- WHERE id IN (2, 10, 11, 42)
- ORDER BY id;
| idint4 | nametext | emailtext | citytext |
|---|---|---|---|
| 2 | Grace Okafor | null | Lagos |
| 10 | Null | null@example.com | Berlin |
| 11 | Ana Lima | null | '' |
| 42 | Ada Lovelace | ada@example.com | London |
Grace and Ana have no email on file. that's NULL: no value at all. it's drawn faint and italic so it can't be mistaken for text.
null faint and italic so it can't pass for text.the same query, for real (press run and check the figure didn't lie):
SELECT id, name, email, city
FROM customers
WHERE id IN (2, 10, 11, 42)
ORDER BY id;| idint4 | nametext | emailtext | citytext |
|---|---|---|---|
| 2 | Grace Okafor | null | Lagos |
| 10 | Null | null@example.com | Berlin |
| 11 | Ana Lima | null | '' |
| 42 | Ada Lovelace | ada@example.com | London |
NULL means "no value". '' is a value that happens to be empty. 'Null' is four letters. postgres keeps all three apart, and so should you: NULL and three-valued logic is the chapter about the first one, and you'll want it sooner than you think.
the semicolon
a semicolon ends one statement, so a block can hold several. each one runs on its own and gets its own result, numbered:
SELECT count(*) AS customers FROM customers;
SELECT count(*) AS orders FROM orders;
SELECT name FROM products WHERE id = 200;| customersint8 |
|---|
| 2000 |
| ordersint8 |
|---|
| 10000 |
| nametext |
|---|
| left-handed teapot |
(product 200 is the left-handed teapot. nobody has ever ordered it.) the semicolon after the last statement is optional here and in most tools. in psql it isn't: psql sends nothing until it sees one.
what, not how
- for row in read_all('customers'):
- if row.id == 42:
- print(row.name, row.city)
- break
- SELECT name, city
- FROM customers
- WHERE id = 42;
you can ask postgres how it decided to answer. EXPLAIN shows the plan instead of running the query:
EXPLAIN SELECT name, city FROM customers WHERE id = 42;
EXPLAIN SELECT name, city FROM customers WHERE city = 'London';two questions with the same shape, two different hows. for id = 42, postgres walks the index that came with the primary key straight to one row (Index Scan using customers_pkey). for London there's no index on city, and 159 customers live there, so it reads the whole table and filters (Seq Scan). you didn't choose either one. tomorrow, with an index on city or ten times the data, it might choose differently, and your query wouldn't change. reading EXPLAIN teaches the rest of those lines.
hover a stage.
spelling
keywords don't care about case, and neither do unquoted names: postgres folds them to lowercase before it looks them up. so this works:
select NAME from CUSTOMERS where ID = 42;| nametext |
|---|
| Ada Lovelace |
this book writes keywords in capitals and names in lowercase, because it's easier to read, not because postgres minds. double quotes, though, turn folding off, so "Customers" means a table with a capital C, and there isn't one:
SELECT name FROM "Customers";which brings up the one rule that bites everybody once: single quotes are for text, double quotes are for names.
SELECT id, name FROM customers WHERE name = "Null";SELECT id, name FROM customers WHERE name = "Null";with single quotes it's a string, and customer 10 comes back. a single quote inside a string is written twice, which is how Sean O'Neil gets found:
SELECT id, name FROM customers WHERE name = 'Null';
SELECT id, name FROM customers WHERE name = 'Sean O''Neil';| idint4 | nametext |
|---|---|
| 10 | Null |
| idint4 | nametext |
|---|---|
| 8 | Sean O'Neil |
keylines
- SELECT picks columns, FROM picks the table, WHERE picks rows, a semicolon ends it.
- the answer is always a table, with typed columns and a row count.
- NULL, '' and 'Null' are three different things, and the grid draws them differently.
- you say what. EXPLAIN shows the how postgres picked.
- single quotes for text, double quotes for names. unquoted names fold to lowercase.