skip to content

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).

row =
a row from FROM (4 of its columns)
idint4
1
nametext
chef's knife
categorytext
kitchen
pricenumeric
49.00
the select list, run once for this row
SELECT,,,,
the row SELECT hands on
nametext
chef's knife
grossnumeric
58.800
shelftext
KITCHEN
priceybool
f
currencytext
EUR

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.

real output, postgres 18.6 (PGlite 0.5.12) · select-and-expressions
pick a product and an item in the select list. the input cells it reads light up, and so does the one cell of the output row it fills. the wooden train has no category, so upper(category) is NULL for it. the literal reads nothing at all.

the same query, all four rows:

sqldb=shop
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;
output, from postgres 18.6
SELECT 4
nametextgrossnumericshelftextpriceyboolcurrencytext
chef's knife58.800KITCHENfEUR
studio headphones155.988AUDIOtEUR
wooden train28.800nullfEUR
left-handed teapot23.988KITCHENfEUR
(4 rows)

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

sqldb=shop
SELECT name, 'name', upper(name), length(name) * 2
FROM customers
WHERE id = 42;
output, from postgres 18.6
SELECT 1
nametext?column?textuppertext?column?int4
Ada LovelacenameADA LOVELACE24
(1 row)

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:

sqldb=shop
SELECT name AS "Customer Name", city AS Town
FROM customers
WHERE id = 42;
output, from postgres 18.6
SELECT 1
Customer Nametexttowntext
Ada LovelaceLondon
(1 row)

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:

predict the output
sql
SELECT 7 / 2;
SELECT =
query.sql
  1. 1SELECT 7 / 2 AS result, pg_typeof(7 / 2) AS type;
the result for 7 / 2
resultint4typeregtype
3integer
(1 row)

two integers make an integer, and integer division throws the remainder away: 3, not 3.5.

real output, postgres 18.6 (PGlite 0.5.12) · select-and-expressions
switch the expression. same numbers, different types, different answers. 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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 1
shoutedtextlettersint4mailboxtextroundednumericjoinednumericlabeltext
ADA LOVELACE12ada50.002024Ada Lovelace from London
(1 row)

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

SELECT *35,977 bytes
SELECT id, name, price5,594 bytes
every product written out as text: all nine columns, against the three a listing page needs. most of the difference is descriptions nobody on that page reads.

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:

sqldb=shop · session star
CREATE VIEW free_stuff AS SELECT * FROM products WHERE price = 0;
ALTER TABLE products ADD COLUMN rating int;
SELECT pg_get_viewdef('free_stuff');
output, from postgres 18.6
#1 · CREATE VIEW
#2 · ALTER TABLE
#3 · SELECT 1
pg_get_viewdeftext
(1 row)

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:

sqldb=shop · session star
continues session star (1 earlier block run first)
SELECT * FROM free_stuff;
output, from postgres 18.6
SELECT 1
idint4skutextnametextcategorytextpricenumerictagstext[]attrsjsonbdescriptiontextdiscontinuedbool
4OFF-0004paper clips, free sampleoffice0.00{free}{"color": "silver", "weight_g": 40}nullf
(1 row)

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.