SQL SELECT: Choose Columns, Aliases and DISTINCT
SELECT * is handy for a first look, but real queries name the columns they need. Listing columns makes results smaller and faster, keeps the column order predictable, and stops a query from changing silently when someone adds a column to the table later.
Choosing and computing columns
After SELECT, list column names separated by commas, in the order you want them. You can also select expressions: arithmetic like price * 2, function calls like upper(title), or text joined with the || operator, as in name || ' (' || country || ')'. The database computes the expression for each row.
Aliases with AS
A computed column gets an awkward default name, literally price * 2. Give it a readable name with AS: price * 2 AS two_copies. Aliases also rename ordinary columns, which helps when you join tables that both have a column called name. If an alias contains spaces, wrap it in double quotes, though snake_case names avoid the issue.
LIMIT
LIMIT 3 returns at most three rows. It is perfect for peeking at a big table. Without an ORDER BY (covered two chapters from now), which rows you get is up to the database. In practice SQLite returns them in storage order, as it does here, but no database promises that.
Expected output
title | year | two_copies The Quiet Harbor | 2015 | 29.98 Northern Lights Code | 2021 | 79.0 River of Salt | 2019 | 34.5 genre Fiction Tech Nonfiction
DISTINCT
SELECT DISTINCT genre FROM books; returns each different genre once, no matter how many books share it. With several columns, DISTINCT removes rows where all the selected columns are equal. It is a quick way to see which values occur in a column, such as all the cities customers live in.
The example runs two statements, so the output contains two result sets, each with its own header line.
Number formatting
SQLite stores price as a floating-point number and prints 39.5 * 2 as 79.0, keeping the decimal point to show that it is not an integer. Other databases may print 79.00 or 79. To control display, use round(value, 2) or the printf() function, or format the numbers in the application that shows the results.
Common mistakes
- A trailing comma before
FROM, as inSELECT title, price, FROM books, which is a syntax error. - Forgetting the comma between two columns.
SELECT title pricetreatspriceas an alias fortitle. - Expecting
DISTINCTto apply to only the first column.
Summary
- List the columns you need instead of
*. - Expressions compute new columns;
ASnames them. LIMIT ncaps the number of rows;DISTINCTremoves duplicate rows.
Quiz: SELECT columns