SQL Query Structure
A SQL SELECT query consists of the clauses SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT, whose result is defined by evaluating them in a fixed logical order starting from the Cartesian product of the FROM tables.
Properties#
Clause semantics#
| Clause | Stage | What it does | Operation |
|---|---|---|---|
FROM | 1 | the Cartesian Product of all listed tables (or their Join with JOIN … ON) | , |
WHERE | 2 | keeps the rows for which the expression is true | selection |
GROUP BY | 3 | partitions the surviving rows into groups and aggregates per group | Grouping |
HAVING | 4 | keeps the groups whose aggregated row satisfies the condition | filter after group-by |
SELECT | 5 | keeps the listed columns / computes aggregates; DISTINCT removes duplicates | projection |
ORDER BY | 6 | sorts the final result | Ordering |
LIMIT/OFFSET | 7 | keeps a segment of the sorted result | Ordering |
For the basic form SELECT … FROM … WHERE …: the result is all rows of the Cartesian product of the FROM tables for which the WHERE expression is true, restricted to the SELECT columns. In the operations of Relational Algebra: .
Aggregation functions#
| Function | Value per group |
|---|---|
COUNT(*) | number of rows |
COUNT(col) | number of non-NULL values of col |
SUM(col), AVG(col) | sum, arithmetic mean |
MIN(col), MAX(col) | minimum, maximum |
GROUP_CONCAT(col, sep) | values concatenated with separator sep (SQLite3) |
Without GROUP BY, an aggregate is computed over all rows of the (filtered) table.
JOIN variants#
See Join for the definitions.
- Implicit join:
FROM A, B WHERE A.x = B.y(traditional). - Explicit join:
FROM A JOIN B ON A.x = B.y(most modern);LEFT JOIN/RIGHT JOINkeep unmatched rows of one side, filled withNULL. NATURAL JOIN: equi-join on all columns that have the same name in both tables; each such column appears once in the output.
Subqueries#
Wherever SQL expects a table, a whole SELECT query in parentheses may be written (Subquery).
Relation to SPARQL#
Basic SPARQL queries translate mechanically into SELECT … FROM … WHERE … queries: one table alias per query triple, equality conditions for constants and shared variables (SPARQL to SQL Translation).
Example#
Sources#
- Slides 03, p. 28–38 (basic query, FROM/WHERE/SELECT semantics)
- Slides 04, p. 15 (translation into operations)
- Slides 05, p. 21 (JOIN … ON, NATURAL JOIN), p. 26–27 (HAVING), p. 30–34 (ORDER BY, LIMIT/OFFSET, subqueries)
- DBIS_VL03 > SQL Basics, DBIS_VL03 > FROM: the cross-product, DBIS_VL03 > WHERE: filtering the cross-product, DBIS_VL03 > SELECT: choosing columns, DBIS_VL05 > More join operations, DBIS_VL05 > Grouping, DBIS_VL05 > More SQL, DBIS_VL07 > Differences between SPARQL and SQL
- Exams: DBIS Exam WS2324 (not published) (Tasks 2.1, 3.3), DBIS Exam WS2324-2 (not published) (Tasks 2.1, 3.3), DBIS Exam WS1617 (not published) (Task 6.2)