Learning navigation

Code with Animation

SELECT & Column Labels

Choose exactly which columns a query returns, build new columns from expressions, and name them with AS.

SQL5 min readConcept 6 of 44

The select list decides the columns

SELECT starts every query. The part after it is the select list: the columns you want back. You can write column names, * for every column, or any expression that produces a value.

An expression is worked out once for every row. It does not have to use a table column, and it can be as simple as points + 10.

AS gives an output column a name. It changes the name in the result only, never in the table.

Ask only for what you need

A smaller result is faster to send and easier to read. It also keeps your program stable: if you name the columns you use, a new column in the table cannot change what your code receives.

Good labels make results self-explaining. A column called score says more than points + 10.

Build a select list

This query returns two columns for every player, and renames one of them:

SELECT name, points AS score
FROM players;

The result has the columns name and score. The table still calls the second column points.

Without AS, PostgreSQL picks a name. A plain column keeps its own name, a function uses the function's name, and a more complex expression gets a generic name. AS is usually optional, but writing it always is the safe habit, because a name that happens to be a reserved word would otherwise break the query.

Shape the select list

Tap columns to add or remove them, try *, rename points, and add a calculated column with and without a label.

SELECT name, points
FROM players;
players (8 rows)
idintegernametextteamtextpointsinteger
1AshaRed31
2BenBlue17
3ChenRedNULL
4DaraGreen24
5EliBlueNULL
6FayRed24
7GusGreen40
8HanaBlue17
Result (8 rows)
nametextpointsinteger
Asha31
Ben17
ChenNULL
Dara24
EliNULL
Fay24
Gus40
Hana17

The select list decides which columns come back. AS renames a column in the result only, not in the table.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does `SELECT name, points FROM players` return?
  2. 2You run `SELECT points + 1 FROM players` with no AS. What name does the result column get?
  3. 3Which query returns a column called `score` that holds each player's points?

Remember this

  • The select list decides which columns a query returns: names, * or expressions.
  • An expression in the select list is worked out once for every row.
  • AS renames a column in the result only, and calculated columns should always have one.
  • SELECT * is fine for exploring but risky in programs, because new columns change the result.

Done with this concept?

Mark it complete to track your progress. No login needed.