SELECT, Columns & Aliases
The simplest query
SELECT column1, column2 FROM table_name;
SELECT *– all columns. Fine for exploring, but in real code list the columns you need: it's faster, clearer, and doesn't break when columns are added.
Expressions in SELECT
You can calculate new values on the fly; the table isn't changed:
- Math:
amount * 1.13 - Text:
name || ' (' || city || ')' - Functions:
upper(name),round(amount) - Constants:
SELECT 'NPR' AS currency
Aliases with AS
- Column alias:
amount * 1.13 AS amount_with_vat– names the result column - If the alias has spaces or capitals, use double quotes:
AS "Total Amount" - Table alias:
FROM expenses AS eor justFROM expenses e→ then writee.amount(essential for joins) ASis optional but makes code easier to read
SELECT without a table
PostgreSQL can evaluate expressions directly: SELECT 2 + 2, now(), upper('hi');
Readable formatting
SELECT
title,
amount,
amount * 0.13 AS vat
FROM expenses;
- One column per line in long queries
- Keywords in UPPERCASE
- Consistent indentation
Where results go
A SELECT returns a result set — a temporary table. You can view it, export it, or use it inside other queries (subqueries, CTEs, views).
Example
-- All columns (good for exploring)
SELECT * FROM categories;
-- Only the columns you need
SELECT name, city FROM users;
-- Calculated columns with aliases
SELECT
title,
amount,
amount * 0.13 AS vat,
amount * 1.13 AS amount_with_vat,
'NPR' AS currency
FROM expenses
LIMIT 3;
-- title | amount | vat | amount_with_vat | currency
-- Weekly groceries | 2450.00 | 318.5000 | 2768.5000 | NPR
-- Combining text
SELECT name || ' from ' || city AS intro FROM users;
-- "Asha Sharma from Kathmandu" ... and NULL for Hari (NULL city makes the whole result NULL!)
-- Table alias + quoted column alias
SELECT e.title AS "Expense", e.amount AS "Amount (NPR)"
FROM expenses AS e
LIMIT 2;
-- No table needed
SELECT 2 + 2 AS four, upper('budget buddy') AS shout, CURRENT_DATE AS today;