skip to content

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:

query.sql
  1. 1SELECT name, city
  2. 2FROM customers
  3. 3WHERE id = 42;

SELECT starts the question. it says what to bring back.

step 1/5
step through it (or click the figure and use ← →). four parts and a semicolon. the order you write them in isn't the order they run in, but that's a later chapter.

now run it. this is a real postgres, in your browser, on the shop's real data:

sqldb=shop
SELECT name, city
FROM customers
WHERE id = 42;
output, from postgres 18.6
SELECT 1
nametextcitytext
Ada LovelaceLondon
(1 row)

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:

sqlempty db
SELECT 1;
output, from postgres 18.6
SELECT 1
?column?int4
1
(1 row)

the select list can hold any expression, and AS names the column it makes:

sqlempty db
SELECT 'hello' AS greeting, 6 * 7 AS answer, upper('ada') AS shouting;
output, from postgres 18.6
SELECT 1
greetingtextanswerint4shoutingtext
hello42ADA
(1 row)

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.

sqldb=shop
SELECT *
FROM customers
ORDER BY id
LIMIT 5;
output, from postgres 18.6
SELECT 5
idint4nametextemailtextcitytextcountrycharcreated_attimestamptz
1Maya Chenmaya.chen@example.comSan FranciscoUS2024-01-01 09:12:00+00
2Grace OkafornullLagosNG2024-01-02 14:40:00+00
3Sam Leesam.lee@example.comTorontoCA2024-01-03 08:05:00+00
4Zoë MartinZoe.Martin@Example.comParisFR2024-01-03 19:30:00+00
5Zoe Martinzoe.martin@example.comLyonFR2024-01-04 11:11:00+00
(5 rows)

* 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:

query.sql
  1. SELECT id, name, email, city
  2. FROM customers
  3. WHERE id IN (2, 10, 11, 42)
  4. ORDER BY id;
point at =
SELECT 4
idint4nametextemailtextcitytext
2Grace OkafornullLagos
10Nullnull@example.comBerlin
11Ana Limanull''
42Ada Lovelaceada@example.comLondon
(4 rows)

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.

real output, postgres 18.6 (PGlite 0.5.12) · the shop database, customers 2, 10, 11 and 42
pick a part. these four customers are the shop's awkward ones on purpose: a missing email, a person actually named Null, and an empty city. the grid draws 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):

sqldb=shop
SELECT id, name, email, city
FROM customers
WHERE id IN (2, 10, 11, 42)
ORDER BY id;
output, from postgres 18.6
SELECT 4
idint4nametextemailtextcitytext
2Grace OkafornullLagos
10Nullnull@example.comBerlin
11Ana Limanull''
42Ada Lovelaceada@example.comLondon
(4 rows)

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:

sqldb=shop
SELECT count(*) AS customers FROM customers;
SELECT count(*) AS orders FROM orders;
SELECT name FROM products WHERE id = 200;
output, from postgres 18.6
#1 · SELECT 1
customersint8
2000
(1 row)
#2 · SELECT 1
ordersint8
10000
(1 row)
#3 · SELECT 1
nametext
left-handed teapot
(1 row)

(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

how
  1. for row in read_all('customers'):
  2. if row.id == 42:
  3. print(row.name, row.city)
  4. break
what
  1. SELECT name, city
  2. FROM customers
  3. WHERE id = 42;
the same request two ways. on the left, the how: a loop you'd write by hand. on the right, the what: the loop is postgres's problem now.

you can ask postgres how it decided to answer. EXPLAIN shows the plan instead of running the query:

sqldb=shop
EXPLAIN SELECT name, city FROM customers WHERE id = 42;
EXPLAIN SELECT name, city FROM customers WHERE city = 'London';
output, from postgres 18.6
#1 · EXPLAIN
Index Scan using customers_pkey on customers (cost=0.28..8.29 rows=1 width=19) Index Cond: (id = 42)
#2 · EXPLAIN
Seq Scan on customers (cost=0.00..49.00 rows=159 width=19) Filter: (city = 'London'::text)

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.

hover a stage. what happens between pressing run and getting rows back. the life of a query has the details.

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:

sqldb=shop
select NAME from CUSTOMERS where ID = 42;
output, from postgres 18.6
SELECT 1
nametext
Ada Lovelace
(1 row)

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:

sqldb=shop
SELECT name FROM "Customers";
output, from postgres 18.6
ERROR 42P01: relation "Customers" does not exist
1 │ SELECT name FROM "Customers";
at line 1, column 18

which brings up the one rule that bites everybody once: single quotes are for text, double quotes are for names.

predict the output
sql
SELECT id, name FROM customers WHERE name = "Null";
sqldb=shop
SELECT id, name FROM customers WHERE name = "Null";
output, from postgres 18.6
ERROR 42703: column "Null" does not exist
1 │ SELECT id, name FROM customers WHERE name = "Null";
at line 1, column 45

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:

sqldb=shop
SELECT id, name FROM customers WHERE name = 'Null';
SELECT id, name FROM customers WHERE name = 'Sean O''Neil';
output, from postgres 18.6
#1 · SELECT 1
idint4nametext
10Null
(1 row)
#2 · SELECT 1
idint4nametext
8Sean O'Neil
(1 row)

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.