Explain it simply
Explain it simply
SELECT is the statement that reads data, and it is the command you will use most in SQL. If the Customers table is a big sheet with five columns, SELECT leaves that sheet untouched and produces a fresh sheet containing only the columns you asked for.
On that new sheet you can rename the headings with AS, and you can even add a column that combines two others, such as "city, country". The original table never changes.
Problem → Why → Solution
The problem: fetching everything, then reshaping it in the app
A delivery app's screen must show each customer's name and an address line like "Berlin, Germany". The developer fetches every column with SELECT * and glues city and country together in JavaScript. Each time the table gains a column, more data travels for nothing, and a misspelled column name only shows up at runtime as undefined.
const rows = await db.query("SELECT * FROM Customers");
const items = rows.map((r) => ({
name: r.customername,
address: r.City + ", " + r.country, // r.City is undefined: the key is "city"
}));Why does this bug happen?
SELECT * leaves the shape of the result to the database, so the app has to guess column names. PostgreSQL lowercases unquoted names, so the key is city and r.City is undefined. When you spell out the columns and aliases in the SELECT list, the query itself defines the exact shape of the result.
Core concept: the SELECT list defines the result's shape
The part between SELECT and FROM is the SELECT list. Each item in it becomes one column of the result set, in the order you write them. An item can be a column name (City), every column (*), a literal value ('VIP', 1) or an expression (City || ', ' || Country, Price * 2). Expressions are evaluated once for every row.
AS renames an output column; the new name is called an alias. It changes the name only in the result, never in the table. As Lesson 4 showed, PostgreSQL lowercases an unquoted alias, so AS Name produces the header name. Only a double-quoted alias such as AS "Location" keeps its capitals and spaces. The AS keyword itself is optional, but always writing it keeps an alias from being confused with a forgotten comma.
|| is the standard SQL operator that joins two pieces of text. In MySQL, || means OR by default, so you would write CONCAT(City, ', ', Country) there (PostgreSQL also has concat()). PostgreSQL also lets you run a query with no FROM at all, such as SELECT 2 + 3;, which is handy as a calculator; some databases, such as older Oracle versions, insist on a FROM.
The last point is row order. Without ORDER BY, the SQL standard guarantees no particular order. A tiny table usually comes back in insertion order, but once data grows and rows get updated, that order can change. The output tables in these lessons show the order PostgreSQL happened to return for this small sample.
- FROM opens the table
- Take each row in turn
- Evaluate the SELECT list
- Label columns with aliases
SELECT never changes the source table; it only builds a new result table.
General pattern
SELECT column_a,
column_b AS new_name,
expression AS "Exact Name"
FROM table_name;Separate items with commas; one item per line reads best. AS new_name gives a lowercase alias, while AS "Exact Name" keeps capitals and spaces exactly.
Example: aliases and a computed column
From Lesson 3's Customers table, this query picks three columns and aliases CustomerName as Name. It also adds a Location column built from City and Country; that column does not exist in the table, the query computes it.
SELECT CustomerName AS Name,
City,
Country,
City || ', ' || Country AS "Location"
FROM Customers;Code breakdown
- Line 1
SELECT CustomerName AS Name,Takes CustomerName and shows it as Name. Because the alias is unquoted, the header comes out as name in lowercase.
- Lines 2-3
City,City and Country are taken unchanged. ContactName and CustomerID are not requested, so they are not in the result.
- Line 4
City || ', ' || Country AS "Location"For every row it joins City, ', ' and Country into new text such as Berlin, Germany. The double quotes keep the header as Location with a capital L.
- Line 5
FROM Customers;With no WHERE, all four rows come back. No ORDER BY was given, so this row order is not guaranteed.
name | city | country | Location
---------------------+-------------+---------+---------------------
Alfreds Futterkiste | Berlin | Germany | Berlin, Germany
Ana Trujillo | Mexico City | Mexico | Mexico City, Mexico
Antonio Moreno | Mexico City | Mexico | Mexico City, Mexico
Around the Horn | London | UK | London, UK
(4 rows)SELECT without FROM, and literal columns
A SELECT list may contain only values and calculations, with no table columns at all. PostgreSQL needs no FROM for that, which makes it a quick way to test what an expression returns. Combine a literal with a table and the same value repeats on every row.
SELECT 2 + 3 AS total,
'kyat' AS currency,
upper('mandalay') AS city;Functions such as upper() also work on columns inside a SELECT list: upper(City) shows every row's city in capitals. Notice that the result 5 | kyat | MANDALAY involves no table at all, yet it is still a result set with one row. In SQL the answer always has the shape of a table.
In real projects
Where this shows up in real projects
When an API endpoint returns JSON, the SELECT list effectively defines the response fields. Aliases such as AS customer_name and AS created_at produce exactly the names the app expects, so no renaming code is needed. Leaving sensitive columns such as password hashes out of the SELECT list is also the first line of defence against leaking them.
Reports and CSV exports use double-quoted aliases such as AS "Customer Name" to produce human-friendly headers. Computing columns like a full name, a one-line address or a price including VAT inside the query means whoever opens the spreadsheet, or the dashboard tool, does not have to calculate them again. Every consumer then sees the same numbers.
Common mistakes
Common mistakes
1. Expecting an unquoted alias to keep its capitals
Write AS CustomerName, read row.CustomerName in the app, and you get undefined, because PostgreSQL turned the key into customername. Use lowercase snake_case aliases (customer_name), or double-quote the alias when you truly need capitals.
2. Misspelling a column name
SELECT CustomerNme FROM Customers; fails in PostgreSQL with ERROR: column "customernme" does not exist (MySQL phrases it as Unknown column). Notice the name in the error is lowercase, because PostgreSQL folded it before searching. In psql, \d customers lists the real column names.
3. Relying on the row order of a plain SELECT
In development the rows come back in ID order, so people assume they always will and skip ORDER BY. In production, after updates, the order shifts and paginated lists start repeating or skipping rows. If order matters, always write ORDER BY.
Best practices
Best practices
- In app code, name the columns the screen or API actually uses instead of SELECT *.
- Write AS before every alias so an alias never looks like a forgotten comma.
- Give aliases that app code reads in lowercase snake_case, and keep double-quoted aliases for report headers.
- Put one item per line in a long SELECT list; diffs and code reviews become much easier to read.
Mini challenge
Mini challenge: a contact sheet
Produce a contact sheet for the sales team from the Customers table.
- Show ContactName under the header Contact (capital C)
- Show CustomerName under the lowercase header company
- Add a label column joining 'Customer #' and CustomerID (e.g. Customer #1)
- No SELECT *: exactly three columns
SELECT
-- TODO: ContactName shown as Contact (keep the capital C)
-- TODO: CustomerName shown as company
-- TODO: 'Customer #' joined with CustomerID, shown as label
FROM Customers;Expected: Four rows under the headers Contact | company | label; the first is Maria Anders | Alfreds Futterkiste | Customer #1.
Show hint
Keeping the capital C needs a double-quoted alias. When you join text and an integer with ||, PostgreSQL converts the integer to text for you.
Show solution
SELECT ContactName AS "Contact",
CustomerName AS company,
'Customer #' || CustomerID AS label
FROM Customers;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Each SELECT list item becomes one result column: a column, a literal or an expression.
- AS renames only in the result, and PostgreSQL lowercases unquoted aliases.
- || is standard string concatenation; MySQL uses CONCAT().
- Without ORDER BY, row order is not guaranteed.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group