78 East LabsApply

Your first SELECT

What a query actually asks the database for, and why the answer is always a table.

Video being recorded
About 8 minutes. The written lesson below is complete — read it now, the video is an alternative rather than a replacement.

A SQL query is a description of the result you want. You do not tell the database how to go and fetch it — which file to open, which index to walk, which table to read first. That is the planner's job, and it will frequently choose a route you did not think of.

The smallest useful query

SELECT name, city
FROM students;

Read it in the order the database does, not the order it is written. FROM runs before SELECT: the database finds the table first, and only then decides which columns to keep.

What comes back is itself a table — rows, and columns with names. That is the whole idea. Every query takes tables and returns a table, which is why queries nest: the result of one is a perfectly good input to another.

Asking for everything

SELECT * returns every column in the table. It is convenient while you are exploring and you do not yet know what is there. It is a liability in code you keep, because the result silently changes shape the day someone adds a column — and whatever was reading it was written against the old shape.

Name your columns once the query is more than a look around.