SQL for Analytics

Updated · 12 min read
mediumPostgreSQL 18sqlanalyticsolapoltpstar-schemadata-warehousecolumnarinterview

Analytics SQL answers questions about many rows at once, such as "how much did we collect each month, by technology?", instead of reading or changing a few rows at a time. The Fee Tracker so far has been a transaction database: it records each enrollment and payment as it happens, and it's built to keep that data correct. Reporting on years of that data is a different job, and teams often copy the data into an analytics database with a different shape (a star schema) and a different storage design (a column store). In this lesson, we will compare the two kinds of database, build a small star schema from the Fee Tracker, write the kind of queries analysts run every day, and see what changes in data warehouses such as Snowflake, BigQuery and Amazon Redshift.

In One Minute

  • OLTP (online transaction processing): many small reads and writes, normalized tables, correctness first. The Fee Tracker is OLTP.
  • OLAP (online analytical processing): fewer, bigger queries that scan and summarize many rows, usually on a copy of the data.
  • A star schema has one fact table (events with numbers, such as payments) surrounded by dimension tables (who, what, when).
  • Column stores keep each column together on disk, so a query that reads 3 of 50 columns reads far less.
  • Analytics SQL leans on GROUP BY, GROUPING SETS, window functions and date bucketing.
  • Data warehouses (Snowflake, BigQuery, Redshift and others) are column stores built for this work.

Two Kinds of Workload

OLTP: running the businessOLAP: understanding the business
Typical query"Record Navika's payment"; "show Advitha's courses""Total fees by month and technology for two years"
Rows per queryA fewThousands to billions
WritesConstant, smallLoaded in batches (hourly, nightly)
DesignNormalized: each fact once (Normalization)Denormalized star schema: easy, fast to summarize (Denormalization)
StorageRow store: a row's columns togetherUsually a column store: a column's values together
ExamplesPostgreSQL, MySQL, SQL Server, OracleSnowflake, BigQuery, Amazon Redshift, ClickHouse, DuckDB

Why not run reports on the transaction database? On a small app you can, and many teams start that way, often on a read replica (Replication and Scaling). As data grows, big report queries compete with the app for the same server, and the normalized design needs many joins for every question. Copying the data into a separate analytics store, a process called ETL (extract, transform, load) or ELT (load first, transform inside the warehouse), lets each side be designed for its own job.

Run the business in OLTP; understand it in OLAP, on a copy shaped for questions

Building a Star Schema

A star schema puts the events you measure in one fact table, and the things you describe them by in dimension tables around it. For fees, each payment is a fact; the student, the course and the date are dimensions:

SQL▶ Try it
-- Dimensions: who, what and when
CREATE TABLE dim_student AS
SELECT student_id, first_name, city, state FROM students;
 
CREATE TABLE dim_course AS
SELECT course_id, title, technology, level FROM courses;
 
CREATE TABLE dim_date AS
SELECT d::date                        AS date_key,
       EXTRACT(YEAR FROM d)::int       AS year,
       EXTRACT(QUARTER FROM d)::int    AS quarter,
       to_char(d, 'YYYY-MM')           AS year_month,
       to_char(d, 'Dy')                AS weekday
FROM generate_series(DATE '2025-01-01', DATE '2026-12-31', INTERVAL '1 day') AS d;
 
-- The fact table: one row per payment, with keys and numbers only
CREATE TABLE fact_payment AS
SELECT payment_id, student_id, course_id,
       paid_on AS date_key, amount_usd,
       paid_on - due_on AS days_late
FROM payments;
 
SELECT count(*) AS facts FROM fact_payment;
SELECT count(*) AS days  FROM dim_date;
Output
SELECT 3
 
SELECT 6
 
SELECT 730
 
SELECT 7
 
 facts
-------
     7
(1 row)
 
 days
------
  730
(1 row)

Explanation: Each dimension keeps the descriptive columns analysts filter and group by. The date dimension has one row per day for two years, with ready-made columns such as year_month and quarter, so nobody has to repeat date functions in every report. The fact table holds only keys that point to dimensions, plus measures, the numbers to add up: amount_usd, and days_late, worked out once during loading (negative means paid early). Real warehouses use these same shapes with millions or billions of fact rows.

One fact table, three dimensions: a star

Analytics Queries

Analytics queries join the fact table to the dimensions they need, filter on dimension columns, and summarize the measures. Fees collected by month and technology:

SQL▶ Try it
CREATE TABLE dim_course AS
SELECT course_id, title, technology, level FROM courses;
CREATE TABLE dim_date AS
SELECT d::date AS date_key, to_char(d, 'YYYY-MM') AS year_month
FROM generate_series(DATE '2025-01-01', DATE '2026-12-31', INTERVAL '1 day') AS d;
CREATE TABLE fact_payment AS
SELECT payment_id, student_id, course_id, paid_on AS date_key, amount_usd
FROM payments;
 
SELECT dd.year_month, dc.technology,
       count(*)           AS payments,
       sum(f.amount_usd)  AS collected_usd
FROM fact_payment AS f
JOIN dim_date   AS dd ON dd.date_key  = f.date_key
JOIN dim_course AS dc ON dc.course_id = f.course_id
GROUP BY dd.year_month, dc.technology
ORDER BY dd.year_month, dc.technology;
Output
SELECT 6
 
SELECT 730
 
SELECT 7
 
 year_month | technology | payments | collected_usd
------------+------------+----------+---------------
 2025-08    | Java       |        1 |        450.00
 2025-10    | Java       |        1 |        250.00
 2025-11    | JavaScript |        1 |        225.00
 2025-12    | Java       |        2 |        800.00
 2025-12    | JavaScript |        1 |        225.00
 2026-01    | SQL        |        1 |        200.00
(6 rows)

Explanation: Every query in a star schema has this shape: the fact table in the middle, one join per dimension, GROUP BY the dimension columns you want to see. December 2025 was the busiest month, with three payments. Because the date dimension already has year_month, the report doesn't need to_char or date_trunc.

Subtotals and running totals come from tools covered earlier: ROLLUP (ROLLUP, CUBE and GROUPING SETS) and window functions (Window Functions):

SQL▶ Try it
SELECT to_char(paid_on, 'YYYY-MM') AS year_month,
       sum(amount_usd)             AS collected_usd,
       sum(sum(amount_usd)) OVER (ORDER BY to_char(paid_on, 'YYYY-MM')) AS running_total_usd
FROM payments
GROUP BY to_char(paid_on, 'YYYY-MM')
ORDER BY year_month;
Output
 year_month | collected_usd | running_total_usd
------------+---------------+-------------------
 2025-08    |        450.00 |            450.00
 2025-10    |        250.00 |            700.00
 2025-11    |        225.00 |            925.00
 2025-12    |       1025.00 |           1950.00
 2026-01    |        200.00 |           2150.00
(5 rows)

Explanation: The inner sum(amount_usd) totals each month; the outer sum(...) OVER (ORDER BY ...) adds the monthly totals up month after month. By January 2026 the program had collected $2,150.00 in all. Month-over-month change (lag), share of total, and rankings are other everyday analytics patterns built on the same window functions.

Column Stores

A row store keeps all of a row's columns together on disk; a column store keeps all of a column's values together. PostgreSQL, MySQL and SQL Server's default tables are row stores, ideal for "fetch this one payment with every column". A column store is ideal for "sum one column over a million rows":

Row storeColumn store
sum(amount_usd) over 10 million rowsReads every column of every rowReads only the amount_usd column
CompressionModerateHigh: a column holds similar values (many 'card's in a row)
Insert or update one rowFastSlower; usually loaded in batches
Best forOLTPOLAP

A rough example: a fact table with 20 columns, of which a report reads 2. A row store reads all 20 columns from disk; a column store reads 2, then compresses them well, so it often reads less than a tenth of the data. That's the main reason warehouses can scan billions of rows in seconds.

A column store reads only the columns a query uses

Data Warehouses at a Glance

Cloud data warehouses are managed column stores that separate storage from compute, so you can scale and pay for each separately.

WarehouseNotes
SnowflakeRuns on the major clouds; separate "virtual warehouses" (compute) over shared storage; billed for compute time and storage
Google BigQueryServerless: no servers to size; often billed by data scanned per query or by reserved capacity
Amazon RedshiftAWS's warehouse; based on a PostgreSQL-derived engine, so much of its SQL looks familiar; provisioned or serverless
OthersAzure Synapse and Microsoft Fabric, Databricks SQL, ClickHouse, DuckDB (embedded)

What changes in the SQL:

On a warehouseWhy
Select only the columns you needColumn stores (and per-scan pricing) reward reading fewer columns; SELECT * can cost real money
Filter on the partition or cluster column, usually a dateLets the warehouse skip whole blocks of data (Partitioning)
Primary and foreign keys are often not enforcedConstraints may be informational only; loading jobs must keep data clean
Updates and deletes are batch operationsPrefer loading new data and rebuilding summaries over row-by-row changes
Dialect differencesEach has its own date functions, QUALIFY (filter on window functions) in Snowflake and BigQuery, and semi-structured data types

Common Mistakes

Running heavy reports on the production primary. They slow down the app. Use a replica or a separate analytics store.

SELECT * on a warehouse. It reads every column and can cost real money. Name the columns.

Joining facts to facts. Two fact tables at different grains (payments and enrollments) joined directly multiply rows and inflate totals. Summarize each to the same grain first, then join (Joining Many Tables).

No date dimension. Every report repeats date functions and gets weeks and quarters slightly different. Build the calendar once.

Trusting unenforced keys. If the warehouse doesn't enforce uniqueness, a load that runs twice doubles every total. Check row counts after loading.

Interview Corner

What is the difference between OLTP and OLAP?

OLTP systems handle many small, fast transactions on normalized tables to run the business. OLAP systems run fewer, large queries that scan and summarize lots of data, usually on a denormalized copy in a column store.

What are fact and dimension tables?

A fact table records events with measures, such as each payment's amount, plus keys to dimensions. Dimension tables describe the who, what and when (student, course, date) that facts are filtered and grouped by.

Why are column stores fast for analytics?

A query reads only the columns it uses, and values in one column compress well, so far less data comes from disk. They are slower for single-row writes, which is why they suit batch-loaded analytics.

What is ETL?

Extract data from source systems, transform it (clean, join, reshape into facts and dimensions), and load it into the analytics store. ELT loads raw data first and transforms it inside the warehouse with SQL.

Practice

Challenge: Using the Fee Tracker tables, report each state and level with the number of payments and the total collected, plus a subtotal per state and a grand total, using ROLLUP.

Show solution
SQL▶ Try it
SELECT coalesce(s.state, 'ALL')  AS state,
       coalesce(c.level, 'ALL')  AS level,
       count(*)                  AS payments,
       sum(p.amount_usd)         AS collected_usd
FROM payments AS p
JOIN students AS s ON s.student_id = p.student_id
JOIN courses  AS c ON c.course_id  = p.course_id
GROUP BY ROLLUP (s.state, c.level)
ORDER BY s.state NULLS LAST, c.level NULLS LAST;
Output
 state |    level     | payments | collected_usd
-------+--------------+----------+---------------
 CA    | Beginner     |        2 |        650.00
 CA    | Intermediate |        3 |       1050.00
 CA    | ALL          |        5 |       1700.00
 TX    | Beginner     |        2 |        450.00
 TX    | ALL          |        2 |        450.00
 ALL   | ALL          |        7 |       2150.00
(6 rows)

ROLLUP (state, level) produces the detail rows, a subtotal for each state (level = ALL) and the grand total. California's five payments are all Srihitha's; Texas's two are Navika's. coalesce labels the subtotal rows; on real data where state itself might be NULL, use GROUPING(s.state) to tell a subtotal from a missing value (ROLLUP, CUBE and GROUPING SETS).

Quick check: SQL for analytics

4 questions
1Which query is typical OLAP?
2In a star schema for fees, what is the fact table?
3Why does a column store read less for sum(amount_usd)?
4What's a risk of joining two fact tables directly?

Key Takeaways

You want toUse
Totals by month and categoryFact table joined to dim_date and a dimension, GROUP BY
Subtotals and a grand totalGROUP BY ROLLUP (a, b)
Running totalssum(...) OVER (ORDER BY ...)
Ready-made calendar columnsA date dimension built with generate_series
Less data read on a warehouseNamed columns and a date filter

Was this tutorial helpful?

Lesson 110 of 115