Declarative programming

On this page 7

Declarative programming is a programming paradigm in which code describes what result is wanted rather than the step-by-step procedure for obtaining it. The language implementation, query engine or runtime then decides how to compute the result. It is one of the two broad families of programming fundamentals, set against imperative programming, which spells out each state change explicitly.

Familiar examples include SQL queries, HTML markup, regular expressions, spreadsheet formulas, configuration languages and functional languages such as Haskell. Each states a goal or a relationship and leaves execution strategy to the underlying system.

How declarative programming separates what from how

Declarative programming works by separating the specification of a result from the mechanism that produces it. The programmer writes a description, such as a query, a set of rules or a mathematical expression, and an engine with built-in knowledge of strategies translates that description into concrete operations.

A SQL statement such as SELECT name FROM customers WHERE country = 'CA' illustrates the idea. It does not say whether to scan the table or use an index, in which order to read pages, or how to allocate memory. The query optimizer evaluates possible execution plans and chooses one based on statistics, indexes and available resources.

Most declarative code shares a set of characteristic properties. The table below lists them with the practical consequence of each.

PropertyMeaningPractical consequence
No explicit control flowOrder of evaluation is not dictated by the codeEngine may reorder or parallelize work
Minimal mutable stateValues are described rather than updated in placeFewer bugs caused by unexpected changes
Referential transparencyAn expression can be replaced by its valueEasier reasoning, testing and caching
Idempotent descriptionsApplying the same description twice gives one resultSafe re-runs in configuration and deployment
Higher abstraction levelCode is closer to the problem domainShorter programs that read like specifications
Characteristic properties of declarative code

Main styles of declarative programming

Declarative programming covers several distinct styles, each built on a different formal foundation. What they share is that the programmer states relationships or constraints and the system derives the answer.

StyleFormal foundationRepresentative languagesTypical use
Functional programmingLambda calculusHaskell, Elm, Clojure, F#Data transformation, compilers, finance
Logic programmingFirst-order predicate logicProlog, DatalogRule engines, expert systems, program analysis
Query languagesRelational algebra and calculusSQL, SPARQL, CypherRetrieving and aggregating data
Constraint programmingConstraint satisfactionMiniZinc, constraint solversScheduling and resource allocation
Markup and configurationDocument and data modelsHTML, CSS, YAML, Terraform, NixUser interfaces and infrastructure
Declarative styles, foundations and typical languages

Purity varies across this spectrum. Haskell enforces pure functions at the type level, while Clojure and F# allow controlled side effects. Many mainstream languages, including Python, JavaScript, C# and Java, now offer declarative sublanguages such as list comprehensions, stream pipelines and LINQ inside an otherwise imperative core.

Declarative and imperative programming compared

The difference between declarative and imperative programming is who owns the algorithm. In imperative code the programmer writes loops, assignments and branches; in declarative code the programmer states the outcome and delegates the algorithm to an engine.

Filtering a list shows the contrast. An imperative version creates an empty result, loops over each item, tests a conditional statement and appends matches. A declarative version expresses the same intent in one line, for example [x for x in orders if x.total > 100] or a SQL WHERE clause, without managing the loop variable or result buffer.

AspectImperative programmingDeclarative programming
FocusSequence of state changesDescription of the desired result
Control flowExplicit loops and branchesImplicit, chosen by the engine
StateVariables updated in placeImmutable values or described state
Performance controlFine-grained and directIndirect, depends on optimizer quality
Readability for intentIntent buried in mechanicsIntent visible at a glance
DebuggingStep through each statementInspect plans, rules or derived output
Imperative versus declarative approaches

The boundary is a spectrum, not a strict divide. Declarative engines are themselves implemented imperatively, and practical systems mix both: an application may build a user interface declaratively while handling network requests with imperative callbacks.

Where declarative programming is used in practice

Declarative techniques dominate wherever a capable engine can outperform hand-written procedures or where describing a target state is safer than scripting changes. Databases, build systems and infrastructure tooling are the clearest examples.

  • User interfaces: React, SwiftUI and Jetpack Compose describe the interface as a function of state, and a reconciler applies the minimal changes.
  • Infrastructure as code: Terraform and Kubernetes manifests declare the desired state, and a controller converges real resources toward it.
  • Build systems: Make, Bazel and Gradle declare dependencies and outputs, and the tool decides what needs rebuilding.
  • Data pipelines: SQL and dataframe expressions let distributed engines plan joins, filters and partitioning.

The common pattern is desired-state reconciliation: describe the target, compare it with reality and let the system compute the difference. This makes repeated runs safe and keeps the description itself a reliable record of intent.

Trade-offs and common misconceptions

The main trade-off of declarative programming is reduced control over performance. When the engine chooses a poor strategy, such as a full table scan instead of an index lookup, the programmer must understand the hidden execution model to fix it, often through hints, indexes or restructured expressions.

SymptomLikely causeTypical fix
Query suddenly slows downOptimizer chose a new plan after data growthInspect the execution plan and update statistics
Recursive function exhausts memoryLazy evaluation built up unevaluated thunksForce strict evaluation or use an accumulator
Configuration applies unexpected changesDrift between declared and actual stateRun a plan or diff before applying
Logic program never terminatesRule order causes infinite searchReorder clauses or add termination conditions
Common problems in declarative code and how to address them

A frequent misconception is that declarative code is automatically slower or automatically faster. Neither holds: a mature optimizer often beats hand-written loops, yet an engine can also make costly choices. Another misconception is that declarative means no side effects at all; most real systems isolate effects rather than eliminating them.

The idea in brief

Declarative programming means telling the computer what you want, not how to get it. Ordering in a restaurant is a good comparison: you ask for a salad, and the kitchen decides how to wash, chop and plate it. Following a recipe yourself, step by step, is the imperative way.

Because the system handles the details, declarative code is usually shorter and easier to read. The trade-off is that when the result is slow or surprising, you need to understand what the system did behind the scenes.

A practical scenario

A data analyst at an online retailer needs monthly revenue per region for the past two years from an orders table of about 50 million rows. An earlier imperative script loaded the rows into application memory, looped over them and accumulated totals in a dictionary. It took around 25 minutes and sometimes ran out of memory.

The analyst replaced it with a single declarative SQL query using GROUP BY on region and month with a date filter. The database optimizer used an index on the order date and aggregated in parallel, returning the result in about 8 seconds. The query is also 12 lines instead of 90, so colleagues can review its intent at a glance.