Learn SQL/Beginner/SQL Foundations/How SQL Queries Work

How SQL Queries Work

You write what you want. You never write how to get it—that part is PostgreSQL's job.

SQL is Declarative

Most programming languages are imperative: you write the exact steps to take in order. SQL is declarative: you describe the result you want and the database figures out the steps.

IMPERATIVE — MOST LANGUAGES

Open the data, loop through every row, check the channel, and append each match.

for campaign in campaigns: if campaign.channel == "google_ads": results.append(campaign)
DECLARATIVE — SQL

Describe the outcome. PostgreSQL decides whether to scan rows, use an index, or choose another plan.

SELECT * FROM marketing.campaigns WHERE channel = 'google_ads';

What Happens When You Run a Query

Behind a short SQL statement, PostgreSQL runs a four-stage pipeline before data comes back.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
Watch a query travel the pipelineStage 1 of 4
1Parser
2Optimizer
3Execution engine
4Result set

ParserValidate the marketing.campaigns query, tables, and columns

Why This Matters

Because PostgreSQL decides how, it can physically execute a query differently from the written order. Logical clause order is fixed, which is what the next lesson breaks down.

Now You Try

Practice this concept

Growth wants active-user counts by acquisition channel while PostgreSQL chooses the physical execution plan.

Available schema
growth

Prefix tables with growth.table_name.

channelactive_users
growth.users
ColumnType
idinteger
created_attimestamp with time zone
countrytext
channeltext
plantext
activated_attimestamp with time zone
churned_attimestamp with time zone
legacy_user_codetext
query.sql
Beginner business practice

Sign up free to try it on a real business scenario