Skip to content

OLTP vs OLAP & Columnar Storage ​

"With a column store architecture, a DBMS need only read the values of columns required for processing a given query, and can avoid bringing into memory irrelevant attributes." — Stonebraker et al., C-Store: A Column-oriented DBMS, VLDB 2005

Summary: Transactions and analytics are two different workload shapes; row stores serve the first, column stores the second, and most real systems need both with a pipe between them. Focus: Row vs column layout, compression, vectorised execution, MergeTree, Parquet and lakehouse tables, dimensional modelling, ETL/ELT/CDC, PostgreSQL materialized views, HTAP, and the cost of reporting on the primary. Learning goal: Decide where a report should run (primary, replica, matview, column store), predict why it is fast or slow, and operate the pipeline that feeds it.

This page is the complete reference for the OLTP/OLAP split and for columnar storage. It covers workload shapes, row vs column layout, every compression scheme practitioners name (run-length, dictionary, delta, bit-packing, frame-of-reference), vectorised execution, late materialisation, zone maps (min-max), sort keys and ORDER BY in ClickHouse MergeTree, projections, the file formats Parquet, ORC and Arrow, star and snowflake schemas, facts, dimensions and slowly changing dimensions, ETL vs ELT, CDC feeds, data lakes and lakehouse table formats (Apache Iceberg, Delta Lake), DuckDB, the ClickHouse MergeTree family (ReplacingMergeTree, AggregatingMergeTree), PostgreSQL materialized views with incremental refresh (pg_ivm), HTAP (TiDB with TiFlash, SingleStore), reporting on replicas with replay conflicts, columnar inside PostgreSQL (Citus columnar, Hydra, pg_duckdb), and what a report does to a primary. It deliberately does not re-teach neighbours: how a row sits on a page is in Database Internals; B-tree vs LSM is in Storage Engines; BRIN and Bloom filters are in Bloom Filters & Probabilistic Structures; replication mechanics are in Replication & Failover; and the CDC mechanism itself is in Change Data Capture.

Page map ​

If you are looking forGo to
One-minute tables to memoriseEverything in one minute
Why two workload shapes need two designsWhy the split exists
C-Store, MonetDB/X100, Kimball, the papersWhere the vocabulary comes from
OLTP vs OLAP, row vs column, compression, vectors, zone mapsThe concepts, one by one
Sort keys, MergeTree, projections, Parquet, ORC, ArrowStorage and file formats
Star schema, facts, dimensions, SCDModelling for analytics
ETL, ELT, CDC, lakehouse, DuckDBGetting data there
Materialized views, pg_ivm, HTAP, replicas, Citus, HydraAnalytics inside the OLTP world
Every product side by sidePer-engine behaviour
Knobs, error codes, part countsMechanics
SQL + Go + Laravel for the report problemSolving the classic problems
Which tool for which workloadChoosing
Monolith to multi-regionIn architecture
Reproduce it: Postgres vs DuckDB vs ClickHouse, matview timingLab
Wrong beliefs, cheat sheet, questions, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The two workload shapes.

OLTPOLAP
Typical operationFetch/insert/update one order by keySum revenue by month and country over a year
Rows touchedA handfulMillions to billions
Columns touchedAll of themThree of forty
MetricLatency (ms), transactions per secondThroughput (rows/s, GB/s scanned)
ConcurrencyThousands of short sessionsTens of long queries
Layout that winsRow store (heap + B-tree)Column store
Write patternMany small writes, updates in placeBulk loads, append-mostly
ExamplesPostgreSQL, MySQL InnoDB, SQL Server, Oracle, CockroachDBClickHouse, DuckDB, BigQuery, Snowflake, Redshift, Parquet files

The techniques that make columns fast.

TechniqueIn plain wordsWhere you meet it
Column pruningRead only the columns the query namesEvery column store, Parquet readers
CompressionSame-type neighbours pack tightlyRLE, dictionary, delta, bit-packing, frame-of-reference, ZSTD/LZ4 on top
Vectorised executionProcess 1,000+ values per operator callDuckDB, ClickHouse, Velox, Photon
Late materialisationGlue columns into rows as late as possibleC-Store, Abadi 2007, TiFlash, ClickHouse PREWHERE
Zone maps / min-maxSkip a block when min..max cannot matchParquet statistics, ClickHouse granules and skip indexes, Snowflake micro-partitions
Sort keyRows stored in key order so ranges are contiguousORDER BY in MergeTree, Snowflake clustering, Iceberg sort order
Pre-aggregationCompute the answer onceMaterialized view, projection, AggregatingMergeTree

The ladder for a slow report (cheapest first; details in Choosing).

RungWhat you doCostStaleness
1Index and tune the queryLowNone
2Materialized view on the primaryOne refresh jobSchedule length
3Read replica for reportsOne replica, conflict settingsReplication lag
4Column store fed by CDC/ELTA second system and a pipelinePipeline latency
5Lakehouse on object storageCatalog, compaction, enginesCommit cadence

Why the split exists ​

One physical layout cannot be best at both jobs. A row store keeps all fields of a tuple together, so one page read serves a whole-row lookup; a column store keeps each column together, so a scan reads only what it needs and compresses well. Every design choice below is a point on one axis: cheap single-row writes and reads vs cheap wide scans.

Row-oriented (write-optimised)Column-oriented (read-optimised)
One write puts a whole row on diskOne row insert touches one file/chunk per column
Point lookup = one pagePoint lookup = many column files
Scan reads all columnsScan reads only named columns
Compression limited (mixed types per page)Compression excellent (one type, often sorted or repeated)
In-place update and delete are naturalUpdates are rewrites, delete markers or new versions
Strong transactional semanticsOften weaker: batch commits, eventual merges

The analogy we reuse on this page: a library. A borrower wants one specific book: walk to the shelf, take it, leave. That is OLTP, and shelving by title works. An auditor asks "how many books per publication year?" If the only arrangement is shelves, they must pull every book to read one line of its title page. They would rather have a card index with one drawer per attribute: all years in one drawer, in order, with runs written as "1998 x 40". That is a column store. Fetching one specific book through the card index means visiting every drawer, which is why the library keeps both, and why a librarian (the pipeline) copies new acquisitions into the index every night.

Three common misunderstandings, up front ​

  1. "Columnar is just faster." It is faster for scans of few columns over many rows. It is slower or unsupported for point reads, single-row updates and high-rate small writes. It is a different trade, not an upgrade.
  2. "A read replica solves analytics." It protects the primary from the load, but a replica is the same row store scanning whole pages, so the report is still slow, and heavy queries on a hot standby can be cancelled by WAL replay conflicts (see below).
  3. "A materialized view stays up to date." In PostgreSQL the contents are frozen at the last REFRESH; they are a cache you refresh, not an incrementally maintained index (unless you add pg_ivm).

Where the vocabulary comes from ​

The split is older than the vocabulary. Row-oriented systems were built for record-at-a-time transaction processing; the C-Store authors describe the design plainly:

"With this row store architecture, a single disk write suffices to push all of the fields of a single record out to disk. Hence, high performance writes are achieved, and we call a DBMS with a row store architecture a write-optimized system. These are especially effective on OLTP-style applications."

Their argument is that a different workload deserves a different layout: "systems oriented toward ad-hoc querying of large amounts of data should be read-optimized", and data warehouses, where "periodically a bulk load of new data is performed, followed by a relatively long period of ad-hoc queries", are the typical case. C-Store (Stonebraker, Abadi and co-authors from MIT, Brandeis, UMass Boston and Brown) is not the first column store; the paper itself credits Sybase IQ, Addamark and KDB as products that had already shown the efficiency in the warehouse market. Its contribution is the combination: compressed columns, overlapping sorted projections, a column-oriented executor, and a hybrid write store (WS) plus read store (RS) joined by a tuple mover. The paper reports itself as preliminary, so treat its benchmark numbers as 2005 research results, not as a current comparison.

The modern engines name their ancestry. DuckDB says its "vectorized execution engine is inspired by the paper MonetDB/X100: Hyper-Pipelining Query Execution", and Abadi, Myers, DeWitt and Madden's ICDE 2007 paper on materialization strategies is where late materialization is named and analysed. The dimensional-modelling side comes from Ralph Kimball, who "introduced the data warehouse/business intelligence industry to dimensional modeling in 1996 with his seminal book, The Data Warehouse Toolkit" (Kimball Group's own description). Bill Inmon's competing school (a normalised, enterprise-wide warehouse feeding marts) and Data Vault are the other two names you will meet in warehouse design discussions; this page follows Kimball because his star schema is what column stores are tuned for.

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition, a timeline or sequence, real scenarios, what each product does, and the fix in SQL, Go and Laravel (full code in Solving the classic problems).

OLTP vs OLAP: workload shapes Must-know ​

In plain words: OLTP (online transaction processing) is the app taking orders: lots of tiny reads and writes by key. OLAP (online analytical processing) is the business asking questions: a few huge reads that summarise history.

Common misunderstanding: "OLAP just means a big query." The shape is the point: many rows, few columns, aggregation, usually no concurrent updates to the data being read. A big SELECT * export is neither; it is a bulk read.

Definition: DuckDB's own wording for the second shape is "complex, relatively long-running queries that process significant portions of the stored dataset, for example aggregations over entire tables or joins between several large tables". A third shape, HTAP (hybrid transactional/analytical processing), claims both in one system; see HTAP.

text
OLTP session                             OLAP session
1  BEGIN;                                1  SELECT country, sum(amount)
2  SELECT * FROM orders WHERE id=881;    2  FROM payments
3  UPDATE stock SET qty=qty-1 WHERE ..;  3  WHERE ts >= '2026-01-01'
4  INSERT INTO payments ...;             4  GROUP BY country;   -- 400M rows, 2 of 40 columns
5  COMMIT;    -- 3 ms, 4 rows            5  -- 6 s, 800 MB scanned

Real scenarios: checkout, wallet transfers, inventory decrements, session writes (OLTP); month-end revenue by region, funnel analysis, fraud model features, finance reconciliation, product dashboards, ad-hoc analyst SQL (OLAP).

ProductDesigned forNotes
PostgreSQL, MySQL InnoDB, SQL Server, OracleOLTP (row store)Can run reports; costs the primary (see below)
SQLiteEmbedded OLTPSingle writer; fine for small reports, not scans of billions
MongoDBDocument OLTPAggregation pipeline works, but over documents, not columns
CockroachDBDistributed OLTPRow-oriented; export or changefeed to a warehouse for analytics
RedisKey-valueNot an analytical store
ClickHouse, DuckDB, BigQuery, Snowflake, RedshiftOLAP (column store)Weak at single-row update and transactions

Fix: decide per query which shape it is, and route accordingly (code in Solving).

Row vs column layout Must-know ​

In plain words: a row store writes id, customer, amount, ts next to each other for each row; a column store writes all ids together, then all customers, then all amounts.

Common misunderstanding: "A column store keeps the data as a table of columns that I can index like any other." Not quite: there is usually no per-row B-tree; the structure is sorted column chunks plus min-max metadata, and a "point lookup" is a scan of one narrow chunk.

Definition: a row store keeps all fields of a tuple contiguous on a page (heap pages, see Database Internals). A column store keeps each column contiguous: ClickHouse's MergeTree in Wide format stores "each column ... in a separate file in a filesystem"; Parquet lays each row group out as one chunk per column. The Parquet docs state that "Readers are expected to first read the file metadata to find all the column chunks they are interested in."

Row store (heap pages)Column store (one chunk per column)idcuststatusamounttsnoteidcuststatusamounttsnoteidcuststatusamounttsnotepage 1: every field of every rowpage 2page NidcustomeramountRLE / delta /bit-packingtsreads 100% of the tableto use roughly 1/6 of the bytesreads one column chunkskips the rest, decodes in vectorsQuery: SELECT sum(amount) FROM payments WHERE ts >= '2026-01-01'
text
Table: payments(id, customer, status, amount, ts)  -- 100 M rows, 6 columns
1  Row store:    sum(amount) reads every page   -> ~100% of table bytes
2  Column store: sum(amount) reads one chunk    -> ~1/6 of the bytes before compression
3  Compression:  amount column delta+bit-packed -> often 3-10x smaller again
4  Result:       10-100x less I/O; the exact factor depends on width, types and data order

Real scenarios: a 40-column event table where the dashboard reads 3 columns; a wide orders table where finance only needs amount and created_at; log analytics where message is large and rarely selected.

ProductLayoutDetail
PostgreSQL heap, InnoDBRowTuple on 8 KB (PG) / 16 KB (InnoDB) pages; TOAST/overflow for big values
ClickHouse MergeTreeColumnOne file per column per part (Wide), or one file (Compact) for small parts
ParquetColumn inside row groupsRow group → column chunk → pages
ORCColumn inside stripesStripe has index data, row data, footer
BigQueryColumn (Capacitor)"stores data in columnar format"
SnowflakeColumn inside micro-partitionsColumns stored independently, each compressed
SQL ServerRow, plus clustered columnstore indexColumnstore is a table-wide alternative layout for analytics
OracleRow on disk; Database In-Memory adds an in-memory column copyDual format
MySQLRow (InnoDB); HeatWave is a separate in-memory columnar engineCloud/Oracle product

Fix: keep OLTP tables as rows; for analytics copy the needed columns into a column engine (see ETL vs ELT).

Compression: RLE, dictionary, delta, bit-packing, frame-of-reference Must-know ​

In plain words: values in one column look alike (same type, often repeated, often nearly sorted), so you can write them in far fewer bytes than a row page allows.

Common misunderstanding: "Compression costs query speed." In a column store it usually adds speed: less data from disk and memory, and many operators run directly on the compressed form. C-Store's justification is a trade: "it makes sense to trade CPU cycles, which are abundant, for disk bandwidth, which is not."

Definition: these are the encodings you will see named in Parquet, ClickHouse codecs, DuckDB and C-Store.

EncodingHow it worksBest forExample
Run-length encoding (RLE)Store (value, count) for runsSorted or low-cardinality columnsA A A A B B → (A,4)(B,2)
Dictionary encodingReplace each distinct value by a small integer code and keep a dictionaryStrings with few distinct values (country, status)DE, FR, DE → dict {0:DE,1:FR}, codes 0,1,0
Delta encodingStore the difference from the previous valueTimestamps, ids, monotonic counters1,4,7,7,8,12 → 1,3,3,0,1,4
Bit-packingUse only as many bits per value as the largest needsSmall integers (codes, deltas)Codes 0..5 use 3 bits, not 32
Frame-of-reference (FOR)Subtract a block minimum, store small offsets, bit-pack themIntegers clustered in a range1000,1003,1001 → base 1000, offsets 0,3,1 in 2 bits
Bitmap per valueOne bit-vector per distinct value (itself RLE'd)Unsorted columns with very few distinct valuesC-Store's fourth scheme
General-purpose codec (LZ4, ZSTD, Snappy)Byte-level compression on top of the encoding aboveEverything, as the last stageClickHouse default LZ4; Parquet per-page codec

Parquet names several of these on its encodings page: RLE_DICTIONARY (dictionary with RLE/bit-packed codes), DELTA_BINARY_PACKED (delta plus per-block minimum plus bit-packing, in effect frame-of-reference over deltas), DELTA_BYTE_ARRAY (prefix compression for strings) and BYTE_STREAM_SPLIT (splits floating-point bytes into streams so the codec compresses better). ClickHouse exposes codecs per column: CODEC(Delta, ZSTD), DoubleDelta, Gorilla (floating-point time series), T64, and the LowCardinality(String) type as dictionary encoding.

text
Column ts (sorted, one per second) -> 1790000000, 1790000001, 1790000002, ...
1  Raw: 8 bytes each -> 8 MB per million rows
2  Delta: first=1790000000, then 1,1,1,1,... (constant)
3  RLE: (1, 999999)  -> a few bytes
4  Result: a sorted timestamp column nearly disappears

Real scenarios: a status column with five values (dictionary + bit-pack: 3 bits per row); a monotonic created_at (delta + RLE); a country column on a table sorted by country (RLE); a high-cardinality UUID column (compresses poorly, sort it and project it away if you can).

EngineWhere you control it
ClickHouseCODEC(...) per column, LowCardinality(...), ORDER BY to create runs
Parquet writersCompression codec per file/column; dictionary on by default; writer chooses encoding
DuckDBChooses lightweight encodings per segment automatically; you choose the sort order of data you load
PostgreSQL heapTOAST compresses only large values (pglz, lz4); no columnar encoding
Citus columnar / HydraPer-table compression (zstd, lz4, pglz, none) via alter_columnar_table_set
SQL Server columnstoreDictionary, RLE and bit-packing inside columnstore row groups

Fix (SQL): sort data by the low-cardinality column you filter on, and declare narrow types.

sql
-- ClickHouse: dictionary + delta + ZSTD, sorted so country forms runs
CREATE TABLE order_facts (
    order_id   UInt64 CODEC(Delta, ZSTD),
    created_at DateTime CODEC(DoubleDelta, ZSTD),
    country    LowCardinality(String),
    quantity   UInt32 CODEC(T64, ZSTD),
    unit_price Decimal(12, 2)
) ENGINE = MergeTree
ORDER BY (country, created_at);

The Go and Laravel loaders in Solving write batches into this table.

Vectorised execution Important ​

In plain words: instead of handing one row at a time from operator to operator, hand over a batch of a thousand values of one column and loop over it in a tight loop the CPU loves.

Common misunderstanding: "Vectorised means GPU or SIMD only." SIMD helps, but the main win is amortising the per-row interpretation overhead (function calls, branches, cache misses) over the whole batch.

Definition: DuckDB: "a large batch of values (a 'vector') are processed in one operation. This greatly reduces overhead present in traditional systems such as PostgreSQL, MySQL, or SQLite which process each row sequentially." ClickHouse says the same: operators "pass intermediate result rows in batches instead of single rows", which suits CPU caches and SIMD instructions. The contrast is the Volcano (iterator) model where next() returns one tuple, and code generation (JIT) as used by some row engines.

text
Volcano (row at a time)                  Vectorised
1  agg.next() -> filter.next()           1  scan.next() -> vector of 2048 amounts
2    -> scan.next() -> 1 tuple           2  filter(vector) -> selection vector
3  evaluate predicate for 1 row          3  sum(vector) -> one partial sum
4  repeat 400,000,000 times              4  repeat ~200,000 times

Real scenarios: sum, count, avg over a billion rows; GROUP BY on a low-cardinality key; filtering with WHERE amount > 100; decompress-and-aggregate in one pass.

EngineExecution model
DuckDBVectorised, pull-based, parallel across row-group "morsels"
ClickHouseVectorised blocks, SIMD, parallel pipelines
PostgreSQLRow-at-a-time (Volcano); optional JIT (LLVM) for expressions; parallel query across workers
MySQL InnoDBRow-at-a-time
SQL ServerBatch mode on columnstore
SQLiteRow-at-a-time bytecode VM

Fix: you do not write vectors; you choose an engine that has them and feed it columnar data. Inside PostgreSQL, extensions such as Citus columnar and pg_duckdb (below) bring vectorised or columnar scans without leaving the server.

Late materialisation Important ​

In plain words: do not rebuild full rows until you know which rows survive. Filter on narrow columns first, remember positions, and only then fetch the other columns for the survivors.

Common misunderstanding: "Early materialisation (build rows first, then filter) is simpler and so just as good." For selective predicates it reads and stitches far more data than necessary.

Definition: Abadi et al. describe scanning each predicate column, outputting the positions that match ("these positions can take the form of ranges, lists, or a bitmap"), intersecting them, and only then fetching the surviving values. Advantages: the executor keeps working "on compressed, column-oriented data" and can "defer tuple construction to later in the query plan, possibly allowing it to construct fewer tuples". ClickHouse's analogue is PREWHERE: read the filter columns first, then read the rest only for matching granules; TiFlash documents a "Late Materialization" feature in the same spirit.

text
SELECT name, amount FROM sales WHERE region = 'EU' AND amount > 1000
1  scan region          -> positions {2, 5, 9, 14, 20, ...}   (bitmap)
2  scan amount at those -> positions {5, 14}                  (still just positions)
3  intersect            -> {5, 14}
4  fetch name[5], name[14], amount[5], amount[14]   -- only now are rows built

Real scenarios: wide tables with a selective filter on one column and SELECT of strings; point-ish analytics ("all events of user 42 yesterday").

EngineMechanism
ClickHousePREWHERE (automatic for the cheapest selective filter)
TiFlashLate materialisation option (documented in the TiDB docs)
DuckDB, Parquet readersPredicate pushdown into the scan, filter-then-project
PostgreSQL heapNot applicable: it reads whole tuples

Fix (SQL): put the most selective, cheapest-to-read predicate columns in the WHERE; in ClickHouse, check EXPLAIN for PREWHERE.

Zone maps, min-max and data skipping Must-know ​

In plain words: for each block of rows, store the smallest and largest value of a column. A query for ts >= '2026-06-01' skips every block whose maximum is earlier.

Common misunderstanding: "A zone map is an index like a B-tree." It does not find rows; it only proves a block cannot contain a match. It works well only when data is physically ordered by the column (or loaded in time order); on shuffled data every block's min-max spans the whole range and nothing is skipped.

Definition: a zone map (min-max index, small materialised aggregate) is per-block metadata. Parquet keeps min/max statistics per column chunk and a page index; ClickHouse keeps one sparse index entry per granule ("blocks of 8192 rows called granules") and optional minmax, set and Bloom-filter data-skipping indexes; Snowflake keeps per-micro-partition metadata and prunes partitions with it; PostgreSQL's BRIN is the same idea for a heap (see Bloom Filters & Probabilistic Structures and Indexing); Iceberg stores column bounds per data file in manifests so planning prunes files.

text
Blocks (granules) of the ts column, data loaded in time order
1  block 1: min=Jan 01 max=Jan 31   -> skip
2  block 2: min=Feb 01 max=Feb 28   -> skip
3  block 3: min=Mar 01 max=Mar 31   -> READ  (query: ts >= Mar 15)
4  block 4: min=Apr 01 max=Apr 30   -> READ
-- shuffled load: every block says min=Jan 01 max=Apr 30 -> nothing skipped

Real scenarios: time-range dashboards on append-only events; "last 7 days" over a 3-year table; WHERE tenant_id = 77 on a table sorted by tenant.

ProductZone-map-like structure
ClickHouseSparse primary index per granule; skip indexes minmax, set, bloom_filter, ngrambf_v1
Parquet / ORCMin/max per column chunk, page index (Parquet); stripe and row-group indexes with min/max and optional Bloom filters (ORC)
SnowflakeMicro-partition metadata; clustering keys to improve pruning
Iceberg / DeltaPer-file column statistics in manifests / the transaction log
PostgreSQLBRIN (block-range min-max); declarative partitioning prunes partitions
DuckDBMin/max statistics on segments

Fix: control physical order, not just the index: sort at load time or choose the right ORDER BY (next block). SQL in Solving.

Sort keys, ORDER BY and the primary index in MergeTree Must-know ​

In plain words: in ClickHouse the table's ORDER BY decides how rows are physically sorted inside every part. Queries that filter on a prefix of that key read only the matching slice.

Common misunderstanding: "PRIMARY KEY in ClickHouse enforces uniqueness like PostgreSQL's." It does not. The docs: "The table's primary key determines the sort order within each table part (clustered index). The primary key also does not reference individual rows but blocks of 8192 rows called granules." It is a sparse index, and duplicates with the same key are allowed (see ReplacingMergeTree).

Definition: ORDER BY (a, b, c) sorts by a, then b, then c. The primary index (by default equal to the sort key, or a prefix of it) stores one entry per granule. A filter on a skips most granules; a filter only on c does not, unless the data happens to be correlated. Order the key from low cardinality to high, and put the columns you filter by most first. This is the ClickHouse analogue of Snowflake clustering keys, Iceberg sort order and Delta Z-ordering/liquid clustering.

text
ORDER BY (country, created_at)         query: WHERE country='DE' AND created_at >= '2026-06-01'
1  index lookup: country='DE' range   -> granules 410..780 of 12,000
2  within that: created_at >= June    -> granules 640..780
3  read only those granules' column chunks -> ~1.2% of the table
-- query: WHERE created_at >= '2026-06-01' only: country is the first key,
-- so every country's June slice is separate -> many granule ranges, weaker pruning

Real scenarios: multi-tenant analytics sorted by (tenant_id, ts); logs sorted by (service, ts); user-event tables sorted by (user_id, ts) for per-user history; choosing PARTITION BY toYYYYMM(ts) to drop old months cheaply.

ProductHow you declare the physical order
ClickHouseORDER BY, optional PRIMARY KEY prefix, PARTITION BY, SAMPLE BY
SnowflakeCLUSTER BY (automatic clustering service)
BigQueryPARTITION BY plus CLUSTER BY
IcebergPartition spec (hidden partitioning) and sort order
Delta LakePartitioning, OPTIMIZE ... ZORDER BY, liquid clustering
SingleStoreColumnstore sort key (documented under "Understanding Sort Key Selection")
PostgreSQLCLUSTER (one-off), BRIN with insertion order, partitioning

Fix: pick the sort key from the filters of your top five queries; do not re-sort later, because it means rewriting data. SQL in the Lab and Solving.

Projections Good to know ​

In plain words: a projection is a hidden second copy of a table (or of its aggregate) kept in another sort order, chosen automatically by the optimiser.

Common misunderstanding: "A projection is a view I query by name." You query the base table; the optimiser silently picks the projection when it scans less data.

Definition: ClickHouse: "Projections store data in a format that optimizes query execution"; "during the query analysis the projection with the least data to scan will be selected by ClickHouse without modifying the query provided by the user." C-Store used the same word earlier: its projections are overlapping, sorted column groups, each with its own sort order, so a query reads the projection sorted by what it filters. Vertica adopted that design. Cost: extra storage and extra work at insert and at merge.

text
Table sales ORDER BY (country, ts)            Projection by_product ORDER BY (product_id, ts)
1  query WHERE country='DE'                   -> base table
2  query WHERE product_id=77                  -> projection by_product (its sort key matches)
3  query sum(amount) GROUP BY product_id      -> aggregate projection, tiny scan
ProductEquivalent
ClickHouseALTER TABLE ... ADD PROJECTION
C-Store / VerticaProjections (the original idea)
PostgreSQLCovering index (INCLUDE), materialized view
SnowflakeMaterialized views, search optimization
Citus columnarNone (use a second table)

Fix: add a projection only for a proven, repeated query shape; each one multiplies insert cost.

Parquet, ORC and Arrow Must-know ​

In plain words: Parquet and ORC are files that store a table in column layout on disk or object storage. Arrow is the same idea in memory, so engines can pass columns to each other without converting.

Common misunderstanding: "Parquet is a database." It is a file format with no server, no locking and no updates in place; to change a row you write a new file. Iceberg or Delta add the table semantics on top (lakehouse).

Definition: a Parquet file starts and ends with the 4-byte magic PAR1 and ends with a footer holding the file metadata (schema, row-group list, per-column-chunk statistics, offsets). The docs: the format "is explicitly designed to separate the metadata from the data", and a reader starts from the footer. Layout: file → row groups → column chunks → pages (data pages plus an optional dictionary page). ORC is "a self-describing type-aware columnar file format", created in 2013 for Hive, organised in stripes with index data, row data and a stripe footer, with min/max and optional Bloom filters, and ACID support in Hive. Apache Arrow is a language-independent columnar memory format (plus IPC/Feather files and Flight RPC); DuckDB, ClickHouse, pandas and Spark exchange data through it.

text
my.parquet
1  PAR1
2  row group 0  -> column chunk a (dict page, data pages) | column chunk b | ...
3  row group 1  -> column chunk a | column chunk b | ...
4  footer: schema, row-group offsets, min/max per chunk, page index
5  footer length (4 bytes) + PAR1
-- reader: seek to the end -> read footer -> pick row groups by statistics -> read only needed chunks

Real scenarios: nightly export of the OLTP database to S3 as Parquet; Spark/Trino/DuckDB/ClickHouse all read the same file; ML training sets; sharing data between companies.

FormatKindStrengthWeakness
ParquetOn-disk columnarUniversal, nested types, page index, Bloom filterNo in-place update; small files hurt
ORCOn-disk columnarHive ecosystem, built-in indexes, ACID in HiveNarrower support outside Hive/Spark/Trino
Arrow (IPC/Feather)In-memory (and file) columnarZero-copy exchange, fast interchangeNot a long-term compressed archive format
AvroOn-disk row-orientedStreaming records and schema evolutionNot good for column scans
CSV / JSONText rowsHuman readableBig, slow, untyped

Fix (SQL, DuckDB):

sql
-- Convert and query without a server
COPY (SELECT * FROM read_csv('order_facts.csv'))
  TO 'order_facts.parquet' (FORMAT parquet, COMPRESSION zstd);
SELECT country, sum(quantity * unit_price) FROM read_parquet('order_facts.parquet') GROUP BY 1;

ClickHouse MergeTree family Must-know ​

In plain words: every INSERT writes a new small sorted chunk (a part); in the background ClickHouse merges small parts into bigger ones. Different engines in the family change what a merge does.

Common misunderstanding: "I can insert one row at a time like in PostgreSQL." Each insert makes a part; thousands of tiny parts make merges fall behind and ClickHouse starts rejecting inserts (Too many parts). Batch your inserts (tens of thousands of rows or more) or use asynchronous inserts.

Definition: the docs: "A part is created whenever a user inserts data into the table." A part is immutable and sorted by the key; part names like all_1_3_1 encode partition, min block, max block and merge level. Background merges combine parts (a k-way merge that keeps order). LSM-style, though without a memtable for the main data path (for the LSM comparison see Storage Engines).

INSERT batchesbatch 1batch 2batch 3Parts (immutable)all_1_1_0all_2_2_0all_3_3_0sorted by ORDER BYsorted by ORDER BYsorted by ORDER BYMerged partall_1_3_1k-way merge keeps sort orderdedup / aggregate rules run hereInside one part: a file per column + sparse primary indexidxmarkcol acol bcol ccol d1 index entry per granule (8192 rows)query skips granules the index rules outBackground merge
text
Time -> INSERT batches arrive; merges run in the background
1  t0  INSERT 100k rows  -> part all_1_1_0
2  t1  INSERT 100k rows  -> part all_2_2_0
3  t2  INSERT 100k rows  -> part all_3_3_0
4  t3  background merge  -> all_1_3_1 (parts 1..3 replaced after the merge finishes)
5  t4  SELECT reads all_1_3_1 (and any newer parts); old parts are removed later
-- for ReplacingMergeTree / AggregatingMergeTree, step 4 also applies the dedup/aggregate rule

The family:

EngineWhat a merge does to rows with equal sorting keyUse for
MergeTreeNothing; rows stayFacts, events, logs
ReplacingMergeTree([ver [, is_deleted]])Keeps the latest row per key (by ver); is_deleted marks deletesUpserts, latest state of an entity, CDC apply
SummingMergeTreeSums numeric columnsSimple counters
AggregatingMergeTreeCombines AggregateFunction states (sumState/sumMerge)Incremental aggregates, rollups via materialized views
CollapsingMergeTree, VersionedCollapsingMergeTreeCancel pairs with sign +1/-1Update/delete streams
Replicated*MergeTreeSame, plus replication via Keeper (ZooKeeper-compatible)Production clusters

Common misunderstanding (Replacing): the docs say ReplacingMergeTree "does not guarantee the absence of duplicates"; merges happen eventually, per part, in the background. To read the deduplicated state now, use SELECT ... FINAL (slower), argMax(col, ver) aggregation, or OPTIMIZE TABLE ... FINAL (heavy, avoid in routine use). AggregatingMergeTree "replaces all rows with the same primary key ... with a single row (within a single data part) that stores a combination of states of aggregate functions", so queries still run sumMerge(...) and GROUP BY to finish the job across unmerged parts.

sql
CREATE TABLE customer_latest (
    customer_id UInt64,
    country     LowCardinality(String),
    updated_at  DateTime,
    is_deleted  UInt8
) ENGINE = ReplacingMergeTree(updated_at, is_deleted)
ORDER BY customer_id;

-- Correct read before merges have happened:
SELECT * FROM customer_latest FINAL WHERE customer_id = 42;

-- Incremental aggregate: a materialized view feeds an AggregatingMergeTree
CREATE TABLE revenue_by_day (
    day     Date,
    country LowCardinality(String),
    revenue AggregateFunction(sum, Decimal(12, 2))
) ENGINE = AggregatingMergeTree ORDER BY (day, country);

CREATE MATERIALIZED VIEW revenue_by_day_mv TO revenue_by_day AS
SELECT toDate(created_at) AS day, country, sumState(unit_price * quantity) AS revenue
FROM order_facts GROUP BY day, country;

SELECT day, country, sumMerge(revenue) FROM revenue_by_day GROUP BY day, country;

Real scenarios: product event analytics (billions of events per day); CDC apply with ReplacingMergeTree keyed by primary key; real-time dashboards from an AggregatingMergeTree rollup; log storage with TTL to expire old partitions.

Knob / objectMeaning
index_granularity (default 8192)Rows per granule: index precision vs index size
PARTITION BY toYYYYMM(ts)Partition = unit for drop/move/TTL; do not over-partition
TTL ts + INTERVAL 90 DAYExpire rows or move to cold storage
async_insert=1Server-side batching of small inserts
system.parts, system.mergesInspect part counts and running merges
min_bytes_for_wide_partThreshold between Compact and Wide part format
Too many parts (code 252)Inserts outrun merges; batch, or fix the partition key

Write-path cost and the row-level semantics are the price: ClickHouse "mutations" (ALTER TABLE ... UPDATE/DELETE) rewrite parts and are heavy; lightweight deletes exist but are still not OLTP-grade.

Star and snowflake schemas, facts and dimensions Must-know ​

In plain words: keep one big table of events (facts: an order line, a click) and small tables of descriptions (dimensions: customer, product, date). Analysts group facts by dimension attributes.

Common misunderstanding: "Normalise the warehouse like the OLTP database." Normal forms from Schema Design protect writes; analytics deliberately denormalises so most queries join one fact to a few small dimensions, or none.

Definition: a star schema has a central fact table with foreign keys to denormalised dimension tables (Kimball: "Facts for measurements", "Dimensions for descriptive context", "Denormalized flattened dimensions"). A snowflake schema normalises the dimensions further (product → category → department), saving space and costing joins. Declare the grain first (one row per order line, per day per store); Kimball's design steps are business process, grain, dimensions, facts. Terms: surrogate key (a warehouse-owned integer key instead of the source's natural key), conformed dimension (the same customer or date dimension shared across fact tables), degenerate dimension (an order number kept in the fact), junk dimension (many low-cardinality flags in one table), role-playing dimension (date used as order date and ship date). Fact types: transaction, periodic snapshot, accumulating snapshot, and factless facts. Measures are additive, semi-additive (balances) or non-additive (ratios). Column stores often go one step further and flatten dimensions into the fact ("one big table"), because a repeated country string costs little after dictionary encoding and removes a join.

text
Star                                     Snowflake
1  fact_sales(date_sk, product_sk,       1  fact_sales -> dim_product -> dim_category -> dim_department
2             customer_sk, qty, amount)  2  more joins, less redundancy, fewer rows in dims
3  -> dim_date, dim_product,             3  -> good when a dimension is huge and has deep hierarchies
4     dim_customer (denormalised)        4  -> in column stores, usually flatten instead

Real scenarios: retail sales mart, ad impressions, SaaS usage metering, ride trips, financial ledgers (periodic snapshot), order fulfilment pipeline (accumulating snapshot).

ChoiceProsCons
StarFew joins, simple for analystsRedundant dimension text
SnowflakeSmaller dimensions, one place per hierarchyMore joins and harder SQL
One big table (OBT)Fastest scans in a column storeRewrites on dimension changes; wide
Data Vault (hubs, links, satellites)Auditable, load-friendlyNeeds marts on top for BI

Fix: model facts at the finest grain you can afford and derive aggregates, not the other way round. SQL:

sql
CREATE TABLE dim_customer (
    customer_sk bigserial PRIMARY KEY,
    customer_id bigint NOT NULL,
    country text NOT NULL,
    valid_from timestamptz NOT NULL,
    valid_to timestamptz,
    is_current boolean NOT NULL DEFAULT true
);
CREATE TABLE fact_order_line (
    order_id bigint, line_no int, date_sk int, customer_sk bigint, product_sk bigint,
    quantity int, amount numeric(12,2), PRIMARY KEY (order_id, line_no)
);

Slowly changing dimensions (SCD) Important ​

In plain words: customers move, products get renamed. History questions ("revenue by the country the customer lived in at the time") need the dimension to remember old values.

Common misunderstanding: "Just update the dimension row." That is Type 1 (overwrite): simple, but it silently rewrites history in every old report.

Definition (Kimball types): Type 0 retain original; Type 1 overwrite; Type 2 add a new row (with valid_from/valid_to/is_current and a new surrogate key); Type 3 add a new attribute (keep previous value in a column); Type 4 add a mini-dimension; Type 5 mini-dimension plus Type 1 outrigger; Type 6 Type 1 attributes added to a Type 2 dimension; Type 7 dual Type 1 and Type 2 dimensions.

text
Customer 42 moves from DE to FR on 2026-06-01
1  Before: sk=7  cust=42 DE valid 2024-01-01..NULL  current
2  Type 1 (overwrite): sk=7 cust=42 FR            -> old orders now appear under FR
3  Type 2: sk=7 cust=42 DE valid ..2026-06-01 not current
4         sk=9 cust=42 FR valid 2026-06-01..NULL current
5  Facts before June reference sk=7 (DE); new facts reference sk=9 (FR)

Real scenarios: sales by customer segment at time of sale, employee department history, price lists, subscription plan changes, regulatory reporting.

TypeHistory keptCostWhen
1NoneLowestCorrections, typos
2FullNew row per change, surrogate key lookup in ETLDefault for analytics-critical attributes
3One previous valueOne extra columnPlanned reorgs ("old region / new region")
4/5/6/7CombinationsMore tables or columnsFast-changing attributes, reporting on both current and historical

Fix: the Go and Laravel Type 2 loaders are in Solving. In column engines without row updates, implement Type 2 as insert-only plus ReplacingMergeTree or periodic rebuilds.

ETL vs ELT Important ​

In plain words: ETL cleans data before it reaches the warehouse; ELT dumps the raw data in first and cleans it inside with SQL.

Common misunderstanding: "ELT means no transformation." The transformation still exists; it moved into the warehouse, where cheap compute and SQL tooling (dbt-style models) make it versionable and re-runnable.

Definition: ETL = Extract, Transform, Load, with a separate transformation engine. ELT = Extract, Load, Transform: land raw copies (often as Parquet), then build staging, intermediate and mart layers with SQL. ELT dominates once warehouse compute is cheap and you want raw history for re-processing.

OLTP primaryPostgreSQL / MySQLorders, customersBatch extractnightly dump / queryCDC feedWAL / binlog via DebeziumETL: transformoutside the warehouseRaw landingParquet / stagingWarehouse (modelled)star schema, loaded cleanWarehouse / lakehouseraw tables, Iceberg / DeltaELT: transformSQL inside the engineMarts / BIfacts, dimensions, matviewsETL = Extract, Transform, Load (top path)ELT = Extract, Load, Transform (bottom path)
text
ETL                                       ELT
1  extract from OLTP                      1  extract from OLTP (or CDC)
2  transform in a pipeline server         2  load raw into warehouse/lakehouse
3  load clean star schema                 3  transform with SQL in the warehouse
4  -- fast queries, fixed schema          4  -- raw kept, re-run on logic change
AspectETLELT
Where transforms runSeparate engine (Spark, Airflow tasks, scripts)Inside the warehouse/lakehouse
Raw data keptOften notYes
Schema changesPipeline redeployNew SQL model
PII handlingMask before loadMust govern raw zone
Typical toolsInformatica, custom jobs, SparkFivetran/Airbyte + dbt, Spark SQL, Trino

Fix: a nightly batch is a COPY out and a bulk load; for low latency use CDC. Idempotent loads (merge/upsert keyed by primary key) make reruns safe.

CDC feeds into the warehouse Important ​

In plain words: instead of re-copying whole tables nightly, read the database's change log and ship each insert, update and delete as it commits.

Common misunderstanding: "CDC is just triggers." Log-based CDC reads the write-ahead log or binlog; it adds no write overhead to the transaction, preserves commit order and captures deletes. Mechanism and pitfalls are in Change Data Capture and Replication & Failover.

Definition: Debezium is an open source CDC platform: "point it at your databases, and your apps can start responding to all of the inserts, updates, and deletes that other apps commit to your databases". In an analytics pipeline the events land in Kafka or object storage, then a sink applies them to the column store (upsert into ReplacingMergeTree, MERGE into an Iceberg/Delta table). Initial load = snapshot, then stream.

text
1  PostgreSQL commits UPDATE orders SET status='paid' WHERE id=881
2  Logical decoding emits the change (replication slot)
3  Debezium -> Kafka topic shop.public.orders
4  Sink: insert (id=881, status='paid', version=lsn) into ClickHouse ReplacingMergeTree
5  Queries use FINAL or argMax to see the latest row; lag = commit to step 4
SourceCDC mechanism
PostgreSQLLogical decoding, wal_level=logical, replication slot, pgoutput
MySQLBinlog (binlog_format=ROW)
MongoDBChange streams (oplog)
SQL Server, OracleChange tracking / CDC tables, LogMiner
CockroachDBChangefeeds

Watch the operational trap: an unconsumed replication slot makes PostgreSQL keep WAL until the disk fills.

Data lake and lakehouse: Apache Iceberg and Delta Lake Important ​

In plain words: a data lake is files in cheap object storage (S3, GCS). A lakehouse puts a transaction log on top, so a folder of Parquet files behaves like a table with commits, schema changes and time travel.

Common misunderstanding: "A lakehouse replaces the OLTP database." It is an analytics store with atomic commits per table; it has no low-latency point writes or row locks, and small frequent commits create small files that need compaction.

Definition: a table format records which data files make up the table at each version. Apache Iceberg keeps a metadata file, manifest lists and manifests; a commit atomically swaps the pointer to a new metadata file, producing a snapshot; features include hidden partitioning, schema evolution, position and equality deletes (merge-on-read) or file rewrites (copy-on-write), and time travel. Delta Lake's protocol "brings ACID properties to large collections of data, stored as files, in a distributed file system or object store": a _delta_log of ordered JSON commits plus periodic Parquet checkpoints, with optimistic concurrency and deletion vectors. Apache Hudi is the third common format. A catalog (Hive Metastore, AWS Glue, a REST catalog, Unity, Nessie) maps table names to the current metadata.

text
Delta commit (two writers, optimistic)
1  W1 reads version 41, writes new data files, tries to commit 42.json
2  W2 reads version 41, writes new data files, tries to commit 42.json
3  W1 wins (atomic create-if-absent); W2 detects conflict
4  W2 re-checks whether its changes still apply, retries as 43.json or fails
-- Iceberg: the same race, resolved by atomically swapping the metadata pointer in the catalog
AspectIcebergDelta LakePlain Parquet folder
Atomic commitYes, via catalog pointer swapYes, via _delta_logNo
Time travelSnapshotsVersionsNo
Schema evolutionYesYesPer-file only
Row-level delete/updateDelete files or rewriteDeletion vectors or rewriteRewrite the file
EnginesSpark, Trino, Flink, DuckDB, ClickHouse, SnowflakeSpark, Trino, Flink, DuckDB (extension)Anything
Maintenancerewrite_data_files, expire_snapshotsOPTIMIZE, VACUUM (not the PostgreSQL VACUUM)Manual

Real scenarios: a CDC stream appended to Iceberg and read by Trino and DuckDB; a daily Spark job producing Delta marts; auditing with time travel; GDPR deletes via row-level delete files.

Fix: schedule compaction; keep a catalog; write in larger commits (every 1–15 minutes, not every second).

DuckDB: analytics in-process Important ​

In plain words: DuckDB is "SQLite for analytics": a library you link into your program (or the duckdb CLI) that reads Parquet, CSV and even PostgreSQL tables with a vectorised column engine, with no server to run.

Common misunderstanding: "DuckDB is a data warehouse." It is a single-process engine: great for gigabytes to a few terabytes on one machine, not a concurrent multi-user warehouse with many writers.

Definition: DuckDB: "For DuckDB, there is no DBMS server software to install, update, and maintain. By default, DuckDB does not run as a separate process but is completely embedded within a host process." It provides ACID through its own MVCC, a Parquet/CSV/JSON reader, and extensions (postgres, httpfs for S3, iceberg, delta). One writer process at a time can open a database file.

text
1  duckdb
2  INSTALL postgres; LOAD postgres;
3  ATTACH 'dbname=shop host=replica.db.internal' AS pg (TYPE postgres, READ_ONLY);
4  SELECT country, sum(amount) FROM pg.public.payments GROUP BY 1;   -- scanned by DuckDB's engine
5  COPY (SELECT * FROM pg.public.payments) TO 'payments.parquet' (FORMAT parquet);
UseFit
Ad-hoc analysis of a Parquet exportExcellent
Transform step in a pipeline (single node)Excellent
Embedded dashboards, local-first appsGood
Many concurrent writers / OLTPWrong tool
Multi-TB, many usersUse ClickHouse, Snowflake, BigQuery or a lakehouse engine

Fix: SQL in the Lab. In Go, DuckDB's client needs cgo, so on this page DuckDB appears only as SQL and CLI in the lab.

Materialized views in PostgreSQL and incremental refresh Must-know ​

In plain words: a materialized view stores the result of a query as a table. Reports read the small stored result instead of recomputing from billions of rows.

Common misunderstanding: "It updates itself." PostgreSQL does not maintain it; you run REFRESH, and that recomputes everything.

Definition: REFRESH MATERIALIZED VIEW "completely replaces the contents of a materialized view". Plain refresh takes an ACCESS EXCLUSIVE lock, so readers wait. With CONCURRENTLY it refreshes "without locking out concurrent selects", but "is only allowed if there is at least one UNIQUE index on the materialized view", and "only one REFRESH at a time may run against any one materialized view". Concurrent refresh computes the new result into a temporary table and applies a diff (inserts and deletes), so it is slower and uses more space than the plain form. WITH NO DATA creates an empty, unscannable view. Incremental maintenance does not exist in core.

pg_ivm (Incremental View Maintenance extension) fills the gap: "only incremental changes are computed and applied on views rather than recomputing the contents from scratch". You call pgivm.create_immv('name', 'SELECT ...') and triggers update the view in the same transaction as each base-table change; pgivm.refresh_immv rebuilds it. It supports a subset (inner and outer joins, DISTINCT, some aggregates such as count, sum, avg, min, max, simple subqueries and CTEs) and takes locks on the view during maintenance. The price is write amplification on the OLTP tables, so it suits moderate write rates and small result sets.

text
Plain matview, one refresh cycle (REFRESH ... CONCURRENTLY)
1  02:00  REFRESH starts: re-runs the full query on the primary (e.g. 40 s of heavy scan)
2  02:00..02:40  readers keep seeing the old rows
3  02:40  diff applied (short lock), new contents visible
4  02:40..next night  data is stale by up to a day
pg_ivm: UPDATE orders ... -> trigger adjusts the view in the same transaction (+ write latency, no staleness)
ApproachStalenessCost on primaryLimit
View (not materialized)NoneFull query every timeSlow
Matview + scheduled REFRESHSchedule lengthFull recompute per runNeeds UNIQUE index for CONCURRENTLY
pg_ivm IMMV~NoneExtra work on each writeQuery subset, extension required
Summary table maintained by triggers or app code~NoneExtra writes, your codeCorrectness is on you
ClickHouse AggregatingMergeTree + MVSecondsOff the primarySecond system
Snowflake / BigQuery materialized viewsAutomaticWarehouse computeVendor restrictions

Real scenarios: monthly revenue by country, leaderboard tables, inventory summaries, dashboards over a billion-row events table.

Fix: SQL, Go refresher and Laravel migration/command are in Solving (the matview snippets) and timed in the Lab.

HTAP: TiDB with TiFlash, SingleStore Important ​

In plain words: HTAP means "one database for orders and analytics". Usually it is an OLTP store with a column copy maintained next to it.

Common misunderstanding: "HTAP removes the pipeline." It hides the pipeline inside the product. Ask what isolates the two workloads, how stale the column copy is, and what the benchmark measured.

Definition: TiDB's docs: "TiFlash is the key component that makes TiDB essentially a Hybrid Transactional/Analytical Processing (HTAP) database. As a columnar storage extension of TiKV, TiFlash provides both good isolation level and strong consistency guarantee." Data is "asynchronously replicated" into TiFlash by acting as a Raft Learner, and the optimiser decides per query whether to read TiKV (rows) or TiFlash (columns), while reads are made consistent. SingleStore's columnstore ("also known as Universal Storage") is "the default table type" in SingleStore Helios; the same product also offers a rowstore table type, so one database can hold both shapes. C-Store itself was a hybrid (WS plus RS). Others: Oracle Database In-Memory, SQL Server clustered columnstore with a rowstore delta, MySQL HeatWave, AlloyDB columnar engine.

text
TiDB with TiFlash
1  INSERT/UPDATE -> TiKV (row store, Raft group, transactional)
2  Raft Learner replicates the log asynchronously -> TiFlash (column store)
3  SELECT sum(...) planner picks TiFlash (or MPP across TiFlash nodes)
4  Read waits until TiFlash has caught up to the read timestamp -> consistent, slightly later
ProductRow sideColumn sideLink between them
TiDB + TiFlashTiKVTiFlashRaft Learner, async
SingleStoreRowstore tablesColumnstore (Universal Storage, the default type)Same product, chosen per table
SQL ServerDelta storeClustered columnstoreTuple mover-like background compression
Oracle Database In-MemoryRow format on diskIn-memory column storeSame table, dual format
PostgreSQLHeapCitus columnar/Hydra/pg_duckdb (separate table or extension)You manage it
CockroachDB, MongoDBRows/documentsNone built inExport to a warehouse

Fix: treat HTAP as "pipeline included"; verify analytics will not steal CPU/IO from the transactional path (resource isolation or separate nodes).

Reporting on replicas and replay conflicts Must-know ​

In plain words: point the report at a read replica. The catch: the replica must keep applying changes from the primary while your long query runs, and some changes are impossible to apply under a running query.

Common misunderstanding: "A hot standby is a free analytics server." A long query can be cancelled when replay needs to remove rows the query could still see, and it only protects the primary if you do not set hot_standby_feedback carelessly.

Definition: PostgreSQL's hot standby docs: "When a conflicting query is short, it's typically desirable to allow it to complete by delaying WAL application for a little bit; but a long delay in WAL application is usually not desirable. So the cancel mechanism has parameters, max_standby_archive_delay and max_standby_streaming_delay". The common conflict is a cleanup (VACUUM removed rows your snapshot needs), which cancels the query with ERROR: canceling statement due to conflict with recovery (SQLSTATE 40001). Remedies: raise max_standby_streaming_delay (default 30 s; the docs say a decision-support standby may set "many hours, or even -1"), or set hot_standby_feedback = on, which "prevents VACUUM from removing recently-dead rows" and so cancels nothing, at the price that "this will delay cleanup of dead rows on the primary, which may result in undesirable table bloat". Another trap from the docs: DROP DATABASE on the primary disconnects everyone on the standby immediately. See MVCC & VACUUM for why dead rows pile up and Replication & Failover for lag.

text
Replica conflict timeline (max_standby_streaming_delay = 30s)
1  t=0     analyst starts a 10-minute report on the standby (snapshot S)
2  t=60    primary VACUUM removes rows still visible to S; WAL record arrives at the standby
3  t=60    replay would remove rows S needs -> replay waits (lag grows)
4  t=90    delay budget exhausted -> report cancelled: conflict with recovery
5  fix A   raise the delay (lag may grow long)   fix B  hot_standby_feedback=on (primary bloat)
           fix C  dedicated analytics replica with big delay, never used for failover
KnobWhereEffect
max_standby_streaming_delayStandbyHow long replay waits before cancelling conflicting queries
max_standby_archive_delayStandbySame, for WAL read from archive
hot_standby_feedbackStandbyTell primary the oldest snapshot; prevents cleanup conflicts, delays VACUUM
statement_timeoutSession/roleStop runaway reports on any node
wal_level, hot_standbyPrimary/standbyNeeded for a hot standby to exist

Fix: the Go reportpool snippet in Solving isolates pools and retries a conflict cancellation; a dedicated analytics replica with generous delay and its own failover role is the usual design. Logical replicas and CDC avoid the conflict entirely because they are separate databases.

Columnar inside PostgreSQL: Citus columnar, Hydra, pg_duckdb Good to know ​

In plain words: you can get column storage without leaving PostgreSQL by choosing a different table access method or an engine extension.

Common misunderstanding: "A columnar extension makes my OLTP table fast for reports." Columnar tables are separate tables (often append-only); you copy or partition data into them.

Definition: Citus docs: "Citus 10 introduces append-only columnar table storage for analytic and data warehousing workloads. When columns (rather than rows) are stored contiguously on disk, data becomes more compressible, and queries can request a subset of columns more quickly." Use CREATE TABLE ... USING columnar, tune with alter_columnar_table_set, and the docs describe archiving old row partitions to columnar storage. Hydra Columnar is an open source columnar extension for PostgreSQL derived from this design. pg_duckdb (built with Hydra and MotherDuck) "integrates DuckDB's columnar-vectorized analytics engine into PostgreSQL". Others: TimescaleDB hypercore (row-to-column compression of older chunks).

sql
CREATE EXTENSION citus;
CREATE TABLE events_archive (LIKE events) USING columnar;
INSERT INTO events_archive SELECT * FROM events WHERE ts < now() - interval '90 days';
SELECT country, count(*) FROM events_archive GROUP BY country;  -- column scan, compressed
OptionStorageUpdatesGood for
Citus columnarColumnar access methodAppend-orientedArchives, logs, fact history inside PG
Hydra ColumnarColumnar access methodAppend-orientedSame, open source
pg_duckdbRuns queries with DuckDB, reads Parquet/IcebergNot applicableAnalytics and Parquet queries from PG
Partitioned heap + matviewRowNormalSmall-to-medium reporting

Fix: move data older than N days to a columnar partition; keep recent rows in the heap.

The cost of running reports on the primary Must-know ​

In plain words: a heavy report on the same server as checkout competes for the same CPU, memory, disk and snapshot machinery. It is not wrong work; it is on the wrong machine.

Common misunderstanding: "It only reads, so it cannot hurt writers." Readers do not block writers in MVCC, but they hold a snapshot, burn I/O and CPU, and delay VACUUM.

Definition and costs: (1) Buffer cache: a big scan can evict hot pages; PostgreSQL limits this for sequential scans with a small buffer ring, but index scans, hash joins and sorts still compete, and cold pages mean random I/O for checkout. (2) I/O and CPU: parallel workers (max_parallel_workers_per_gather) and work_mem spills to temp files. (3) Snapshots: a long transaction pins the xmin horizon, so VACUUM cannot remove dead rows created after it started: bloat and slower checkout (MVCC & VACUUM). (4) Connections: a report holds one for minutes (Connection Pooling). (5) Locks: some report DDL or REFRESH without CONCURRENTLY takes strong locks.

text
Month-end, 09:00 on the primary
1  finance: SELECT ... FROM orders JOIN order_items ... (reads 90 GB, 8 minutes)
2  checkout p99 climbs 40 ms -> 300 ms (shared buffers, disk queue)
3  autovacuum cannot clean orders (xmin pinned)  -> bloat for the next days
4  the same query on a replica / column store: checkout unaffected
MitigationEffectCost
statement_timeout, idle_in_transaction_session_timeoutBounds the damageReport may fail
Separate role with low work_mem/max_parallel_workersSmaller footprintSlower report
ReplicaIsolationReplay conflicts, lag
Matview refreshed off-peakMoves the heavy work in timeStale data
Column storeMoves it away and makes it cheaperPipeline

Fix: measure with Database Observability (pg_stat_activity long queries, pg_stat_statements), then climb the ladder in Choosing.

Per-engine behaviour ​

"Never name a feature without naming the product." This table is the one to bookmark.

CapabilityPostgreSQLMySQL InnoDBSQL ServerOracleSQLiteMongoDBCockroachDBRedisClickHouseDuckDB
Primary layoutRow (heap)Row (clustered B+tree)Row; columnstore index optionalRow; In-Memory column copy optionalRowDocument (BSON)Row (LSM, Pebble)In-memory structuresColumnColumn
Point lookup by keyFastFastFastFastFastFastFastFastestPoorPoor
Large aggregateSlow at scale (parallel query helps)SlowFast with columnstoreFast with In-MemorySlowAggregation pipeline, slow at scaleSlowNot applicableExcellentExcellent (one node)
Row-level update/deleteNative (MVCC)NativeNative (columnstore: delete bitmap + delta)NativeNativeNativeNativeNativeMutations or merge-time rulesSupported, bulk-optimised
Materialized viewYes, manual refresh; incremental via pg_ivmNo built-inIndexed views (maintained)Yes, fast refreshNoOn-demand views via $mergeNo built-inNoYes, insert-time MVNo (create tables)
Reads ParquetVia FDW/pg_duckdb/extensionsNoPolyBase/OPENROWSET (vendor docs)External tablesNoNoNoNoYes (table function and engine)Yes (native)
Columnar option insideCitus columnar, Hydra, pg_duckdb, TimescaleDBHeatWave (separate engine)Clustered columnstoreDatabase In-MemoryNoneNoneNoneNoneNativeNative
HTAP storyExtensions and replicasHeatWaveColumnstore with deltaIn-MemoryNoneAtlas analytics nodes (vendor)None built inNoneNot HTAPNot HTAP
CDC outLogical decodingBinlogCDC / change trackingLogMiner / GoldenGateNoneChange streamsChangefeedsKeyspace notifications / streamsConsumesConsumes

What the warehouse products do:

ProductStorageNotes
BigQueryColumnar (Capacitor) on Colossus"stores data in columnar format"; serverless; partition + cluster
SnowflakeMicro-partitions, columnar, each column compressedPruning by per-partition min/max; clustering keys
RedshiftColumnar MPP, sort and dist keysAWS; zone maps per block
ClickHouse Cloud / self-hostedMergeTree on local disk or object storageReal-time analytics
Trino / Spark + Iceberg/DeltaParquet files + table formatLakehouse
TiDB + TiFlashRaft Learner column replicaHTAP

Mechanics ​

Anatomy of a column scan Important ​

  1. The planner picks the columns, applies partition and file pruning from metadata (partition values, Parquet footer, Iceberg manifest, ClickHouse sparse index).
  2. For surviving blocks the reader decompresses only the needed column chunks (last-stage codec such as LZ4/ZSTD, then encoding such as dictionary or delta).
  3. Predicates are evaluated on the encoded or decoded vector; a selection vector or bitmap of positions is produced (late materialisation).
  4. Operators (aggregation, join probe) run over vectors; hash aggregation uses per-thread tables merged at the end.
  5. The result stream is built from the surviving positions.
text
Scan of order_facts, query: WHERE country='DE' AND created_at >= '2026-06-01'
1  parts/files:  120 -> pruned by partition (month) to 6
2  granules:     48,000 -> primary index narrows to 3,100
3  columns:      5 total -> read 3 (country, created_at, quantity*unit_price)
4  decompress:   LZ4 -> Delta/DoubleDelta -> vector of 8,192
5  aggregate:    partial sums per thread -> merge -> result

Knobs and settings you will actually touch Must-know ​

ProductParameterMeaning
PostgreSQLmax_parallel_workers_per_gatherParallel scan workers per query node
PostgreSQLwork_mem, temp_file_limitMemory per sort/hash; spill cap
PostgreSQLstatement_timeout, idle_in_transaction_session_timeoutBound runaway reports and idle snapshots
PostgreSQLmax_standby_streaming_delay, max_standby_archive_delay (default 30 s), hot_standby_feedbackReplay vs report trade on a standby
PostgreSQLwal_level=logical, max_replication_slots, max_slot_wal_keep_sizeNeeded for CDC; cap WAL kept by a slot
PostgreSQLREFRESH MATERIALIZED VIEW [CONCURRENTLY]Needs a UNIQUE index for CONCURRENTLY
ClickHouseindex_granularity (8192), PARTITION BY, ORDER BY, TTLLayout and expiry
ClickHouseasync_insert, wait_for_async_insertBatching tiny inserts
ClickHouseparts_to_delay_insert, parts_to_throw_insertBack-pressure thresholds when parts accumulate
ClickHousemax_threads, max_memory_usageParallelism and per-query memory
DuckDBthreads, memory_limit, temp_directoryResource controls; spills to disk
Parquet writersRow-group size, page size, codec, dictionary on/offPruning granularity and ratio
Iceberg/DeltaTarget file size, compaction, snapshot expirySmall-files cost and metadata growth

Errors and signals to recognise Must-know ​

WhereMessage / codeMeaningAction
PostgreSQL standbycanceling statement due to conflict with recovery, SQLSTATE 40001Replay needed to remove rows the report could seeRetry, raise delay, or use a dedicated replica
PostgreSQLSQLSTATE 57014 (query_canceled)statement_timeout or cancelRaise limit or optimise
PostgreSQLcannot refresh materialized view "x" concurrently (needs unique index)Missing UNIQUE indexAdd the index
PostgreSQLSlot retention / disk full on primaryUnconsumed replication slotDrop/advance slot; set max_slot_wal_keep_size
ClickHouseToo many parts (code 252)Inserts outrun mergesBatch inserts; coarser PARTITION BY
ClickHouseMEMORY_LIMIT_EXCEEDED (241)Query over max_memory_usageFilter earlier, spill to disk, raise limit
DuckDBOut of Memory ErrorOver memory_limitRaise limit, set temp_directory
Delta / IcebergCommit conflict / ConcurrentModificationExceptionOptimistic commit lost the raceRetry the operation

Compression ratios and layout, rules of thumb Good to know ​

  • Column stores often get 3-10x from encoding plus a general codec; text with high cardinality gets less. Measure with system.columns (ClickHouse) or DESCRIBE/file sizes (Parquet); never promise a ratio.
  • Sorted data compresses best. Re-sorting at load time is cheaper than choosing a worse codec.
  • Granule, row group and stripe size trade pruning precision against metadata and per-read overhead.
  • A part, file or micro-partition that is too small costs more in metadata and open calls than it saves in reads.

Solving the classic problems ​

Problem 1: the monthly report slows checkout Must-know ​

SolutionHowAdvantageCost / limitation
Index and tuneCovering index, partial index, EXPLAINNo new infrastructureLimited at scale; see Indexing, Query Planning
Materialized viewPre-aggregate; refresh off-peakCheap, in-databaseStale; full recompute
Read replicaRoute reports to a standbyIsolates primary loadRow store; replay conflicts and lag
Column store + CDC/ELTClickHouse/BigQuery/Snowflake/lakehouseOrders of magnitude faster scansA second system to run
Parquet export + DuckDBNightly export, analysts query filesNo server; cheapManual freshness

Before: the report on the primary. It joins three tables and scans paid-order history on the same server that takes checkout writes.

go
// Command before runs a monthly revenue report straight on the OLTP primary.
// It works, and it is the query that eventually hurts checkout latency.
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// A full scan of orders and order_items, joined and aggregated, on the same
// server (and the same buffer cache, I/O budget and connections) that takes
// customer writes.
const monthlyRevenue = `
SELECT date_trunc('month', o.created_at) AS month,
       c.country,
       sum(i.quantity * i.unit_price)    AS revenue,
       count(DISTINCT o.id)              AS orders
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN customers c   ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY 1, 2
ORDER BY 1, 2`

func main() {
	// The DSN points at the primary: the same host the checkout flow writes to.
	db, err := sql.Open("pgx", "postgres://app@primary.db.internal:5432/shop")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

	rows, err := db.QueryContext(ctx, monthlyRevenue)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		var (
			month   time.Time
			country string
			revenue float64
			orders  int64
		)
		if err := rows.Scan(&month, &country, &revenue, &orders); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s %s %.2f %d\n", month.Format("2006-01"), country, revenue, orders)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
php
<?php

// app/Http/Controllers/RevenueReportController.php
// An aggregate over the whole orders history, on the default connection:
// the same primary that handles checkout writes.
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

final class RevenueReportController
{
    public function monthly(): JsonResponse
    {
        $rows = Order::query()
            ->join('order_items', 'order_items.order_id', '=', 'orders.id')
            ->join('customers', 'customers.id', '=', 'orders.customer_id')
            ->where('orders.status', 'paid')
            ->groupByRaw("date_trunc('month', orders.created_at), customers.country")
            ->orderByRaw('1, 2')
            ->selectRaw("date_trunc('month', orders.created_at) as month")
            ->selectRaw('customers.country')
            ->selectRaw('sum(order_items.quantity * order_items.unit_price) as revenue')
            ->selectRaw('count(distinct orders.id) as orders')
            ->get();

        return response()->json($rows);
    }
}

Problem 2: refresh a Postgres materialized view without blocking readers Must-know ​

sql
CREATE MATERIALIZED VIEW monthly_revenue AS
SELECT date_trunc('month', o.created_at) AS month, c.country,
       sum(i.quantity * i.unit_price) AS revenue, count(DISTINCT o.id) AS orders
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY 1, 2;
CREATE UNIQUE INDEX monthly_revenue_pk ON monthly_revenue (month, country);
REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue;   -- readers keep reading

Go: a scheduled refresher (cron or Kubernetes CronJob) creates the view, then times a concurrent refresh.

go
// Command matview refreshes a Postgres materialized view on a schedule.
// Run it from cron, a Kubernetes CronJob or any scheduler; the report then
// reads the small pre-aggregated view instead of scanning orders.
package main

import (
	"context"
	"database/sql"
	"log"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// REFRESH ... CONCURRENTLY needs at least one UNIQUE index on the view that
// covers plain columns and has no WHERE clause.
var setup = []string{
	`CREATE MATERIALIZED VIEW IF NOT EXISTS monthly_revenue AS
	 SELECT date_trunc('month', o.created_at) AS month,
	        c.country,
	        sum(i.quantity * i.unit_price)    AS revenue,
	        count(DISTINCT o.id)              AS orders
	 FROM orders o
	 JOIN order_items i ON i.order_id = o.id
	 JOIN customers c   ON c.id = o.customer_id
	 WHERE o.status = 'paid'
	 GROUP BY 1, 2`,
	`CREATE UNIQUE INDEX IF NOT EXISTS monthly_revenue_pk
	 ON monthly_revenue (month, country)`,
}

func main() {
	// A physical streaming replica is read-only, so the view is created and
	// refreshed on the primary (off-peak) and read from a replica, where the
	// view's rows arrive like any other table data.
	db, err := sql.Open("pgx", "postgres://maintenance@primary.db.internal:5432/shop")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	for _, stmt := range setup {
		if _, err := db.ExecContext(ctx, stmt); err != nil {
			log.Fatal(err)
		}
	}

	// Readers keep seeing the old contents until the new ones are swapped in.
	start := time.Now()
	if _, err := db.ExecContext(ctx, `REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue`); err != nil {
		log.Fatal(err)
	}
	log.Printf("monthly_revenue refreshed in %s", time.Since(start))
}

Laravel: a reporting connection, a controller that reads the view, a migration that creates it, and a scheduled command that refreshes it.

php
<?php

// config/database.php (excerpt) — a second connection for reporting.
// Point it at a read replica, or at a separate warehouse database.
//
// 'connections' => [
//     'pgsql' => [ /* primary: checkout reads and writes */ ],
//     'reporting' => [
//         'driver' => 'pgsql',
//         'host' => env('REPORTING_DB_HOST', 'replica.db.internal'),
//         'port' => env('REPORTING_DB_PORT', '5432'),
//         'database' => env('REPORTING_DB_DATABASE', 'shop'),
//         'username' => env('REPORTING_DB_USERNAME', 'reporting'),
//         'password' => env('REPORTING_DB_PASSWORD', ''),
//     ],
// ],

// app/Http/Controllers/RevenueReportController.php — reads the small view
// from the reporting connection; the primary never sees this query.
namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

final class RevenueReportController
{
    public function monthly(): JsonResponse
    {
        $rows = DB::connection('reporting')
            ->table('monthly_revenue')
            ->orderBy('month')
            ->orderBy('country')
            ->get();

        return response()->json($rows);
    }
}
php
<?php

// database/migrations/2026_11_25_000000_create_monthly_revenue_view.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        DB::statement(<<<'SQL'
            CREATE MATERIALIZED VIEW monthly_revenue AS
            SELECT date_trunc('month', o.created_at) AS month,
                   c.country,
                   sum(i.quantity * i.unit_price)    AS revenue,
                   count(DISTINCT o.id)              AS orders
            FROM orders o
            JOIN order_items i ON i.order_id = o.id
            JOIN customers c   ON c.id = o.customer_id
            WHERE o.status = 'paid'
            GROUP BY 1, 2
            SQL);

        // Required by REFRESH ... CONCURRENTLY.
        DB::statement('CREATE UNIQUE INDEX monthly_revenue_pk ON monthly_revenue (month, country)');
    }

    public function down(): void
    {
        DB::statement('DROP MATERIALIZED VIEW IF EXISTS monthly_revenue');
    }
};
php
<?php

// app/Console/Commands/RefreshMonthlyRevenue.php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class RefreshMonthlyRevenue extends Command
{
    protected $signature = 'reports:refresh-revenue';

    protected $description = 'Refresh the monthly_revenue materialized view without blocking readers';

    public function handle(): int
    {
        // Runs on the primary: a streaming replica is read-only.
        DB::connection('pgsql')->statement('REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue');

        return self::SUCCESS;
    }
}

// routes/console.php
use Illuminate\Support\Facades\Schedule;

Schedule::command('reports:refresh-revenue')
    ->hourly()
    ->withoutOverlapping()
    ->onOneServer();

Laravel's database config accepts any number of named connections, and DB::connection('reporting') (or Report::on('reporting')) keeps a report off the primary. This is separate from the read/write split inside one connection; the sticky option exists to make a request read its own writes, which you do not want for a report. The query builder has no materialized-view grammar, so DB::statement carries the DDL and the migration is the right place for it. Schedule::command(...) with withoutOverlapping() and onOneServer() makes a multi-server deployment refresh once.

Problem 3: isolate the report workload and survive replay conflicts Must-know ​

One *sql.DB per workload, small pool for reports, and a retry for a conflict cancellation.

go
// Command reportpool keeps the OLTP pool and the reporting pool apart and
// shows what a long report on a hot standby can fail with: a replay conflict.
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/jackc/pgx/v5/pgconn"
	_ "github.com/jackc/pgx/v5/stdlib"
)

// Stores holds one handle per workload so a report can never borrow a
// checkout connection.
type Stores struct {
	OLTP   *sql.DB // primary: short transactions, small pool
	Report *sql.DB // replica or warehouse: few, long queries
}

func open(dsn string, maxConns int) (*sql.DB, error) {
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(maxConns)
	db.SetConnMaxLifetime(30 * time.Minute)
	return db, nil
}

const report = `SELECT country, sum(quantity * unit_price) FROM order_facts GROUP BY country`

// isReplayConflict reports whether err is the standby cancelling a query
// because WAL replay needed to remove rows the query still could see.
// PostgreSQL reports a query cancelled by recovery as SQLSTATE 40001
// (serialization_failure) with the message "canceling statement due to
// conflict with recovery".
func isReplayConflict(err error) bool {
	var pgErr *pgconn.PgError
	return errors.As(err, &pgErr) && pgErr.Code == "40001"
}

// RunReport retries a replay-conflict cancellation a few times; any other
// error is returned at once.
func (s *Stores) RunReport(ctx context.Context) error {
	var err error
	for attempt := 1; attempt <= 3; attempt++ {
		err = s.runOnce(ctx)
		if err == nil || !isReplayConflict(err) {
			return err
		}
		log.Printf("report cancelled by replay conflict (attempt %d), retrying", attempt)
		time.Sleep(time.Duration(attempt) * time.Second)
	}
	return err
}

func (s *Stores) runOnce(ctx context.Context) error {
	rows, err := s.Report.QueryContext(ctx, report)
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		var country string
		var revenue float64
		if err := rows.Scan(&country, &revenue); err != nil {
			return err
		}
		fmt.Println(country, revenue)
	}
	return rows.Err()
}

func main() {
	oltp, err := open("postgres://app@primary.db.internal:5432/shop", 20)
	if err != nil {
		log.Fatal(err)
	}
	defer oltp.Close()
	rep, err := open("postgres://reporting@replica.db.internal:5432/shop", 3)
	if err != nil {
		log.Fatal(err)
	}
	defer rep.Close()

	s := &Stores{OLTP: oltp, Report: rep}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()
	if err := s.RunReport(ctx); err != nil {
		log.Fatal(err)
	}
}

In Laravel the equivalent is the reporting connection, ALTER ROLE reporting SET statement_timeout = '5min' on the database side, and a retry around the query:

php
<?php

use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

// Retry a report that a hot standby cancelled (SQLSTATE 40001).
function runReport(string $sql): array
{
    for ($attempt = 1; ; $attempt++) {
        try {
            return DB::connection('reporting')->select($sql);
        } catch (QueryException $e) {
            // Only a conflict with recovery is worth retrying; everything else fails at once.
            if ($attempt >= 3 || (string) $e->getCode() !== '40001') {
                throw $e;
            }
            sleep($attempt * 2);
        }
    }
}

Problem 4: a real column store with batch loads Important ​

The report against a denormalised fact table (DDL in the comments), and a batch loader.

go
// Command clickhouse runs the same monthly revenue report against a
// column-oriented warehouse through the standard database/sql interface.
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"time"

	"github.com/ClickHouse/clickhouse-go/v2"
)

// Typical DDL, kept here as documentation. The fact table is denormalised:
// the customer country is copied onto each row, so the report needs no join.
//
//	CREATE TABLE order_facts (
//	    order_id    UInt64,
//	    created_at  DateTime,
//	    country     LowCardinality(String),
//	    quantity    UInt32,
//	    unit_price  Decimal(12, 2)
//	)
//	ENGINE = MergeTree
//	PARTITION BY toYYYYMM(created_at)
//	ORDER BY (country, created_at);
const monthlyRevenue = `
SELECT toStartOfMonth(created_at)  AS month,
       country,
       toFloat64(sum(quantity * unit_price)) AS revenue,
       uniqExact(order_id)         AS orders
FROM order_facts
GROUP BY month, country
ORDER BY month, country`

func main() {
	// OpenDB returns a *sql.DB; sql.Open connects lazily, so nothing is
	// dialled until the first query.
	db := clickhouse.OpenDB(&clickhouse.Options{
		Addr: []string{"clickhouse.internal:9000"},
		Auth: clickhouse.Auth{Database: "analytics", Username: "reporting"},
	})
	defer db.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	if err := report(ctx, db); err != nil {
		log.Fatal(err)
	}
}

func report(ctx context.Context, db *sql.DB) error {
	rows, err := db.QueryContext(ctx, monthlyRevenue)
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		var (
			month   time.Time
			country string
			revenue float64
			orders  uint64
		)
		if err := rows.Scan(&month, &country, &revenue, &orders); err != nil {
			return err
		}
		fmt.Printf("%s %s %.2f %d\n", month.Format("2006-01"), country, revenue, orders)
	}
	return rows.Err()
}
go
// Command chbatch loads order facts into ClickHouse with one large batch
// insert. Every INSERT creates a new part that background merges must later
// combine, so many tiny inserts are the classic way to hurt a MergeTree table.
package main

import (
	"context"
	"log"
	"time"

	"github.com/ClickHouse/clickhouse-go/v2"
)

type fact struct {
	OrderID   uint64
	CreatedAt time.Time
	Country   string
	Quantity  uint32
	UnitPrice string // Decimal columns accept decimal.Decimal or a string, not float64
}

func main() {
	// The native protocol connection (not database/sql) exposes PrepareBatch.
	conn, err := clickhouse.Open(&clickhouse.Options{
		Addr: []string{"clickhouse.internal:9000"},
		Auth: clickhouse.Auth{Database: "analytics", Username: "loader"},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	if err := load(ctx, conn, extract()); err != nil {
		log.Fatal(err)
	}
}

// load sends all facts as one batch, which becomes one (or a few) parts.
func load(ctx context.Context, conn clickhouse.Conn, facts []fact) error {
	batch, err := conn.PrepareBatch(ctx, "INSERT INTO order_facts")
	if err != nil {
		return err
	}
	for _, f := range facts {
		if err := batch.Append(f.OrderID, f.CreatedAt, f.Country, f.Quantity, f.UnitPrice); err != nil {
			return err
		}
	}
	return batch.Send()
}

// extract stands in for reading the next chunk from the CDC feed or from a
// staging table. Aim for tens of thousands of rows per batch or more.
func extract() []fact {
	return []fact{
		{OrderID: 1, CreatedAt: time.Now(), Country: "DE", Quantity: 2, UnitPrice: "19.90"},
		{OrderID: 2, CreatedAt: time.Now(), Country: "FR", Quantity: 1, UnitPrice: "5.00"},
	}
}

For ClickHouse there is no first-party Laravel driver; its HTTP interface works with Laravel's Http client: the SQL is the POST body and default_format=JSON selects the response format.

php
<?php

// app/Services/ClickHouseRevenue.php
// ClickHouse speaks HTTP on port 8123, so Laravel's Http client is enough.
// The query goes in the POST body; the result format is a query parameter.
//
// Table (run once in ClickHouse, not in a Laravel migration):
//   CREATE TABLE order_facts (
//       order_id UInt64, created_at DateTime,
//       country LowCardinality(String), quantity UInt32, unit_price Decimal(12, 2)
//   ) ENGINE = MergeTree
//   PARTITION BY toYYYYMM(created_at)
//   ORDER BY (country, created_at);
namespace App\Services;

use Illuminate\Support\Facades\Http;

final class ClickHouseRevenue
{
    /** @return list<array<string, mixed>> */
    public function monthly(): array
    {
        $sql = <<<'SQL'
            SELECT toStartOfMonth(created_at) AS month,
                   country,
                   toFloat64(sum(quantity * unit_price)) AS revenue,
                   uniqExact(order_id) AS orders
            FROM order_facts
            GROUP BY month, country
            ORDER BY month, country
            SQL;

        return Http::withBasicAuth(config('services.clickhouse.user'), config('services.clickhouse.password'))
            ->withQueryParameters(['database' => 'analytics', 'default_format' => 'JSON'])
            ->withBody($sql, 'text/plain')
            ->timeout(60)
            ->post(config('services.clickhouse.url')) // e.g. http://clickhouse.internal:8123
            ->throw()
            ->json('data');
    }
}

Problem 5: slowly changing dimension, Type 2 Important ​

sql
-- close the current version and add a new one, in one statement (one transaction)
WITH closed AS (
    UPDATE dim_customer SET valid_to = now(), is_current = false
     WHERE customer_id = 42 AND is_current AND country <> 'FR'
    RETURNING customer_id
)
INSERT INTO dim_customer (customer_id, country, valid_from, is_current)
SELECT customer_id, 'FR', now(), true FROM closed;   -- inserts only if a row was closed
go
// Command scd2 applies a Type 2 slowly changing dimension change: close the
// current row of a customer dimension and insert a new version, atomically.
package main

import (
	"context"
	"database/sql"
	"log"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// Dimension layout (surrogate key per version, natural key repeated):
//
//	CREATE TABLE dim_customer (
//	    customer_sk  bigserial PRIMARY KEY,
//	    customer_id  bigint      NOT NULL,   -- natural key from the OLTP system
//	    country      text        NOT NULL,
//	    valid_from   timestamptz NOT NULL,
//	    valid_to     timestamptz,            -- NULL while current
//	    is_current   boolean     NOT NULL DEFAULT true
//	);
//	CREATE UNIQUE INDEX one_current ON dim_customer (customer_id) WHERE is_current;

// ChangeCountry records that a customer moved. Facts loaded before the move
// keep pointing at the old surrogate key, so history stays correct.
func ChangeCountry(ctx context.Context, db *sql.DB, customerID int64, country string, at time.Time) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() // no-op after Commit

	res, err := tx.ExecContext(ctx, `
		UPDATE dim_customer
		SET valid_to = $3, is_current = false
		WHERE customer_id = $1 AND is_current AND country <> $2`,
		customerID, country, at)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return nil // nothing changed (or customer unknown): do not add a version
	}
	if _, err := tx.ExecContext(ctx, `
		INSERT INTO dim_customer (customer_id, country, valid_from, is_current)
		VALUES ($1, $2, $3, true)`, customerID, country, at); err != nil {
		return err
	}
	return tx.Commit()
}

func main() {
	db, err := sql.Open("pgx", "postgres://etl@warehouse.db.internal:5432/dw")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	if err := ChangeCountry(ctx, db, 42, "DE", time.Now()); err != nil {
		log.Fatal(err)
	}
}
php
<?php

// app/Warehouse/CustomerDimension.php
// Type 2 slowly changing dimension in a warehouse database: every change of a
// tracked attribute closes the current row and inserts a new version.
namespace App\Warehouse;

use Illuminate\Support\Facades\DB;

final class CustomerDimension
{
    public function changeCountry(int $customerId, string $country): void
    {
        DB::connection('warehouse')->transaction(function ($db) use ($customerId, $country): void {
            $now = now();

            // Close the current version only if the tracked attribute changed.
            $closed = $db->table('dim_customer')
                ->where('customer_id', $customerId)
                ->where('is_current', true)
                ->where('country', '<>', $country)
                ->update(['valid_to' => $now, 'is_current' => false]);

            if ($closed === 0) {
                return; // unchanged or unknown customer: no new version
            }

            $db->table('dim_customer')->insert([
                'customer_id' => $customerId,
                'country' => $country,
                'valid_from' => $now,
                'is_current' => true,
            ]);
        });
    }
}

Problem 6: export to Parquet for the lab and for analysts Good to know ​

php
<?php

// app/Console/Commands/ExportOrdersParquet.php
// Lab helper: let the DuckDB command-line tool read the paid order lines straight
// from PostgreSQL (its postgres extension) and write one Parquet file locally.
// DuckDB must be on PATH on the machine that runs this command.
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;

final class ExportOrdersParquet extends Command
{
    protected $signature = 'reports:export-parquet {path=storage/app/order_facts.parquet}';

    protected $description = 'Export order facts to a Parquet file for analytical engines';

    public function handle(): int
    {
        $db = config('database.connections.reporting');
        $target = base_path($this->argument('path'));

        // Read-only attach; credentials travel in the environment, not in the SQL text.
        $attach = sprintf(
            "ATTACH 'host=%s port=%s dbname=%s user=%s' AS pg (TYPE postgres, READ_ONLY)",
            $db['host'], $db['port'], $db['database'], $db['username']
        );

        $sql = "INSTALL postgres; LOAD postgres; {$attach};
            COPY (SELECT o.id AS order_id, o.created_at, c.country, i.quantity, i.unit_price
                  FROM pg.public.orders o
                  JOIN pg.public.order_items i ON i.order_id = o.id
                  JOIN pg.public.customers c ON c.id = o.customer_id
                  WHERE o.status = 'paid')
            TO '{$target}' (FORMAT parquet, COMPRESSION zstd)";

        $result = Process::timeout(600)
            ->env(['PGPASSWORD' => (string) $db['password']])
            ->run(['duckdb', '-c', $sql]);

        if ($result->failed()) {
            $this->error($result->errorOutput());

            return self::FAILURE;
        }

        $this->info("Wrote {$target}");

        return self::SUCCESS;
    }
}

Failure handling for the pipeline Important ​

FailureMeaningRetry?Rule
Replay conflict (40001 on standby)Replay needed removed rowsYes, boundedRetry 2-3 times with backoff, then fail or use a dedicated replica
Statement timeout (57014)Report too slowNoFix query or use a faster engine
Too many partsInsert outpaced mergesYes, after a pauseBatch more; do not hammer
Iceberg/Delta commit conflictAnother writer wonYesRe-read table state, re-apply, commit
CDC consumer crashOffset not committedResume at-least-onceMake the sink idempotent (ReplacingMergeTree, MERGE)
Duplicate CDC eventAt-least-once deliveryN/AKey by primary key + version; see Idempotent Consumers

Choosing ​

Workload / situationRecommendationExtra techniqueReason
Dashboard over a few million rows, one queryIndex + matview on primary or replicaREFRESH CONCURRENTLY off-peakNo new system
Tens of millions of rows, several analystsReplica for reportsmax_standby_streaming_delay, dedicated analytics replicaIsolates primary
Hundreds of millions to billions, ad-hocClickHouse, BigQuery, Snowflake or Redshift via CDC/ELTStar schema or flattened fact, sort key from top filtersScan cost dominates
Analyst needs one-off answers from an exportDuckDB over ParquetCOPY ... TO ... (FORMAT parquet)No server
Event streams, real-time rollupsClickHouse MergeTree + MVAggregatingMergeTree, TTLSeconds-fresh aggregates
Upserts in the warehouseReplacingMergeTree or Iceberg/Delta MERGEFINAL/argMax, compactionIdempotent sinks
Time-series history inside PostgreSQLCitus columnar / Hydra / partitioned archiveMove cold partitions to columnarStay in one DB
Strict need for one system for bothHTAP (TiDB + TiFlash, SingleStore)Resource isolation, verify stalenessPipeline hidden inside
Many writers, point readsKeep OLTP; do not use a column storeCache in RedisWrong shape
Open table format, many enginesIceberg or Delta on object storageCatalog, compaction, snapshot expiryEngine independence

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One PostgreSQL serves checkout and the admin dashboard. Start with the cheap rungs: an index for the report, then a materialized view refreshed at night. Example: a Laravel monolith with orders, order_items, customers; monthly_revenue is a matview refreshed by Schedule::command('reports:refresh')->dailyAt('02:00')->onOneServer(). Set statement_timeout on the reporting role so a stray query cannot run for an hour.

Modular monolith and multiple databases ​

Different modules own different schemas; the reporting module reads other modules' data. Give it a read-only role and the reporting connection to a replica; do not let it join across module tables with write privileges. Publish stable reporting views per module (billing.v_invoice_lines) as the contract. Example: finance reads billing.v_invoice_lines and orders.v_paid_orders through views, never the base tables, so modules can refactor tables without breaking reports.

Microservices ​

Each service owns its database, so a cross-service report cannot be one SQL join. Options: each service emits events or CDC to Kafka (see Change Data Capture, Transactional Outbox), and one analytics store joins them; or a per-service read model feeds a warehouse. Example flow: orders-service (PostgreSQL) and payments-service (MySQL) → Debezium → Kafka topics orders.public.orders, payments.payments → a sink writes to ClickHouse ReplacingMergeTree tables keyed by id → an ELT model builds fact_order_payment. The report reads the warehouse; no service is hit. Consistency is eventual: a payment may show in the warehouse seconds after the order, so dashboards must be labelled with data freshness.

Distributed data: replicas, caches, multi-region ​

A dedicated analytics replica (cascading or logical) per region keeps reports local; beware replay conflicts and lag, and never use the analytics replica as a failover target if you set hot_standby_feedback or long delays. Cache dashboard results in Redis with a TTL tied to the refresh cadence; a matview refresh invalidates it. In multi-region systems ship Parquet or CDC to a regional lake and query with a federated engine; cross-region reads of raw data are expensive. See Replication & Failover and Eventual Consistency in Databases.

Scaling path: 1x, 10x, 100x ​

ScaleDesignWhat changes
1x (millions of rows)Tune + indexes, matviewNothing new to run
10x (hundreds of millions)Replica or partitioned tables with pruning (Partitioning), pg_ivm for hot summariesOne replica; conflict settings
100x (billions)Column store via CDC/ELT, or lakehouse on object storagePipeline, catalog, compaction, data contracts, governance
1000x (petabytes, many teams)Lakehouse with Iceberg/Delta, many engines, medallion layersPlatform team, lineage, cost control

The wider scale ladder is in Storage & Data Scaling and the operational playbook for huge tables is in Billion-Row Tables.

Lab ​

Same query on a Postgres row table and on DuckDB/ClickHouse over exported Parquet, then matview refresh timing. Expected outputs below describe shape (which columns are read, which plan nodes appear), never promised numbers: measure on your own hardware.

Setup (PostgreSQL, 4 M order lines):

sql
CREATE TABLE customers (id int PRIMARY KEY, country text);
CREATE TABLE orders (id bigint PRIMARY KEY, customer_id int REFERENCES customers, status text, created_at timestamptz);
CREATE TABLE order_items (order_id bigint REFERENCES orders, line_no int, quantity int, unit_price numeric(12,2), PRIMARY KEY (order_id, line_no));

INSERT INTO customers SELECT g, (ARRAY['DE','FR','US','IR','GB'])[1 + g % 5] FROM generate_series(1, 100000) g;
INSERT INTO orders SELECT g, 1 + g % 100000, (ARRAY['paid','paid','paid','refunded','new'])[1 + g % 5],
       now() - (g % 1095) * interval '1 day' FROM generate_series(1, 2000000) g;
INSERT INTO order_items SELECT o, l, 1 + (o + l) % 5, 5 + (o % 90) FROM generate_series(1, 2000000) o, generate_series(1, 2) l;
ANALYZE;

Experiment 1: row store baseline.

text
1  psql> \timing on
2  psql> EXPLAIN (ANALYZE, BUFFERS) SELECT date_trunc('month', o.created_at) m, c.country, sum(i.quantity*i.unit_price)
         FROM orders o JOIN order_items i ON i.order_id=o.id JOIN customers c ON c.id=o.customer_id
         WHERE o.status='paid' GROUP BY 1,2;
3  expect: Parallel Seq Scan on orders and order_items, Hash Join, Buffers: shared hit/read in the 10^4-10^5 range
4  note the total time; run it twice (second run is warm)

Experiment 2: export to Parquet and query with DuckDB.

sql
-- psql: \copy (SELECT o.id order_id, o.created_at, c.country, i.quantity, i.unit_price
--               FROM orders o JOIN order_items i ON i.order_id=o.id JOIN customers c ON c.id=o.customer_id
--               WHERE o.status='paid') TO 'order_facts.csv' CSV HEADER
-- duckdb (CLI):
COPY (SELECT * FROM read_csv('order_facts.csv')) TO 'order_facts.parquet' (FORMAT parquet, COMPRESSION zstd);
.timer on
SELECT date_trunc('month', created_at) m, country, sum(quantity*unit_price) FROM 'order_facts.parquet' GROUP BY 1,2 ORDER BY 1,2;
EXPLAIN ANALYZE SELECT country, sum(quantity*unit_price) FROM 'order_facts.parquet' GROUP BY 1;
-- expect: PARQUET_SCAN reading only country, quantity, unit_price columns; file size far smaller than the CSV

Experiment 3: ClickHouse on the same Parquet.

sql
-- clickhouse-client
CREATE TABLE order_facts (order_id UInt64, created_at DateTime, country LowCardinality(String), quantity UInt32, unit_price Decimal(12,2))
ENGINE = MergeTree PARTITION BY toYYYYMM(created_at) ORDER BY (country, created_at);
INSERT INTO order_facts SELECT * FROM file('order_facts.parquet', Parquet);
SELECT toStartOfMonth(created_at) m, country, sum(quantity*unit_price) FROM order_facts GROUP BY m, country ORDER BY m, country;
-- expect in the client footer: "Read N rows, X MiB" far below the row-store buffers; inspect storage:
SELECT name, rows, bytes_on_disk FROM system.parts WHERE table='order_facts' AND active;
SELECT column, formatReadableSize(sum(column_data_compressed_bytes)) c, formatReadableSize(sum(column_data_uncompressed_bytes)) u FROM system.parts_columns WHERE table='order_facts' AND active GROUP BY column;

Experiment 4: time the same query from Go on both engines.

text
1  go run ./lab/timeit "$PRIMARY_DSN" "SELECT date_trunc('month', o.created_at), c.country, sum(i.quantity*i.unit_price) FROM orders o JOIN order_items i ON i.order_id=o.id JOIN customers c ON c.id=o.customer_id WHERE o.status='paid' GROUP BY 1,2"
2  go run ./lab/timeit "$PRIMARY_DSN" "SELECT * FROM monthly_revenue"      -- after experiment 5 created the view
3  clickhouse-client --time --query "SELECT toStartOfMonth(created_at), country, sum(quantity*unit_price) FROM order_facts GROUP BY 1,2"
4  expect: step 2 is orders of magnitude faster than step 1 (it reads a few hundred rows); step 3 is the column-engine number; compare min/median, not the first cold run
go
// Command timeit runs one query several times against any database/sql DSN
// and prints min / median / max wall time. Use it to compare the same report
// on a Postgres row table and on a replica or warehouse.
//
//	go run ./lab/timeit "postgres://app@localhost:5432/shop" "SELECT count(*) FROM orders"
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"sort"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
	if len(os.Args) != 3 {
		log.Fatal("usage: timeit <pgx-dsn> <query>")
	}
	db, err := sql.Open("pgx", os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	const runs = 5
	var times []time.Duration
	for i := 0; i < runs; i++ {
		start := time.Now()
		if err := drain(context.Background(), db, os.Args[2]); err != nil {
			log.Fatal(err)
		}
		times = append(times, time.Since(start))
	}
	sort.Slice(times, func(a, b int) bool { return times[a] < times[b] })
	fmt.Printf("min=%s median=%s max=%s (cold-cache runs raise the max)\n",
		times[0], times[runs/2], times[runs-1])
}

// drain reads every row so the measurement includes transfer, not just plan.
func drain(ctx context.Context, db *sql.DB, query string) error {
	rows, err := db.QueryContext(ctx, query)
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
	}
	return rows.Err()
}

Experiment 5: matview refresh timing and blocking.

text
1  session A: CREATE MATERIALIZED VIEW monthly_revenue AS <the report>; CREATE UNIQUE INDEX ON monthly_revenue (month, country);
2  session A: \timing on  then  REFRESH MATERIALIZED VIEW monthly_revenue;      -- note time; takes ACCESS EXCLUSIVE
3  session B (during A): SELECT * FROM monthly_revenue;                         -- blocks until A finishes
4  session A: REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue;            -- usually slower in total
5  session B (during A): SELECT * FROM monthly_revenue;                         -- returns the old rows immediately
6  expect: concurrent refresh is slower end-to-end but never blocks readers

Experiment 6: reproduce a replay conflict (needs a primary and a hot standby).

text
1  standby: ALTER SYSTEM SET max_standby_streaming_delay = '5s'; SELECT pg_reload_conf();   -- reload is enough
2  standby, session 1: SELECT pg_sleep(60), count(*) FROM orders;                            -- long query
3  primary: UPDATE orders SET status = 'paid' WHERE id <= 100000; VACUUM orders;
4  expect on standby after ~5s of conflict: ERROR: canceling statement due to conflict with recovery
5  repeat with hot_standby_feedback = on (ALTER SYSTEM + reload on the standby): no cancellation; the primary's pg_stat_replication shows backend_xmin held back

Common misconceptions ​

BeliefReality
Columnar is faster for everythingFaster for wide scans over few columns; slower for point reads and updates
A read replica gives me analyticsIt isolates load, but it is still a row store, and replay conflicts can cancel long queries
Materialized views update automaticallyNot in PostgreSQL; use REFRESH or pg_ivm
REFRESH ... CONCURRENTLY is always betterIt needs a UNIQUE index and is slower and heavier overall; it only avoids blocking readers
Parquet is a databaseIt is a file format; Iceberg/Delta add table semantics
ClickHouse PRIMARY KEY is uniqueIt is a sparse sort index; ReplacingMergeTree dedups eventually, not immediately
Inserting row by row is fine in ClickHouseEach insert is a part; tiny inserts cause Too many parts
ELT means no transformationThe transform moved into the warehouse
HTAP removes the pipelineIt hides the pipeline inside the product
Normalise the warehouse like OLTPStar schemas and flattened facts are deliberate denormalisation
DuckDB replaces a warehouseIt is single-process and single-writer; excellent for one node
SCD Type 1 is harmlessIt silently rewrites history in old reports

Cheat sheet ​

TopicWhat to remember
OLTP vs OLAPFew rows all columns vs many rows few columns; latency vs throughput
Row vs columnRow for point reads/writes, column for scans and compression
CompressionRLE, dictionary, delta, bit-packing, frame-of-reference; sorted data compresses best
VectorisedBatch of ~1-2k values per operator call; amortises overhead
Late materialisationCarry positions, build rows last
Zone mapsMin-max per block; need physically ordered data
ClickHouseORDER BY = sort key; sparse index of 8192-row granules; batch inserts
Replacing/AggregatingEventual merge-time semantics; use FINAL or *Merge
ParquetFooter metadata, row group -> column chunk -> page; no updates
Iceberg/DeltaAtomic commits via metadata pointer / transaction log; compact files
Star schemaFacts at declared grain, dimensions denormalised; SCD Type 2 for history
ETL vs ELTTransform before vs inside the warehouse; ELT keeps raw
CDCLog-based; at-least-once; make sinks idempotent
PG matviewREFRESH recomputes; CONCURRENTLY needs UNIQUE; pg_ivm for incremental
Replica reportsMind max_standby_streaming_delay and hot_standby_feedback
PrimaryDo not run big reports on it: cache, I/O, snapshots, connections

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does SELECT sum(amount) FROM payments read so much less in a column store? Must-know ​

Answer

Answer: It reads only the amount chunk, compressed, instead of every page with all columns. See Row vs column layout.

2 — Name five compression encodings and when each wins. Good to know ​

Answer

Answer: RLE for runs, dictionary for few distinct strings, delta for monotonic values, bit-packing for small integers, frame-of-reference for values clustered near a base. See Compression.

3 — What is late materialisation and which engines expose it? Good to know ​

Answer

Answer: Filter on narrow columns, carry row positions, fetch other columns only for survivors; ClickHouse PREWHERE, TiFlash late materialisation, column readers generally. See Late materialisation.

4 — Why do zone maps stop working on shuffled data? Important ​

Answer

Answer: Every block's min-max spans the whole range, so no block can be proven irrelevant. See Zone maps.

5 — In ClickHouse, why is PRIMARY KEY not a uniqueness constraint, and how do you get "latest row per key"? Important ​

Answer

Answer: It is a sparse index over granules; use ReplacingMergeTree with a version, and read with FINAL or argMax because merges are eventual. See MergeTree family.

6 — A report on the PostgreSQL standby is cancelled with conflict with recovery. Give two fixes and their costs. Important ​

Answer

Answer: Raise max_standby_streaming_delay (replay lag grows) or set hot_standby_feedback (bloat on the primary). A dedicated analytics replica is the clean option. See replay conflicts.

7 — What must exist for REFRESH MATERIALIZED VIEW CONCURRENTLY, and what does it cost? Important ​

Answer

Answer: A UNIQUE index; it is slower and heavier overall but does not block readers. See Materialized views.

8 — What does pg_ivm add and what is the downside? Good to know ​

Answer

Answer: Incremental maintenance of a materialized view through triggers; it adds write cost to base tables and supports only a subset of queries.

9 — Why do star schemas denormalise, and what is the grain? Must-know ​

Answer

Answer: Analytics joins a fact to few dimensions or flattens them; the grain is what one fact row represents, and it must be declared first. See Star schema.

10 — How does Type 2 SCD keep history correct? Important ​

Answer

Answer: A new dimension row with a new surrogate key per change; older facts keep pointing at the old key. See SCD.

11 — ETL vs ELT: when would you choose ELT? Must-know ​

Answer

Answer: When warehouse compute is cheap and you want raw history to re-transform with SQL. See ETL vs ELT.

12 — What does a lakehouse table format add to a folder of Parquet files? Good to know ​

Answer

Answer: Atomic commits, snapshots/time travel, schema evolution, row-level deletes via metadata (Iceberg metadata pointer, Delta _delta_log). See Lakehouse.

Glossary ​

TermMeaning
OLTPOnline transaction processing: many small reads/writes by key
OLAPOnline analytical processing: few large scans and aggregates
HTAPHybrid transactional/analytical processing in one system
Row storeLayout keeping all fields of a row together
Column storeLayout keeping each column together
Run-length encoding (RLE)Store (value, count) for runs of equal values
Dictionary encodingReplace repeated values by small integer codes
Delta encodingStore differences between neighbouring values
Bit-packingStore each value with the minimum number of bits
Frame-of-reference (FOR)Subtract a block minimum and bit-pack the offsets
Vectorised executionOperators process batches of column values
Late materialisationDelay assembling rows until positions are known
Zone mapPer-block min-max metadata used to skip blocks
Sort keyPhysical row order within a part/file (ORDER BY in MergeTree)
Sparse indexOne index entry per granule instead of per row
GranuleClickHouse's smallest read unit (8192 rows by default)
PartAn immutable sorted chunk written by one INSERT in MergeTree
MergeBackground combination of parts into larger ones
ReplacingMergeTreeMerge-time dedup by sorting key, keeping the latest version
AggregatingMergeTreeMerge-time combination of aggregate function states
ProjectionHidden alternative ordering or aggregate of a table, chosen by the optimiser
ParquetColumnar file format with row groups, column chunks, footer metadata
ORCColumnar file format with stripes and built-in indexes
ArrowColumnar in-memory format for zero-copy exchange
Row groupParquet unit holding a column chunk per column
Predicate pushdownApply filters inside the scan using statistics
Star schemaFact table plus denormalised dimensions
Snowflake schemaStar with normalised dimension hierarchies
Fact tableRows of measurable events at a declared grain
Dimension tableDescriptive context for facts
GrainWhat one fact row represents
Surrogate keyWarehouse-owned integer key per dimension row version
SCDSlowly changing dimension: how dimension history is kept (Types 0-7)
ETL / ELTTransform before / after loading into the warehouse
CDCChange data capture: streaming a database's change log
Data lakeRaw files in object storage
LakehouseData lake plus a transactional table format
Iceberg / Delta LakeOpen table formats with snapshots and atomic commits
CompactionRewriting many small files into fewer large ones
Materialized viewStored query result; refreshed on demand in PostgreSQL
pg_ivmExtension for incremental materialized view maintenance
Hot standbyRead-only PostgreSQL replica serving queries during recovery
hot_standby_feedbackStandby tells primary its oldest snapshot to avoid cleanup conflicts
Replay conflictWAL replay cannot proceed because a running query needs old rows
Tuple moverC-Store process moving data from write store to read store
TiFlashTiDB's columnar replica (Raft Learner)
Citus columnar / HydraPostgreSQL columnar table access methods

References ​

Built by Morteza Negahi