Declarative Languages
Declarative Programming: Describing What, Not How
Most first programming courses teach you to write instructions: set a counter, loop over a list, test a condition, update a variable. Declarative programming takes the opposite approach. You describe the result you want, and a language engine works out the steps. You meet this style whenever you query a database, write a search pattern, style a web page or write a build file. Seeing it as a distinct way of programming helps you write shorter programs and read them correctly.
Describing the result instead of the steps
Declarative programming is a style in which a program states the properties of the desired result and leaves the sequence of operations to an engine. Compare two ways of listing honours students. The first spells out every step:
honours = []
for s in students:
if s.gpa >= 3.5:
honours.append(s.name)The second, written in SQL, only describes the answer:
SELECT name FROM students WHERE gpa >= 3.5;The SQL version never mentions a loop, an accumulator or the order in which rows are visited. It says which rows qualify and which column to report. In relational algebra the same query is a composition of two operations:
Here σ (selection) keeps the rows that satisfy a condition and π (projection) keeps the named columns. The expression defines the answer as a set; it does not prescribe an algorithm. One detail differs: relational algebra treats results as sets, while SQL keeps duplicate rows unless you write DISTINCT.
Who decides the steps
The database must still choose and perform operations to produce the result. The query optimizer is the engine component that compares possible execution plans for a query and picks the one it estimates to be cheapest. The executor then carries out the operations in that plan, such as scanning rows and testing conditions. The query defines the result; the plan specifies how to compute it.
Example: Suppose the students table holds 1 000 000 rows and 20 000 of them have a GPA of at least 3.5. A full table scan examines all 1 000 000 rows. After an administrator adds an index on gpa, assume the optimizer chooses an indexed plan that locates the qualifying entries and fetches roughly 20 000 table rows. With the query unchanged, this hypothetical plan reduces table-row examinations by roughly a factor of 1000000/20000=50. Overall work and runtime also depend on index traversal, row-fetch costs and caching, so this ratio does not imply a fiftyfold speedup.
The trade-off is control. When a query runs slowly, you cannot reorder its loops directly, because the query specifies none; you inspect the plan the optimizer chose and change the data structures, such as indexes, or restate the query so the optimizer can find a better plan.
Declarative languages you already use
The same division of labour appears well beyond databases.
Language | You describe | The engine decides |
|---|---|---|
SQL | Which rows and columns the result contains | Scan order, join method, index use |
Regular expressions | The set of strings a pattern matches | How to step through the text |
HTML and CSS | Document structure and style rules | Element positions and rendering order |
Make | Targets, their dependencies and build recipes | Which files are out of date and the build order |
Spreadsheet formulas | How each cell relates to others | The order in which cells recalculate |
A regular expression such as [0-9]{3}-[0-9]{4} describes every string of three digits, a hyphen and four digits; the matching engine decides how to scan the input. A CSS rule such as h2 { color: navy; } says that every level-two heading is navy, not when or in what order to paint them. A Makefile lists what each file depends on, and Make compares timestamps to decide which commands to run.
Declarative is a spectrum rather than a strict category. Many declarative languages still contain small imperative pieces, such as the shell commands inside a Make recipe, but the overall control flow is decided by the engine.
What to remember
- Declarative programs describe properties of the result; an engine chooses the steps.
- In SQL the query fixes the result, the optimizer chooses a plan and the executor performs its operations.
- An index can reduce table-row examinations without changing the query, but the reduction alone does not determine the runtime improvement.
- Any order you need, such as sorted output, must be part of the description.
- SQL, regular expressions, HTML and CSS, Make and spreadsheet formulas are all declarative in this sense.
- The cost of the style is less direct control over performance.
Example: Predicting the result of a grouped SQL query
A registrar stores course results in a table called enrolment. Assume grade is a decimal column, so AVG returns a decimal, and round averages to two decimal places.
student | course | grade |
|---|---|---|
Ana | CS101 | 82 |
Ana | MA120 | 74 |
Ben | CS101 | 91 |
Ben | PH110 | 68 |
Chloe | CS101 | 77 |
Chloe | MA120 | 88 |
Dev | PH110 | 59 |
Dev | MA120 | 95 |
The registrar runs this query:
SELECT course, COUNT(*) AS n, AVG(grade) AS avg_grade
FROM enrolment
WHERE grade >= 70
GROUP BY course
ORDER BY course;An aggregate function such as COUNT or AVG takes the rows of one group and returns a single value for that group. The query does not say how to visit the rows; it describes which rows count and what to report about each course.
a) How many rows of enrolment satisfy the WHERE condition?
WHERE describes a test applied to each row on its own. Check every grade against 70.
Ben's PH110 grade of 68 and Dev's PH110 grade of 59 are below 70, so ________ rows are removed. All other grades (82, 74, 91, 77, 88, 95) pass.
Six rows satisfy the condition. Whether the engine scans the table from the top or uses an index on grade, the set of qualifying rows is the same.
b) Write out the complete result of the query.
GROUP BY collects the six surviving rows by course, and each group becomes one output row.
- CS101 keeps Ana (82), Ben (91) and Chloe (77). The grades add to ________ across 3 rows.
- MA120 keeps Ana (74), Chloe (88) and Dev (95). The grades add to ________ across 3 rows.
- PH110 had two rows, but both failed the WHERE test, so no PH110 row remains to form a group.
ORDER BY course sorts the output alphabetically, so the result has two rows:
- CS101, n = 3, avg_grade = 83.33
- MA120, n = 3, avg_grade = 85.67
A course with no surviving rows simply does not appear; it is not reported with a count of zero.
c) The registrar adds the line HAVING AVG(grade) > 85 after the GROUP BY line. What does the query now return?
HAVING filters groups after aggregation, while WHERE filters individual rows before grouping. The WHERE step and the groups from part (b) are unchanged, so test each group's average against 85.
CS101's average of ________ is not greater than 85, so that group is dropped. MA120's average of 85.67 is greater than 85, so it stays.
The result is a single row: MA120, n = 3, avg_grade = 85.67.
Notice the size of the change: one added line of description produced a different result, and nothing about loops, counters or visiting order had to be rewritten. That is the practical payoff of the declarative style.
A developer sends the statement SELECT name FROM staff WHERE dept = 'Sales'; to a relational database. Because SQL is declarative, the statement says which rows are wanted but not how to fetch them. Arrange the stages the database engine goes through, from receiving the statement text to returning rows.
Loading ordering steps…
A SQL SELECT statement is written in the order SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, but standard SQL defines the meaning of the clauses in a different logical order. Arrange the clauses below in that logical order, from first to last. The engine may physically execute the query differently, as long as the result matches.
Loading ordering steps…