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.
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)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.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
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.
Practice this concept
Growth wants active-user counts by acquisition channel while PostgreSQL chooses the physical execution plan.
growthPrefix tables with growth.table_name.
channelactive_usersgrowth.users| Column | Type |
|---|---|
| id | integer |
| created_at | timestamp with time zone |
| country | text |
| channel | text |
| plan | text |
| activated_at | timestamp with time zone |
| churned_at | timestamp with time zone |
| legacy_user_code | text |
Sign up free to try it on a real business scenario