SELECT & Column Labels
Choose exactly which columns a query returns, build new columns from expressions, and name them with AS.
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.
| idinteger | nametext | teamtext | pointsinteger |
|---|---|---|---|
| 1 | Asha | Red | 31 |
| 2 | Ben | Blue | 17 |
| 3 | Chen | Red | NULL |
| 4 | Dara | Green | 24 |
| 5 | Eli | Blue | NULL |
| 6 | Fay | Red | 24 |
| 7 | Gus | Green | 40 |
| 8 | Hana | Blue | 17 |
| nametext | pointsinteger |
|---|---|
| Asha | 31 |
| Ben | 17 |
| Chen | NULL |
| Dara | 24 |
| Eli | NULL |
| Fay | 24 |
| Gus | 40 |
| Hana | 17 |
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.
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.