Rows and columns

Part of the free LogicWiz Data Engineering course, Module 4: Storage and file formats. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 10:40 on Monday. Tess starts a new report on the shop's database: revenue by month, for three years. Twenty minutes later it is still running, and Dana is asking why checkout has slowed down for customers. The same database finds order 1042 in a millisecond.

You'll learn to

  • Tell the shop's small questions (OLTP) from an analyst's big ones (OLAP)
  • Count the pages a Postgres query has to read
  • Explain why keeping each column together makes a scan fast
  • Run one question on rows (Postgres) and on columns (Parquet)

Learn

One fast question, one slow one

Start with what each side asked.

The shop asks small questions all day: find order 1042, mark it shipped, show one customer's basket. Each one touches a few whole rows, found by their key, and must answer in milliseconds. Thousands arrive every second. This kind of work is called OLTP (online transaction processing).

Tess asked a different kind of question: revenue by month for three years. That is millions of rows, but only two or three columns of each. This kind of work is called OLAP (online analytical processing).

One way of laying data out on disk cannot be best at both. The rest of this lesson shows why.

The two kinds of work

OLTP: running the shopOLAP: understanding the shop
Place order 1081, mark 1042 shippedRevenue per country per month
A few rows, all their columnsMillions of rows, a few columns
Finds rows by key, through a B-tree indexScans and aggregates
Many users, milliseconds eachFew analysts, seconds are fine
Postgres, MySQL, SQL Server, OracleSnowflake, BigQuery, Redshift, Databricks SQL, DuckDB

A table is a file of pages

Nora looks at the slow report and asks one thing: "How many pages did it read?"

Postgres keeps a table as one file, cut into pages of 8 KB (8,192 bytes). Each page holds whole rows, one after another. A database that keeps a row's values together like this is called a row store.

Think of a filing cabinet with one sheet per order. Everything about order 1042 is on its sheet, so finding it is quick. Adding up one number from every sheet means pulling out every sheet.

The picture shows page 0 of a test table, big_orders (100,000 made-up orders), and one row on it.

Page 0 of big_orders, and one row on it

Two bars. The first splits an 8 KB Postgres page into a 24-byte header, 480 bytes of line pointers, 16 free bytes and 7,672 bytes of rows. The second splits one 64-byte row into its header, six column values and padding, with amount taking 5 bytes.

Read each bar left to right: the top bar is one page, the bottom bar is one order on it. The amber block is all a sum of amount needs: 5 bytes of the row. (Measured with pageinspect on this exact table.)

How many rows fit on a page

Work it out, one step at a time.

  • A page is 8,192 bytes. Its header takes 24, so 8,168 are left.
  • One order needs 57 bytes. Postgres rounds every row up to a multiple of 8, so it sits in a 64-byte slot.
  • Each row also needs a 4-byte line pointer at the front of the page, saying where the row starts. That makes 68 bytes a row.
  • 8,168 / 68 = 120 rows on a page.
  • 100,000 rows / 120 = 834 pages.

Postgres calls a stored row a tuple. Of this tuple's 57 bytes, 24 are a header Postgres keeps for itself, and only 5 are the amount.

See where the rows live

SELECT ctid, order_id, status, amount
FROM big_orders
ORDER BY order_id
LIMIT 3;

SELECT pg_column_size(order_id) AS id, pg_column_size(order_ts) AS ts,
       pg_column_size(status) AS status, pg_column_size(amount) AS amount
FROM big_orders
WHERE order_id = 1;

SELECT COUNT(*) FILTER (WHERE (ctid::text::point)[0] = 0) AS rows_on_page_0,
       COUNT(DISTINCT (ctid::text::point)[0]) AS pages_with_rows,
       pg_relation_size('big_orders') / 8192 AS pages_in_file
FROM big_orders;

ctid is a row's address: (0,1) means page 0, line pointer 1. The last query counts 120 rows on page 0 and 834 pages with rows in them. The file has 896 pages: a bulk load grows a table several pages at a time, and a scan reads the empty pages at the end too.

Three pages against 896

Now ask both questions of this table.

The shop's question is WHERE order_id = 54321. The primary key has an index: a small sorted structure that says which page each order is on. Postgres reads the index's top page (the root), one page at the bottom (a leaf), then the one table page. That is 3 pages.

Tess's question is SUM(amount). It has no shortcut. Every page holds whole rows, so to reach every amount Postgres has to walk every page.

Before you run them, make a guess.

Which pages each question reads

An index of two pages beside a table of 896 pages. A lookup of one order reads the two index pages and one table page; a sum of one column reads all 896 table pages.

  1. The table at rest. 100,000 orders sit on 896 pages. Beside them is the primary key's index, sorted by order_id.

  2. Find order 54321. Postgres reads the root page, then one leaf page, which gives the row's address. Then it reads that one table page. Total: 3 pages.

  3. Sum every amount. The index is no help: it is sorted by order, and the sum needs every row. Postgres reads all 896 pages, whole rows and all, to use 5 bytes of each row.

Press Next step and watch which boxes change colour: each coloured box is a page Postgres had to read.

Run both questions and count the pages

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT *
FROM big_orders
WHERE order_id = 54321;

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT SUM(amount)
FROM big_orders;

Read the Buffers lines: one buffer is one 8 KB page. The lookup shows 3. The sum shows 896: every page, every column of every row, to use one column.

Remember: a row store finds one row in a few pages, and reads every page to add up one column.

Turn the table sideways

What if the file kept all the amounts next to each other? Then all the statuses, then all the order_ids. A sum of amount would read the amounts and skip everything else.

A store laid out this way is called a column store. In the filing cabinet, it is one long sheet per column: a sheet of every amount, a sheet of every status.

Real column files do one thing first. They cut the rows into large groups, then store each group column by column, so one row's values are never far apart. Parquet calls the groups row groups; Snowflake calls them micro-partitions. This mixed layout is called PAX.

The same three orders, two layouts

LayoutWhat is stored next to what
Row store, page 01, 2, ..., shipped, USD, 0.37 then 2, 3, ..., delivered, USD, 0.74 then 3, 4, ..., cancelled, USD, 1.11
Column store, orderid chunk1, 2, 3
Column store, status chunkshipped, delivered, cancelled
Column store, currency chunkUSD, USD, USD
Column store, amount chunk0.37, 0.74, 1.11: three amounts side by side

To sum amount, the row store walks every row on every page. The column store reads the amount chunk and nothing else.

The same small orders table drawn twice, as row-store pages holding whole rows and as column-store chunks holding one column each; picking a query highlights the bytes each layout has to read.

Pick the lookup of one order (every column, one row), then the sum of one column (one column, every row). The highlighted bytes are what each layout reads: the row store wins the first, the column store the second.

Columns squeeze small

A column has a second gift. Its values share one type and repeat a lot, so they compress well.

Two tricks do most of the work. Dictionary encoding writes each different value once, then keeps a small code per row: placed is 0, shipped is 1. Run-length encoding writes a repeat as a count: "USD, 40,000 times".

The next example copies SwiftKart's 80 orders 500 times to get 40,000 rows. It writes them to Parquet, a file format that stores columns, and prints the bytes each column takes.

Before you run it, guess which column is the biggest.

The same orders, as columns

import duckdb

duckdb.sql("""CREATE TABLE orders AS
    SELECT o.* REPLACE (o.order_id + 1000 * r.range AS order_id)
    FROM 'data/orders.csv' AS o, range(500) AS r
    ORDER BY order_id""")
duckdb.sql("COPY orders TO 'orders.parquet' (FORMAT PARQUET)")
print(duckdb.sql("SELECT COUNT(*) FROM orders").fetchone()[0], "orders written to orders.parquet")

sizes = duckdb.sql("""
    SELECT path_in_schema AS column_name, SUM(total_compressed_size) AS bytes
    FROM parquet_metadata('orders.parquet')
    GROUP BY 1
    ORDER BY 2 DESC
""").fetchall()
total = sum(b for _, b in sizes)
for name, b in sizes:
    print(f"{name:12} {b:>8} bytes  {b / total:6.1%}")

parquet_metadata lists the pieces of each column in the file. status holds 40,000 values in under 3 KB (five words stored as codes), and currency, one value repeated, takes 56 bytes. order_id barely compresses and is three quarters of the file. A query that needs only status reads about 1% of it. (REPLACE swaps one column in o.*, so each copy gets new ids.)

Why the CPU likes columns

Speed is not only about the disk. Two more things happen inside the CPU.

First, memory reaches the CPU in fixed pieces of 64 bytes, called cache lines. Think of a tray that always carries 64 bytes. In the row store a tray brings one order, and the sum wants 5 of its bytes: over 90% is wasted. In a column of 8-byte amounts a tray brings 8 amounts, and every byte is used.

Second, a classic row engine hands data along one row at a time: 10 million rows, 10 million calls. This is called the Volcano model. A vectorised engine hands over a batch. DuckDB passes 2,048 values at a time, so 10 million rows take 10,000,000 / 2,048 = 4,883 calls. Inside a batch, the CPU can add several numbers with one instruction (SIMD).

One cache line, two layouts

Two bars of 64 bytes each. In the row store bar only 5 bytes are the amount; in the column store bar all 64 bytes are amounts, eight of them.

Each bar is one 64-byte cache line. Amber is what the sum uses: 5 bytes in the top bar, all 64 in the bottom one.

Ask DuckDB the same kind of question

import duckdb

duckdb.sql("""CREATE TABLE orders AS
    SELECT o.* REPLACE (o.order_id + 1000 * r.range AS order_id)
    FROM 'data/orders.csv' AS o, range(500) AS r
    ORDER BY order_id""")
duckdb.sql("COPY orders TO 'orders.parquet' (FORMAT PARQUET)")

print(duckdb.sql("""
    SELECT status, COUNT(*) AS orders
    FROM 'orders.parquet'
    GROUP BY status
    ORDER BY status
""").fetchall())

plan = duckdb.sql("EXPLAIN SELECT status, COUNT(*) FROM 'orders.parquet' GROUP BY status").fetchall()[0][1]
print(plan)

In the plan, the PARQUET_SCAN box lists only status: DuckDB asks the file for that one column, and every step above it works on batches of 2,048 values. Postgres answered its sum by reading every page. The column engine reads one column's chunks.

Do the sum for three years of orders

Back to Tess's report. Say three years of orders take 2 TB, in 6 columns of about the same width, and one machine reads 500 MB a second. She wants SUM(amount).

  • Row store: read everything. 2,000,000 MB / 500 = 4,000 s, about 67 minutes.
  • Column store: read one column of six. 333,333 MB / 500 = 667 s, about 11 minutes.
  • Column store, compressed 5 times: 66,667 MB / 500 = 133 s, about 2 minutes.

Unpacking costs some CPU, but fast compression methods unpack well over 1,000 MB a second on one core, faster than the data arrives. That is a 30-fold gap before you add a second machine.

Seconds to sum amount over 2 TB at 500 MB/s

Bars compare scan time: 4,000 seconds for a row store, 667 seconds for a column store reading one column of six, and 133 seconds when that column is also compressed five times.

Each bar is the time for one machine to read what the layout makes it read: the shorter the bar, the fewer bytes.

The trap: running reports on the shop's database. A big report reads every page. It competes with checkout for CPU and disk, and pushes the pages checkout needs out of Postgres's memory cache (shared_buffers). Copy the data out: to a read replica at least, to a warehouse or lakehouse properly.

The opposite mistake hurts too. In a column store one order is spread over many compressed chunks, so changing one row means rewriting or marking whole chunks. Do not run the shop on a warehouse. Systems that try to do both are called HTAP (SQL Server columnstore indexes, SingleStore, TiDB), but most companies keep the two apart.

Numbers to remember

WhatNumberGood to know
Postgres page8,192 bytes (8 KB)One "buffer" in EXPLAIN (ANALYZE, BUFFERS) is one page
Page header24 bytesThen 4 bytes of line pointer per row, growing forward; rows are packed from the end backwards
Tuple header23 bytes, padded to 24Transaction ids (Lesson 6.7 uses them), the row's own ctid, flags; a null bitmap is added when the row has nulls
Tuple sizeA multiple of 8 bytesEach value is aligned to its type, then the whole tuple is rounded up: 57 becomes 64
Cache line64 bytesx86 and most ARM servers
DuckDB vector2,048 valuesWhat one step hands to the next
Spark Parquet reader batch4,096 rowsspark.sql.parquet.columnarReaderBatchSize
SIMD register (AVX2)256 bitsAdds 4 int64 values with one instruction
Decompression, one coresnappy 1,500 MB/s, lz4 3,850 MB/sFrom the zstd project's benchmark

What changed at SwiftKart

Tess's report no longer touches the shop's database. A nightly job copies the orders out and writes them as columns, and the three-year report reads only the columns it needs. Checkout keeps its row store and its millisecond lookups.

This split shapes the whole trade. Row stores such as Postgres and MySQL run the business. Column stores such as Snowflake, BigQuery and Parquet files answer questions about it. Pipelines exist largely to carry data from the first to the second.

That copy has to be written in some file format. Lesson 4.2 picks one: CSV, JSON, Avro or Parquet.

In one line

A row store keeps whole rows together on 8 KB pages, so it finds one order fast; a column store keeps each column together, so it adds up one column fast.

Interview corner

What is the difference between OLTP and OLAP, and why do they want different storage?

OLTP is the operational workload: many small transactions that read and write a few whole rows by key, like placing an order. OLAP is fewer, heavier queries that scan many rows but few columns, like revenue per month. A row store keeps a row's values together on one page, so a key lookup touches 2 or 3 pages; a column store keeps each column together, so a scan of one column of six reads a sixth of the bytes, compressed. Companies run them on different systems and move data between them with pipelines.

Walk me through why SUM(amount) is slow on Postgres for a 100,000-row table.

A heap page is 8 KB with a 24-byte header, 4-byte line pointers and tuples of a 24-byte header plus the columns, rounded to 8 bytes. Here each row is a 64-byte slot, so a page holds 120 rows and the table about 834 pages, and the sequential scan reads every one of them (896 including empty pages), using 5 bytes of every 68. An index on amount would not help a full sum. On Parquet the same query reads only the amount column chunks, a few percent of the file.

What is vectorised execution and why does it speed up scans?

Instead of the Volcano model, where each operator returns one row per next() call, operators exchange batches: 2,048 values in DuckDB, 4,096 rows in Spark's vectorised Parquet reader. The per-call overhead is paid thousands of times less often, the data for one column sits in a contiguous array that fills whole 64-byte cache lines, and tight loops over arrays compile to SIMD instructions that process several values per instruction. Columnar storage and vectorised execution reinforce each other.

Why not run reports directly on the production database?

A big analytical query on a row store reads every page of the table, competing with live traffic for CPU, disk I/O and the buffer cache, so checkout slows down. The row layout also makes those scans slow. Reports belong on a read replica at minimum, and properly on a warehouse or lakehouse fed by a pipeline.