SQL Quest

Lessons, hints, explained solutions, the in-browser PostgreSQL editor and practice answer checks in your browser are available. Graded assessments, recorded progress from answer checks and new certificates aren't available yet.

SELECT

Reads rows from one or more tables and returns the columns or expressions you list.

Syntax

SELECT [DISTINCT] expression [AS alias], ...
FROM table [AS t]
[WHERE condition]
[GROUP BY ...] [HAVING ...]
[ORDER BY ...] [LIMIT n] [OFFSET m];

SELECT builds a result table. FROM names where the rows come from; the select list says which columns (or computed expressions) each output row has.

  • * means "every column, in table order". Handy for exploring; list columns explicitly in real queries so the result does not change when the table does.
  • expression AS alias names an output column. AS is optional, but write it: it makes intent obvious. Quote an alias with double quotes only if it needs spaces or capitals (AS "Total SAR").
  • Unquoted identifiers are folded to lower case: SELECT Price reads the column price.
  • Expressions can be arithmetic (price * quantity), function calls, CASE, literals or subqueries.
  • SELECT without FROM evaluates expressions once: SELECT 7 / 2, now();.
  • Without ORDER BY the row order is not defined. It may look stable, but it can change after an update or between runs.

Examples

Pick and rename columns starter
SELECT product_name, category, price AS list_price
FROM products;

One output row per product, three columns. The alias renames price in the result only.

Computed column starter
SELECT order_id, quantity, quantity * 2 AS double_quantity, status
FROM orders
ORDER BY order_id;

Expressions are evaluated once per row. ORDER BY makes the row order reliable.

SELECT without FROM starter
SELECT 7 / 2 AS int_division, 7 / 2.0 AS exact_division, current_date AS today;

Integer divided by integer truncates (3); one numeric operand gives 3.5.

Pitfalls

  • Relying on the order rows happen to come back in. Only ORDER BY guarantees order.

  • Using single quotes for an alias ('total'): single quotes make a string literal. Use AS total or AS "Total".

  • Writing a comma after the last select-list item: SELECT a, b, FROM t is a syntax error near FROM.

  • Using SELECT * in a query that feeds a report or an INSERT: a new column silently changes the result.

Other databases

For orientation only: SQL Quest executes PostgreSQL.

SQL Server

Identifiers can be quoted with [brackets]; double quotes also work with the default QUOTED_IDENTIFIER ON.

MySQL

Identifiers are quoted with backticks (name); double quotes are string delimiters unless ANSI_QUOTES is enabled.

Oracle

Unquoted identifiers fold to UPPER case (PostgreSQL folds to lower). A query needs FROM before 23ai; use FROM dual for a single-row SELECT.