1974 Query Language Declarative External DSL

SQL

Structured Query Language

SQL

SQL is arguably the most successful DSL ever created — and possibly the most underappreciated design achievement in computing history. It takes a fundamentally hard problem (querying an arbitrary relational database) and makes it expressible in sentences that non-programmers can learn in an afternoon.

50+
Years in production
~1B
Instances running worldwide
40+
Major SQL dialects
#1
DB-Engines popularity (relational)

// Annotated Query — hover the highlighted terms

SELECTDML verb — begin a read operation  c.name, SUM(o.total)Projection — columns to return  AS revenueAlias — rename the expression
FROMSpecifies the primary relation (table)  customers cTable alias for brevity
JOIN orders o ON c.id = o.customer_idRelational join — combine matching rows
WHERE o.created_at > '2024-01-01'Filter predicate — applied before grouping
GROUP BYAggregation grouping key  c.nameMust match non-aggregate columns in SELECT
HAVING SUM(o.total) > 50000Filter applied AFTER aggregation (unlike WHERE)
ORDER BY revenue DESCSort by alias — evaluated last  LIMIT 10Restrict result set size;
-- Window functions: SQL at its most expressive
SELECT
  salesperson,
  region,
  quarterly_sales,
  RANK() OVER (
    PARTITION BY region
    ORDER BY quarterly_sales DESC
  ) AS regional_rank,
  quarterly_sales / SUM(quarterly_sales) OVER (
    PARTITION BY region
  ) AS share_of_region
FROM sales_data
WHERE quarter = 'Q4-2024';

// Design Decisions That Made SQL Great

  • Declarative, not procedural — you describe the result set, not the algorithm to build it. The query optimiser chooses the plan.
  • Set-based thinking — operations act on entire relations, not row-by-row loops. This enables massive parallelism.
  • English keywords — SELECT, FROM, WHERE, HAVING read like a specification document. Non-technical stakeholders can review queries.
  • Composability — subqueries, CTEs, and views let complex queries be built from simpler ones.
  • Standardisation — ANSI SQL means core queries port across databases. Dialects add power without breaking the base.
1996 Styling Language Declarative Cascade-based

CSS

Cascading Style Sheets

CSS

CSS is a study in elegant domain specificity. Its domain is visual presentation — and within that domain, it does things that no general-purpose language can do as concisely. A single CSS declaration can restyle thousands of elements simultaneously. The cascade, specificity, and inheritance — often cited as CSS's difficulties — are actually highly sophisticated solutions to a genuinely hard problem: style inheritance in a tree.

/* Container Queries — a DSL gaining new expressiveness */
@container article (min-width: 600px) {
  .byline {
    display: flex;
    gap: 1rem;
    align-items: center;
  }
  .byline-avatar {
    width: 48px;
    aspect-ratio: 1;
    border-radius: 50%;
  }
}

/* The cascade in action */
/* Specificity: 0-1-0 */
.card { color: navy; }
/* Specificity: 0-2-0 — wins */
.card.featured { color: crimson; }
/* Specificity: 1-0-0 — always wins */
#hero { color: goldenrod; }

// What Makes CSS Distinctively a DSL

  • Selector grammar — CSS selectors are a pattern-matching DSL embedded within the styling DSL. article > h2 + p::first-line navigates a document tree with extreme precision.
  • The cascade algorithm — a sophisticated resolution system for conflicting declarations, based on origin, specificity, and order. No general language implements this.
  • Inheritance tree — properties propagate through the document hierarchy automatically, matching the semantic structure of HTML.
  • Custom properties (variables) — introduced in 2017, these make CSS a programmable DSL — values can propagate and override down the cascade.
  • At-rules@media, @keyframes, @supports, @layer are sub-languages within CSS for responsiveness, animation, feature detection, and layering.
// CSS Specificity — calculated as three independent counters
A B C ID selectors #header class / attr / pseudo-class .active, [type], :hover element / pseudo-element div, p, ::before · · #nav .active > a:hover → 1·1·1 (beats 0·2·3)
1951 / 1986 Pattern Matching Formal Language

Regular Expressions

Regex / RE — a language of patterns

.*

Regular expressions are among the most compact DSLs ever devised — a pattern like ^\+?[1-9]\d{1,14}$ expresses an entire specification (E.164 phone number format) in twenty characters. They descend directly from Stephen Kleene's 1951 mathematical notion of regular sets, formalised into the regex syntax we know through Ken Thompson's 1968 implementation in ed. They are perhaps the purest example of a DSL rooted in formal language theory.

// ANNOTATED: email validation regex
^start anchor
[a-zA-Z0-9char class: alphanumeric
._-+ literal chars
]+one or more
@literal @
[a-zA-Z0-9char class
-]+one or more
(?:\.non-capture group: literal dot
[a-zA-Z0-9-]+domain segment
)*zero or more
\.literal dot
[a-zA-Z]{2,}$TLD, 2+ chars, end anchor
// live matches:
test@example.com  ·  user.name+tag@sub.domain.org  ·  invalid@com  ·  hello@world.co.uk
// Finite State Machine for regex: ab+c
q0 start q1 saw 'a' q2 saw 'b' q3 accept a b b c
# Named groups — regex as structured extraction
import re

pattern = re.compile(r"""
  (?P<year>\d{4})    # 4-digit year
  [-/]
  (?P<month>\d{1,2}) # 1–2 digit month
  [-/]
  (?P<day>\d{1,2})   # 1–2 digit day
""", re.VERBOSE)

m = pattern.search("Delivery: 2024-03-15")
print(m.group('year'))   # '2024'
print(m.group('month'))  # '03'

// The Regex DSL Paradox

  • Regex has write-only reputation — complex patterns become illegible even to their authors. The re.VERBOSE flag (shown left) adds comments to address this.
  • Regex is formally grounded — it corresponds exactly to the class of Regular Languages in the Chomsky hierarchy. This gives it mathematical guarantees: matching always terminates.
  • PCRE extended it beyond formal regular expressions with lookaheads, lookbehinds, and backreferences — making it technically more powerful than "regular."
  • Regex is universal — supported in virtually every language, text editor, and command-line tool on earth.
1986 Typesetting Scientific Publishing

LaTeX

Lamport's TeX — the language of scientific publishing

∑∫

LaTeX is the DSL that conquered academic science. The domain is scientific document preparation — and within that domain, it achieves something no GUI word processor ever has: mathematically perfect typesetting. A physicist can write \hat{H}\psi = E\psi and get the Schrödinger equation rendered with typographic precision impossible in Word. Over 60% of all academic papers in mathematics, physics, and computer science are written in LaTeX.

% Maxwell's Equations — expressed in LaTeX
\begin{align}
  \nabla \cdot \vec{E}  &= \frac{\rho}{\varepsilon_0} \\
  \nabla \cdot \vec{B}  &= 0 \\
  \nabla \times \vec{E} &= -\frac{\partial\vec{B}}{\partial t} \\
  \nabla \times \vec{B} &= \mu_0\!\left(\vec{J}
    + \varepsilon_0\frac{\partial\vec{E}}{\partial t}\right)
\end{align}

// LaTeX Design Philosophy

  • Semantic markup\emph{} means "emphasise," not "italicise." The style is separate from the structure, echoing HTML/CSS separation.
  • Extensible via packages — the CTAN archive has 6,500+ packages extending LaTeX into every scientific sub-domain. Each package is itself a mini-DSL.
  • Deterministic output — the same .tex source always produces identical PDF output. No GUI reflow surprises.
  • Version-controllable — plain text source plays beautifully with git, unlike binary Word documents.
2014 Infrastructure as Code Declarative HCL

Terraform / HCL

HashiCorp Configuration Language — infrastructure made declarative

Terraform's HCL is a masterclass in applying DSL thinking to infrastructure provisioning. Before Terraform, provisioning cloud resources meant imperative scripts — create this server, then configure this network, then attach this disk, handle the errors. HCL flips this: you declare the desired state, Terraform computes the diff against reality, and executes only what's needed. This mirrors SQL's declarative brilliance applied to a new domain.

# Terraform HCL — declare desired state, not steps
resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type

  vpc_security_group_ids = [
    aws_security_group.allow_http.id
  ]

  tags = merge(local.common_tags, {
    Name = "web-${var.environment}"
  })

  lifecycle {
    create_before_destroy = true
  }
}

output "public_ip" {
  value       = aws_instance.web.public_ip
  description = "The public IP of the web server"
}

// HCL's Key DSL Decisions

  • Resource graph — HCL builds an implicit dependency graph from references. aws_security_group.allow_http.id tells Terraform to create the SG first. No explicit ordering needed.
  • Idempotent by design — running Terraform twice produces no changes the second time. The plan is always computed from current state.
  • Interpolation expressions — string interpolation, function calls, and conditionals give HCL expressiveness without becoming a general programming language.
  • Providers as DSL extensions — each cloud provider's Terraform provider is a DSL vocabulary extension, adding its resource types to HCL's grammar.
  • State separation — state is stored externally; the HCL source is purely declarative.
2015 API Query Type System Facebook

GraphQL

A query language for your API — typed, introspectable, composable

GraphQL solves a specific, painful domain problem: clients over-fetching or under-fetching data from REST APIs. Facebook engineers in 2012 were struggling to power the mobile News Feed efficiently — too many REST calls, too much wasted bandwidth. GraphQL lets clients describe the exact shape of data they need, and the server returns exactly that. Its schema is itself a DSL — the Schema Definition Language (SDL) — that both documents and enforces the API contract.

# GraphQL SDL — the schema DSL within the query DSL
type Article {
  id: ID!
  title: String!
  author: User!
  tags: [Tag!]!
  body: String!
  publishedAt: DateTime
  comments(limit: Int = 10): [Comment!]!
}

type Query {
  article(id: ID!): Article
  articles(
    filter: ArticleFilter
    orderBy: ArticleOrderBy
    first: Int
    after: String
  ): ArticleConnection!
}

# Client query mirrors the response shape exactly
query FeaturedArticle($id: ID!) {
  article(id: $id) {
    title
    author { name avatar { url } }
    tags { name slug }
    comments(limit: 3) { body author { name } }
  }
}

// GraphQL's DSL Innovations

  • Hierarchical queries — query shape mirrors response shape. The client holds the pen: no more over-fetching.
  • Introspection — GraphQL APIs can be queried about themselves. IDEs and tools can auto-complete based on the live schema.
  • Fragments — reusable query pieces that enable composition. Define once, spread anywhere.
  • Subscriptions — the query language extends to real-time: subscription { messageAdded { text } }.
  • Strong typing — every field has a declared type. The DSL is its own contract between client and server.
2008 BDD Human-readable Tests

Gherkin

Behaviour-Driven Development — tests as readable specifications

🥒

Gherkin (used by Cucumber, Behave, and SpecFlow) is a DSL designed for a uniquely social purpose: writing automated tests that non-technical stakeholders can read and verify. Its domain is behavioural specification. A product owner, a tester, and a developer can all meaningfully engage with a Gherkin specification — which makes it one of the few DSLs designed as much for human collaboration as for machine execution.

# Gherkin — tests that product owners can read
Feature: User Account Deposits

  Background:
    Given a user "alice@example.com" exists
    And their account balance is £0.00

  Scenario: Successful deposit
    When alice deposits £50.00
    Then her account balance should be £50.00
    And she should receive a confirmation email

  Scenario Outline: Deposit limits
    When alice attempts to deposit <amount>
    Then the result should be <outcome>

    Examples:
      | amount   | outcome  |
      | £10.00   | success  |
      | £0.00    | rejected |
      | £10001   | rejected |

// Gherkin as a Social DSL

  • Given-When-Then — the three keywords map directly to precondition, action, and postcondition — the universal structure of any test case, in plain English.
  • Scenario Outlines — parameterised scenarios from tables. Data-driven tests that non-developers can extend.
  • Ubiquitous Language — Gherkin enforces Eric Evans' DDD concept of a shared vocabulary between technical and non-technical team members.
  • Living documentation — passing Gherkin tests are proof that the system matches the specification. The tests are the documentation.
Next: Future Directions → ← History