picking columns
columns, expressions, aliases, built-in functions, and when SELECT * stops being harmless.
- address
- everything.basics.select_and_expressions
- part
- part 2, one table
- chapter
- chapter 1 of 12
- reading time
- 7 min
SELECT is a map: for every row FROM hands over, it computes each item in the select list and hands on one output row. an item can be a column, a literal, or any expression built from them, and AS gives it a name.
SELECT * means "every column, as the table has them right now", and that's where it stops being harmless.
the picture
you know how SELECT feels like "pick some columns"? it does more than that. every item in the list is an expression, evaluated once for every row, and a plain column name is just the simplest expression there is.
think of a form you fill in once per customer: each line on the form says how to fill one box ("price plus VAT", "category in capitals"), and every row of the table gets its own copy. one row in, one filled-in form out. SELECT never looks at two rows at once (that's what aggregates are for).
price * 1.2 AS gross reads price = 49.00 and fills gross = 58.800. numeric times numeric is numeric, so nothing is rounded: 1.2 adds a decimal place.
upper(category) is NULL for it. the literal reads nothing at all.the same query, all four rows:
SELECT name, price * 1.2 AS gross, upper(category) AS shelf, price > 50 AS pricey, 'EUR' AS currency
FROM products
WHERE id IN (1, 5, 7, 200)
ORDER BY id;| nametext | grossnumeric | shelftext | priceybool | currencytext |
|---|---|---|---|---|
| chef's knife | 58.800 | KITCHEN | f | EUR |
| studio headphones | 155.988 | AUDIO | t | EUR |
| wooden train | 28.800 | null | f | EUR |
| left-handed teapot | 23.988 | KITCHEN | f | EUR |
four rows in, four rows out, always. SELECT can change the columns completely, but on its own it never changes how many rows there are.
names
every output column has a name. AS picks it. leave AS out and postgres makes one up: a bare column keeps its name, a function call is named after the function, and anything else gets the name ?column?:
SELECT name, 'name', upper(name), length(name) * 2
FROM customers
WHERE id = 42;| nametext | ?column?text | uppertext | ?column?int4 |
|---|---|---|---|
| Ada Lovelace | name | ADA LOVELACE | 24 |
note the second column: 'name' in single quotes is a string, the same in every row, not the name column (first query has the quoting rules).
the AS keyword itself is optional, price * 1.2 gross works, but write it: a forgotten comma between two columns turns the second one into an alias of the first, silently. and an alias folds to lowercase like any other name, unless you double-quote it:
SELECT name AS "Customer Name", city AS Town
FROM customers
WHERE id = 42;| Customer Nametext | towntext |
|---|---|
| Ada Lovelace | London |
Customer Name keeps its capitals and its space. Town became town. a name is born in SELECT and only ORDER BY gets to use it: the logical order explains why WHERE can't.
expressions have types
every expression has a type, and the type decides what an operator does. this catches everyone once:
SELECT 7 / 2;- 1SELECT 7 / 2 AS result, pg_typeof(7 / 2) AS type;
| resultint4 | typeregtype |
|---|---|
| 3 | integer |
two integers make an integer, and integer division throws the remainder away: 3, not 3.5.
pg_typeof shows the type postgres picked for each one.the rule of thumb: an operation on two integers stays an integer, and anything with a numeric in it becomes numeric. :: casts a value to another type. the whole system of types and when postgres converts between them is in types and casts.
the functions you'll use every day
postgres ships hundreds of functions. a handful cover most days:
SELECT upper(name) AS shouted,
length(name) AS letters,
left(email, strpos(email, '@') - 1) AS mailbox,
round(49.995, 2) AS rounded,
extract(year FROM created_at) AS joined,
name || ' from ' || city AS label
FROM customers
WHERE id = 42;| shoutedtext | lettersint4 | mailboxtext | roundednumeric | joinednumeric | labeltext |
|---|---|---|---|---|---|
| ADA LOVELACE | 12 | ada | 50.00 | 2024 | Ada Lovelace from London |
|| glues text together. careful with it: one NULL in the chain and the whole result is NULL (NULL and three-valued logic). concat() skips NULLs instead, and coalesce() puts something in their place (CASE, COALESCE and NULLIF).
when SELECT * stops being harmless
* means every column, in the table's order. it's great at a psql prompt, where you want to look around. in code that lives for years, it has three ways to hurt.
it sends everything. products has a 6 KB description on one row and 3 KB of hex on another. ask for * and they all come along, whether you show them or not:
six times the bytes, over the network, through the driver, into memory, for a page that shows a name and a price. it also stops postgres from answering from an index alone (index-only scans), because no index holds every column.
it changes when the table does. add a column, and every SELECT * returns one more. code that reads columns by position gets the wrong one, and a SELECT * view does something stranger. it's expanded once, when the view is created, and never again:
CREATE VIEW free_stuff AS SELECT * FROM products WHERE price = 0;
ALTER TABLE products ADD COLUMN rating int;
SELECT pg_get_viewdef('free_stuff');| pg_get_viewdeftext |
|---|
the view's stored definition lists the nine columns by name. the new rating isn't one of them, and won't be until someone recreates the view:
SELECT * FROM free_stuff;| idint4 | skutext | nametext | categorytext | pricenumeric | tagstext[] | attrsjsonb | descriptiontext | discontinuedbool |
|---|---|---|---|---|---|---|---|---|
| 4 | OFF-0004 | paper clips, free sample | office | 0.00 | {free} | {"color": "silver", "weight_g": 40} | null | f |
it hides what the code needs. a query that names its columns tells the next reader exactly what it depends on. * tells them nothing, and makes "can we drop this column?" a question nobody can answer by reading the code.
so: * at the prompt, names in the program.
keylines
- SELECT computes its list once per row: one row in, one row out.
- an item is any expression: a column, a literal, a function call, a comparison.
- AS names a column. unnamed expressions get ?column?. unquoted names fold to lowercase.
- the type of an expression decides the operator: 7 / 2 is 3.
-
- is every column, now. fine at the prompt, a liability in code and in views.