Declarative vs Imperative Query Languages
Why saying what you want (SQL, Cypher, a MongoDB pipeline) instead of how to get it lets the database pick indexes, join orders and parallelism, and where MapReduce fits.
Overview
There are two ways to ask a computer for data. Imperative code spells out the steps: loop over these records, check this field, add to that list. A declarative query states the result you want (these columns, from rows that match this condition, grouped this way) and leaves the steps to the system. SQL is the best-known declarative language; graph pattern languages like Cypher and SPARQL, and even CSS selectors, work the same way.
The difference matters because whoever chooses the steps also owns their performance. With a declarative query, the database chooses, and it can choose better when data, indexes or hardware change, without anyone touching the application.
The same question, two ways
In imperative code you write the algorithm: the loops, the conditions and the order of steps. You pick the indexes and the join order yourself, in code. When the data grows or an index is added, you rewrite the code, and if you want parallel execution you write it yourself. In return you get full control.
In a declarative query you write the result: filter, join, group, sort. The query planner picks the indexes and the join order. When the data grows or an index is added, the planner may pick a new plan, and the engine can split the work to run it in parallel. When you do need control, the escape hatches are hints, rewriting the query, or dropping down to code.
Here is an imperative version of 'total spent by customer 42'. It always reads every order, because the loop says so.
The declarative version is one line of SQL: SELECT sum(total) FROM orders WHERE customer_id = 42. It says nothing about scanning or indexes, which is exactly what leaves the database free to choose.
Key concepts
- Declarative query
- Imperative code
- Query planner
- Execution plan
- Table statistics
- MapReduce
- Predicate pushdown
Interview questions
- Why is SQL declarative, and why does that matter?
- How does MapReduce differ from SQL?
- A report query got slow after the table grew. How do you approach it?
Sign up free to read the full topic
More DDIA topics
- Beyond MapReduce: Dataflow Engines
- Change Data Capture (CDC)
- Clocks and Time in Distributed Systems
- Column-Oriented Storage and Compression
- Consensus Algorithms: Paxos and Raft
- Consistency Guarantees: Eventual, Causal and Linearizable
- Encoding Formats: JSON, Protobuf, Avro, Thrift
- End-to-End Correctness and the Exactly-Once Myth
- Event Streams and Message Brokers
- Fan-Out and the Twitter Timeline Problem
- Fault Tolerance in Stream Processing
- Faults and Partial Failures
Start free on Cariara · Coding problems · System design studio