bhylu.com

Advertisements

SQL Quick Ref

Use this short reference when you remember the question but need help assembling the clauses. Read the matching lesson when the result surprises you; a syntax reminder cannot replace understanding the row relationships.

Understand the idea

For a list, choose columns, table, filter, and ordering. For a summary, state the input rows and grouping key before adding aggregates. For related data, identify the keys and decide which unmatched rows must remain. For a change, preview the target rows and choose a transaction boundary. The worked statement below combines a filtered aggregate with explicit result naming.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT c.name, COALESCE(SUM(o.total_cents), 0) AS paid_cents
FROM customers AS c
LEFT JOIN orders AS o
  ON o.customer_id = c.customer_id AND o.status = 'paid'
GROUP BY c.customer_id, c.name
ORDER BY paid_cents DESC, c.customer_id;

Read the result

The report shows Mira at 2300, Dev at 1350, then Asha and Noor at 0. A stable identifier breaks the tie between the zero totals.

Try one change

Rebuild the statement from the plain-language requirement without looking. Explain every clause and the reason for the LEFT JOIN.