Dayrvia
SQL

Databases

Read filters and joins, then practise NULL handling and transactions with concrete records.

Take the full quiz

QueriesRows and columns

Choosing rows and columns

SELECT names the columns in the result. WHERE describes which rows qualify. Use a unique key to identify records because names can repeat.

Code example

SELECT name FROM results
WHERE score >= 80;

Walkthrough

Rows with scores of at least 80 qualify, including exactly 80. Only their names appear in the result.

Aggregation and joinsGrouping

Counting within groups

GROUP BY collects rows sharing a key. COUNT(*) counts rows while COUNT(column) counts non-NULL values. HAVING applies conditions to groups.

Code example

SELECT team, COUNT(*), COUNT(score)
FROM results GROUP BY team;

Walkthrough

If a team has three rows and only two scores have been entered, the counts are 3 and 2 respectively.

Aggregation and joinsOuter joins

Finding missing matches

A LEFT JOIN preserves rows from the left. Missing matches produce NULL values on the right. Multiple matches produce multiple result rows.

Code example

SELECT m.id, a.id
FROM members m LEFT JOIN applications a
  ON m.id = a.member_id;

Walkthrough

A member with no application keeps their id and gets NULL for a.id. A member with two applications appears twice.

QueriesNULL checks

Testing for NULL

NULL represents missing or unknown information. An ordinary comparison with NULL evaluates to UNKNOWN. WHERE keeps only TRUE rows, so use IS NULL to test for a missing value.

Code example

SELECT id FROM tasks
WHERE finished_at IS NULL;

Walkthrough

The query selects tasks without a completion time. The ordinary comparison finished_at = NULL would not select them under standard SQL semantics.

TransactionsCommit and rollback

Grouping changes into a transaction

A transfer needs its debit and credit to take effect together. A transaction groups the changes. In PostgreSQL, COMMIT makes them effective permanently and ROLLBACK undoes the uncommitted changes.

Code example

BEGIN;
UPDATE balances SET amount = amount - 10 WHERE id = 1;
UPDATE balances SET amount = amount + 10 WHERE id = 2;
ROLLBACK;

Walkthrough

Starting from 50 and 20, this transaction sees 40 and 30 after the updates. ROLLBACK restores 50 and 20.

Further reading