Database Warehousing and Analytics · Lesson 99 of 112

Database Columnar Storage

What you will learn

  • The difference between a row store and a column store
  • Why analytical queries favour columns
  • How run-length encoding shrinks repeated values
  • Why column stores are weaker at single-row work
  • A fair way to read a speed demo

1. Two ways to lay out the same table

A table is a grid. The disk, however, stores a long line of bytes, so the database must choose an order for the grid.

order_id city quantity amount
1 Dhaka 3 360
2 Khulna 1 450
3 Dhaka 5 600

A row store writes one whole row after another:

1 Dhaka 3 360 | 2 Khulna 1 450 | 3 Dhaka 5 600

A column store writes one whole column after another:

order_id: 1 2 3
city:     Dhaka Khulna Dhaka
quantity: 3 1 5
amount:   360 450 600

Both hold exactly the same information. The ordinary databases you have used so far (SQLite, and the relational systems named in chapter 9) are normally row stores. Many analytical systems are column stores. Both are reached with SQL; the difference is below the surface.

2. Why columns help analysis

Think of a report: SELECT SUM(amount) FROM sales. It needs one column out of, say, 40. In a row store the database must read every row from disk, including the 39 columns it does not need, and pick out the amounts. In a column store it reads only the amount column: roughly 1/40 of the data.

Analytical queries typically touch few columns of very many rows, so this saves a lot. Operational queries (lesson 13.1) typically touch all columns of one row, and then the row layout is better: a whole record sits in one place.

3. A model you can run

We can imitate both layouts in plain Python: a list of tuples for the row store and a dictionary of lists for the column store. One million rows, five columns. The cities and numbers are generated by a simple rule.

import time

cities = ["Dhaka", "Chattogram", "Khulna", "Sylhet"]
n = 1_000_000
rows = [(i, cities[i % 4], i % 50, i % 7 + 1, (i % 90 + 10) * 10) for i in range(n)]   # row store
cols = {"id": [r[0] for r in rows], "city": [r[1] for r in rows], "product": [r[2] for r in rows],
        "quantity": [r[3] for r in rows], "amount": [r[4] for r in rows]}                 # column store

def best_ms(fn, repeat=5):
    times = []
    for _ in range(repeat):
        start = time.perf_counter()
        result = fn()
        times.append(time.perf_counter() - start)
    return result, min(times) * 1000

total_row, ms_row = best_ms(lambda: sum(r[4] for r in rows))
total_col, ms_col = best_ms(lambda: sum(cols["amount"]))
print(total_row == total_col, total_row)
print(f"row store    : {ms_row:.1f} ms")
print(f"column store : {ms_col:.1f} ms")
True 544996000
row store    : 65.6 ms
column store : 12.3 ms

Both layouts give the same total. On this one run, summing from the column layout took about a fifth of the time. Your numbers will differ on another machine or another run; only the order (columns faster) is the point.

A fair warning about this demo: it is a model. Part of the gap here comes from Python (sum over a ready-made list runs in fast built-in code, while the generator over tuples runs more Python steps), not only from memory layout. In a real database the extra cost of the row layout is mostly reading unneeded data from disk, and the benefit grows with the number of columns and rows.

Fetching one whole record is the opposite story. The row store has it in one piece; the column store must collect one value from each column:

print(rows[500_000])
print(tuple(cols[name][500_000] for name in cols))
(500000, 'Dhaka', 0, 5, 600)
(500000, 'Dhaka', 0, 5, 600)

Same answer, but the column version did one lookup per column. With 40 columns it does 40. Inserting a new record is also more work in a column store, because a value must be added to every column.

4. Compression

Values in a column resemble each other (all cities, all amounts), so columns compress well. One simple method is run-length encoding (RLE): replace a run of equal values with the value and a count.

def run_length(values):
    out = []
    for v in values:
        if out and out[-1][0] == v:
            out[-1][1] += 1
        else:
            out.append([v, 1])
    return out

print(run_length(sorted(cols["city"])))
[['Chattogram', 250000], ['Dhaka', 250000], ['Khulna', 250000], ['Sylhet', 250000]]

One million city names became four pairs. This only works this well because the column was sorted, so equal values sit together. Real systems combine several encodings (for example a dictionary that replaces each city by a small number) and can often work on compressed data directly, which is faster still. This lesson names the ideas only; details differ by product, so check the documentation of the system you use.

Run-length encoding of a real column, in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A sorted column is exactly a list of runs, and GROUP BY produces them: each value once, with the length of its run. The count of stored values drops to the count of runs:

SELECT country, COUNT(*) AS run_length FROM customers GROUP BY country ORDER BY country LIMIT 5;
SELECT COUNT(*) AS values_in_column, COUNT(DISTINCT country) AS runs_after_sorting FROM customers;
country     run_length
----------  ----------
Bangladesh          21
Brazil              30
Canada              27
Egypt               25
Ghana               26
(5 rows)

values_in_column  runs_after_sorting
----------------  ------------------
             420                  16
(1 row)
SELECT city, COUNT(*) AS run_length FROM customers GROUP BY city ORDER BY city LIMIT 5;
SELECT COUNT(*) AS values_in_column, COUNT(DISTINCT city) AS runs_after_sorting FROM customers;
city    run_length
------  ----------
Accra           14
Austin          15
Cairo           14
Dhaka           17
Hanoi           23
(5 rows)

values_in_column  runs_after_sorting
----------------  ------------------
             300                  16
(1 row)
SELECT enrolled_year, COUNT(*) AS run_length FROM students GROUP BY enrolled_year ORDER BY enrolled_year LIMIT 5;
SELECT COUNT(*) AS values_in_column, COUNT(DISTINCT enrolled_year) AS runs_after_sorting FROM students;
enrolled_year  run_length
-------------  ----------
         2023          83
         2024         102
         2025          86
         2026          89
(4 rows)

values_in_column  runs_after_sorting
----------------  ------------------
             360                   4
(1 row)

The fewer distinct values a column has compared with its number of rows, the better it compresses this way.

5. Row store or column store?

Row store Column store
Best at one record at a time; many small writes summaries over few columns of many rows
Typical use operational systems (OLTP) warehouses and analysis (OLAP)
Reading one full record fast slower (one lookup per column)
Inserting one record fast slower (touch every column)
Scanning one column reads all columns reads just that column
Compression moderate usually high

This is why a business often runs both: a row-oriented database for daily work and a column-oriented warehouse fed from it (lessons 13.1 and 13.4).

Worked example: choose a layout

A made-up phone company has two jobs.

  1. Billing screen: when a customer calls support, show their name, plan, balance, last five bills and open tickets. One customer, many columns, instant answer, and updates when they pay.
  2. Monthly analysis: the average call length by region for the last 24 months over 800 million call records. Only two columns (region and length) matter.

Job 1 reads whole records and writes often: a row store. Job 2 scans two columns of a huge table: a column store would read only those two columns and compress them well.

The company would keep the billing data in the row-oriented database and copy call records into a column-oriented warehouse for job 2.

Common mistakes

  • Treating a column store as a drop-in replacement for the operational database; it is slower at single-row reads and writes.
  • Believing one demo's numbers. Speed depends on the data, hardware and system; measure your own case.
  • Choosing columns because they sound modern. If reports are fast enough, a row store is fine.
  • Forgetting that sorting helps compression, and that the sort order is a design choice.

Key takeaways

  • A row store keeps records together; a column store keeps each column together.
  • Analytical queries read a few columns of many rows, so columns read less data and compress better.
  • Operational work reads or writes whole rows, so rows win there.
  • Run-length encoding and similar tricks work because a column holds similar values.
  • Warehouses are commonly column-oriented; operational databases are commonly row-oriented.

Practice

1. In which layout is SELECT SUM(amount) cheaper, and why?

Show answer

In the column layout: only the amount column is read. A row layout reads every column of every row.

2. Why is fetching one full customer record slower in a column store?

Show answer

Each column is stored separately, so the system must look up the value in every column and put the record back together.

3. What would run-length encoding do to the list A A A B B A?

Show answer

It would become [A, 3] [B, 2] [A, 1].

4. Why did the sorted city column compress to just four pairs?

Show answer

Sorting put equal cities next to each other, so each city formed one long run.

5. Why should you not trust the 65.6 ms and 12.3 ms figures as general facts?

Show answer

They come from one run on one machine and a Python model of the layouts. Different hardware, data or a real database would give different numbers.

6. A shop's checkout system and its yearly sales report: which should use which layout?

Show answer

Checkout: row store (many small writes of whole records). Yearly report: column store (summing a few columns across many rows), or a row store if the data is small enough.