SQLazy: Write Complex SQL in Plain Language

Picture7png

When you write SQL, what scares you is not syntax but complexity. The moment a requirement gets complicated, the SQL runs away: CTEs inside CTEs, window functions on top of window functions, dozens of lines mashed into one lump. Get something wrong? Change one place and three break.
Some say it is only SQL, just learn it and you are done. But the question is not whether you can write it; it is whether you still recognize it two months later, and whether anyone else can take it over.

With SQLazy, break a complex requirement down, layer by layer, in plain language, one step at a time.

tb: sort timestamp
segment value; change; as gid
summarize first timestamp as effective_from, first id as id; group gid, value
compute ifn(effective_from[1], datetime("9999-12-31 00:00:00")), as effective_to

SQL dialect does not matter; once the logic is clear, you are done. Each step debugs on its own, every intermediate result is a click away, and you always know where the change belongs.
Compile it into SQL and run it straight in the database:

WITH Value AS (
		SELECT id, value, timestamp
		FROM events
	),
	Value2 AS (
		SELECT gid, id AS id, value AS value, timestamp AS effective_from
		FROM (
			SELECT id, value, timestamp
				, SUM(CASE
					WHEN value <> col__5 THEN 1
					ELSE 0
				END) OVER (ORDER BY CASE
					WHEN timestamp IS NULL THEN 1
					ELSE 0
				END, timestamp ASC) + 1 AS gid
			FROM (
				SELECT Value.*, LAG(value) OVER (ORDER BY CASE
						WHEN timestamp IS NULL THEN 1
						ELSE 0
					END, timestamp ASC) AS col__5
				FROM Value
			) sub__6
		) Value1
		GROUP BY gid
	)
SELECT gid, id, value, effective_from
	, LEAD(effective_from, 1, TO_DATE('9999-12-31 00:00:00', 'YYYY-MM-DD HH24:MI:SS')) OVER (ORDER BY gid) AS effective_to
FROM Value2
ORDER BY gid;

The same description generates SQL for several databases. One click to switch between MySQL, PostgreSQL and Oracle. Write it once, run it anywhere.

Complex SQL should not be a tangled mess. SQLazy: complex SQL in plain language.