Custom SQL rules
When the built-in checks are not enough, write a custom SQL rule: a query that counts the rows (or anything else) that break your rule. The rule fails when the count is greater than 0.
Requirements
Section titled “Requirements”- One statement that starts with
SELECTorWITH. Up to 10,000 characters. - It returns exactly one row with one numeric column named
violation_count. Anything else ends the rule in error. - Read-only. Statements such as
INSERT,UPDATE,DELETE,MERGE,CREATE,DROP,ALTER,TRUNCATE,GRANT,COPY,CALL,SETorDOare refused when you save. PostgreSQL runs the query in a read-only transaction; BigQuery dry-runs it first and it must fit the connection’s bytes cap. - Aggregate. Return a count, not rows. DataLoris stores only the number.
Use fully qualified table names (schema.table on PostgreSQL, `project.dataset.table` on BigQuery).
Examples
Section titled “Examples”Negative order totals:
SELECT COUNT(*) AS violation_countFROM public.ordersWHERE total_amount < 0Orders whose customer does not exist (orphaned foreign keys):
SELECT COUNT(*) AS violation_countFROM public.orders oLEFT JOIN public.customers c ON c.id = o.customer_idWHERE c.id IS NULLYesterday’s revenue differs from the payments ledger by more than 1%:
WITH o AS ( SELECT COALESCE(SUM(total_amount), 0) AS total FROM analytics.orders_daily WHERE order_date = CURRENT_DATE - 1), p AS ( SELECT COALESCE(SUM(amount), 0) AS total FROM finance.payments WHERE paid_at::date = CURRENT_DATE - 1)SELECT CASE WHEN ABS(o.total - p.total) > 0.01 * GREATEST(p.total, 1) THEN 1 ELSE 0 END AS violation_countFROM o, pEvents in the future (clock skew or bad parsing), today’s partition only:
SELECT COUNT(*) AS violation_countFROM `acme.analytics.events`WHERE event_date = CURRENT_DATE() AND event_time > TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 MINUTE)Fewer than 24 hourly loads yesterday:
SELECT IF(COUNT(DISTINCT TIMESTAMP_TRUNC(loaded_at, HOUR)) < 24, 1, 0) AS violation_countFROM `acme.raw.orders`WHERE DATE(loaded_at) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)A custom SQL rule has no column of its own, so you choose what a failure affects: the whole table, or specific columns (at least one). This drives lineage impact.