Skip to content

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.

  • One statement that starts with SELECT or WITH. 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, SET or DO are 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).

Negative order totals:

SELECT COUNT(*) AS violation_count
FROM public.orders
WHERE total_amount < 0

Orders whose customer does not exist (orphaned foreign keys):

SELECT COUNT(*) AS violation_count
FROM public.orders o
LEFT JOIN public.customers c ON c.id = o.customer_id
WHERE c.id IS NULL

Yesterday’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_count
FROM o, p

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.