AlgoViz

OLAP

medium 26 min

OLAP (online analytical processing) answers big questions about a lot of history: totals, trends and comparisons.

Video lesson · Chapter 1 of 5

A two-year report meets a live checkout

0:00 / 5:07

OLAP in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A shop has two kinds of questions. "Is order 4711 paid?" is about one row and must be answered at once. "Which region grew most this year?" is about millions of rows and may take a few seconds. Online analytical processing, or OLAP, is the family of systems built for the second kind.

An OLAP system holds history, often years of it, copied from the databases that run the business. Its users are few: analysts, managers, dashboards and programs that train models. Almost every request is a read that scans, filters, groups and adds up.

The data is arranged for that work. Numbers sit in fact tables, the words used to group them sit in dimension tables, and each column is stored on its own so that a query reads only what it needs.

Why it exists

Running a huge report on the database that takes orders makes customers wait. The report fills the memory with old pages and keeps the disk busy. Moving it to another system protects the shop.

The layout matters as much as the separation. A row store reads whole rows even when a question needs two columns out of fifty. A column store reads the two, and equal values next to each other compress well.

One copy that joins all sources also gives everyone the same numbers. Without it, sales and finance each count revenue in their own way.

A short history

  1. 1993

    Edgar F. Codd, with S. B. Codd and C. T. Salley, publishes "Providing OLAP to User-Analysts" and gives the idea its name.

  2. 1996

    Ralph Kimball's book The Data Warehouse Toolkit appears. It spreads dimensional modelling: fact tables with dimensions around them.

  3. 1997

    Jim Gray and colleagues publish the data cube paper, which generalises GROUP BY, cross-tabs and subtotals into one operator.

  4. 2005

    Mike Stonebraker and others present C-Store, a column-oriented database, at the VLDB conference.

  5. 2010

    Google engineers publish Dremel: interactive analysis of very large datasets in columns.

Words to know

OLTP
Online transaction processing: many small reads and writes that run the business.
Data warehouse
A central store of data integrated from many sources. History is kept (time-variant) and rows are loaded, not edited (non-volatile).
Fact table
Rows of measurable events, such as one line of a sale, with keys and numbers.
Dimension table
Descriptions used to filter and group: time, product, customer, store.
Grain
What exactly one row of the fact table stands for.
Measure
A number in a fact table that can be added up or averaged.
Column store
Storage that keeps the values of one column together.
ETL and ELT
Extract, transform and load, or load first and transform inside the warehouse.

How it works

Step through the idea, or press Play.

Step 1 of 3

Copy. Changes leave the operational databases on a schedule or as a stream

Understand it

Start here

The beekeeper and a year of notebooks

A beekeeper writes one page for every visit to a hive: the date, the hive, the sky and the honey collected. That is perfect for looking up one visit. Then comes a different question: how much honey was there in total?

Reading a year by column
12345678910111212 notebooks

The notebooks stay. They are still the best place to write down the next visit.

The idea

The questions it answers

  • What were total sales last quarter?

    A total over a range of time.

  • Which region grows fastest?

    Two periods compared, group by group.

  • What sells best in winter?

    A ranking inside one slice of the year.

  • What will demand be next month?

    History as training data for a forecast.

Key properties

PropertyWhat it means
Complex queriesGrouping, totals, joins and window functions over millions or billions of rows
Read-heavyAlmost only SELECT; data arrives in batches or streams
HistoricalMonths or years: the last 12 months, this year against last year
Few usersAnalysts, data scientists, managers and dashboards, not every customer
Seconds, not millisecondsA typical target. Some engines answer in under a second

The path

From an order to a dashboard

The analytics pipeline

Four operational databases, orders, payments, customers and inventory, feed a pipeline. It batch loads a raw copy into a data warehouse, where the data is cleaned and then arranged as a star schema with summaries. Dashboards and reports scan the warehouse and give answers to a few analysts.
The sources on top serve customers. Everything below serves questions.
  1. 1

    Extract

    Pull raw data from databases, APIs, files and logs. Read a replica, or follow change data capture, so that customers feel nothing.

  2. 2

    Transform

    Clean, validate, remove duplicates, agree on names and units, join and aggregate.

  3. 3

    Load

    Put rows into fact and dimension tables. Many teams load the raw copy first and transform it inside the warehouse: ELT.

Three layers inside the warehouse

LayerAlso calledHolds
RawBronzeAn exact copy of the source. No changes, so any step can be repeated
StagingSilverCleaned and validated: types converted, duplicates removed
AnalyticsGoldReady for the business: star schemas, summaries, key figures

One night in the pipeline

If any step fails, run it again from the raw copy.

Storage

Why columns win here

A table with 50 columns of similar size, stored by row, must be read in full to add up one column. Stored by column, the engine opens one file in fifty. On top of that, a column holds one type of value, so it compresses well, and the processor can work on many values of it at a time.

Bytes read by a scan

B≈R×c×w×k109×2×8×14=4 GBB \approx R \times c \times w \times k \qquad 10^9 \times 2 \times 8 \times \tfrac14 = 4\ \text{GB}
R rows, c columns used, w bytes per value, and k the share left after compression. With 50 columns, uncompressed and by row, the same question reads 10^9 x 50 x 8 = 400 GB. The compression to a quarter is an assumption.

Two ways to compress a column

MethodExampleGood for
DictionaryNorth, South, North becomes 0, 1, 0Few distinct values
Run-lengthFive times North becomes North x 5Sorted columns

How a query skips data

The fastest byte is the one that is never read. Small minimum and maximum values per block make the second question cheap.

Model

The star schema

One fact table, four dimensions

A sales fact table in the middle with four keys, amount, quantity and profit. Around it are four dimension tables: time with date, month, quarter and year; product with name, category and brand; customer with name, segment and region; store with name, city and country.
Measures in the middle; when, what, who and where around it.
Fact tableDimension table
StoresEvents you can measure: sales, clicks, ordersDescriptions to filter and group by
ColumnsKeys to dimensions, and measuresA key and descriptive text
SizeVery large: millions or billions of rowsSmall: thousands to millions
Examplesamount, quantity, profit, discountname, category, region, status

Decide the grain first. If one row is one product line of an order, then counting rows counts lines. Orders need COUNT(DISTINCT order_id). Mixing two grains in one table is the classic way to get revenue twice.

SQL
SELECT t.quarter, p.category,       SUM(f.amount)              AS total_sales,       COUNT(DISTINCT f.order_id) AS num_orders,       AVG(f.profit)              AS avg_profit_per_lineFROM sales_fact fJOIN dim_time t    ON f.time_id = t.idJOIN dim_product p ON f.product_id = p.idWHERE t.year = 2024GROUP BY t.quarter, p.categoryORDER BY t.quarter, total_sales DESC;
Sales by category and quarter. The grain here is one line of an order.

A snowflake schema splits a dimension further: product, then category, then department. It stores each name once and adds joins. A star is more common, because dimensions are small and simple queries are worth more than the saved space. Facts stay normalised in both.

Cubes

Drill, roll, slice, dice and pivot

A cube is a way to see measures along several dimensions at once, such as time, product and region: a spreadsheet with more than two sides. Real cubes may have many dimensions, so the name is only a picture.

OperationWhat it doesExample
Drill-downSummary to detailYear, quarter, month, day
Roll-upDetail to summaryCity, state, country, region
SliceFix one value of one dimensionQ1 2024 only
DiceFilter several dimensionsElectronics, North America, Q4
PivotSwap the axesTime by product becomes product by time

How many summaries can a cube hold?

∏i=1d(Li+1)4 flat dimensions:;24=16 groupings\prod_{i=1}^{d} (L_i + 1) \qquad 4 \text{ flat dimensions}:; 2^4 = 16 \text{ groupings}
L is the number of levels in dimension i, plus one for "all". Time with four levels and three flat dimensions gives 5 x 2 x 2 x 2 = 40. Nobody stores them all; pick the ones people ask for.

Compute it now or keep it ready?

Sums of sums are right. Distinct visitors per day cannot be added into visitors per month.

Worked example

This year against last year

Compare revenue by region and category for two years. Three traps: an inner join drops a category that is new this year, a last-year total of zero divides by zero, and integer division cuts off the decimals.

SQL
SELECT s.region, p.category,       SUM(CASE WHEN t.year = 2024 THEN f.amount ELSE 0 END) AS y2024,       SUM(CASE WHEN t.year = 2023 THEN f.amount ELSE 0 END) AS y2023,       ROUND(100.0         * (SUM(CASE WHEN t.year = 2024 THEN f.amount ELSE 0 END)          - SUM(CASE WHEN t.year = 2023 THEN f.amount ELSE 0 END))         / NULLIF(SUM(CASE WHEN t.year = 2023 THEN f.amount ELSE 0 END), 0)       , 1) AS growth_percentFROM sales_fact fJOIN dim_time t    ON f.time_id = t.idJOIN dim_product p ON f.product_id = p.idJOIN dim_store s   ON f.store_id = s.idWHERE t.year IN (2023, 2024)GROUP BY s.region, p.category;
One scan, no self-join, and a new category shows up with an empty growth figure.

Compare

OLTP and OLAP side by side

OLTP: the cashierOLAP: the detective
WorkMany small reads and writesFew large reads
UsersThousands of customersA few analysts
LayoutRowsColumns
SchemaNormalisedStar, sometimes snowflake
TransactionsACID neededBatch loads are fine
Answer timeMillisecondsSeconds, sometimes less
DataThe current stateHistory

Where does this question go?

Technologies

Popular tools

ToolWhere it fits
SnowflakeCloud warehouse; columnar micro-partitions of 50 to 500 MB before compression
BigQueryGoogle Cloud; columnar storage, prunes partitions by the filter
RedshiftAWS; blocks hold the values of one column
ClickHouseColumn-oriented, open source or cloud, for real-time analytics
DuckDBRuns inside your program; columnar and vectorised
DruidReal-time analytics on streams and batches
HiveSQL over files in distributed storage
DatabricksA lakehouse: tables over files in cloud storage
VerticaAn analytics database
ParquetNot a database: a column file format many of them read

Dashboards sit on top: Tableau, Power BI, Looker and similar tools send SQL to the warehouse.

Practice

Good habits

Do

  • Use column storage, such as Parquet files.
  • Partition by date.
  • Keep summaries for common questions.
  • Use window functions for running totals.
  • Store the result of expensive joins.
  • Replace whole days, so that a job can run twice.

Avoid

  • SELECT * on huge tables.
  • Forgetting the partition filter.
  • Using the warehouse for transactions.
  • Skipping data quality checks.
  • Ignoring what a query costs.
  • Adding up distinct counts.

Summary

The whole topic in one minute.

OLAP systems answer questions about a lot of history. They scan few columns of many rows, so they store data by column, skip partitions that cannot match, and keep common totals ready.

Data arrives through a pipeline and is arranged as facts with dimensions around them. The price is freshness and slow single-row work, so transactions stay in the operational database. Always agree on two things first: the grain of a row, and how old an answer may be.

  • OLAP answers big questions about history; OLTP runs the business.
  • Columns win because a query uses few of them and they compress well.
  • Facts hold numbers, dimensions hold words, and the grain says what a row is.
  • Skip data first: partitions, then block ranges, then columns.
  • Drill-down adds detail, roll-up removes it, slice and dice filter, pivot turns.
  • Agree how old an answer may be before you build the pipeline.

Sources