Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

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.

Know these firstRelational Model

Properties#

Clause semantics#

ClauseStageWhat it doesOperation
FROM1the Cartesian Product of all listed tables (or their Join with JOIN … ON)×\times, ⋈\bowtie
WHERE2keeps the rows for which the expression is trueselection σ\sigma
GROUP BY3partitions the surviving rows into groups and aggregates per groupGrouping
HAVING4keeps the groups whose aggregated row satisfies the conditionfilter after group-by
SELECT5keeps the listed columns / computes aggregates; DISTINCT removes duplicatesprojection Π\Pi
ORDER BY6sorts the final resultOrdering
LIMIT/OFFSET7keeps a segment of the sorted resultOrdering

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: Πcols(σφ(T1×⋯×Tk))\Pi_{\mathit{cols}}(\sigma_\varphi(T_1 \times \dots \times T_k)).

Aggregation functions#

FunctionValue 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 JOIN keep unmatched rows of one side, filled with NULL.
  • 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#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only