Principle:173TECH Sayn SQL Materialisation
| Knowledge Sources | |
|---|---|
| Domains | Data_Engineering, Data_Modelling |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
Technique for persisting SQL query results as database objects through configurable materialisation strategies that balance freshness, performance, and incremental processing.
Description
SQL materialisation is the practice of persisting the result of a SQL query as a physical database object (table or view). The materialisation strategy determines how the data is stored and refreshed:
- Table: Full refresh — drop and recreate (or replace) the table on each run
- View: Virtual — create a SQL view that evaluates on query, always current
- Incremental: Merge — only process new/changed records and merge them using a delete key
- Script: Execute arbitrary SQL with no persisted output (DDL, grants, etc.)
This solves the problem of choosing between freshness (views) and performance (tables) while supporting incremental processing for large datasets that cannot be fully reprocessed on each run.
Usage
Use this principle when designing a data modelling layer where SQL queries need to be materialized as database objects. The choice of materialisation depends on:
- Table: When the query is expensive and data changes infrequently
- View: When data must always be current and the query is fast
- Incremental: When the dataset is large and only new records need processing
- Script: When executing DDL, grants, or other non-SELECT statements
Theoretical Basis
Each materialisation strategy uses a different execution path:
Table: Create a temp table from the query, then move it to the final location (or use CREATE OR REPLACE if supported).
View: Create or replace a SQL view with the query.
Incremental: Create a temp table from the query, then merge it with the existing table using a delete key:
Failed to parse (syntax error): {\displaystyle \text{result} = (\text{existing} \setminus \text{matching}_{\text{delete\_key}}) \cup \text{new} }
The merge ensures that records with matching delete keys from the new data replace existing records.
Script: Execute the SQL directly without any table management.
Pseudo-code for incremental merge:
# Abstract algorithm (NOT real implementation)
temp = create_temp_table(query_result)
for row in existing_table:
if row[delete_key] in temp[delete_key]:
delete(row)
insert_all(temp)
drop(temp)
Practical Guide
Configure materialisation in YAML:
# tasks/models.yaml
models:
user_summary:
type: sql
file_name: user_summary.sql
materialisation: incremental
delete_key: user_id
destination: analytics.user_summary
Or use the config() Jinja macro inside the SQL file:
-- sql/user_summary.sql
{{ config(materialisation='incremental', delete_key='user_id') }}
SELECT user_id, COUNT(*) as order_count
FROM {{ src('raw.orders') }}
GROUP BY user_id