SQL Snippets

References

Debugging and exploration

Performance tweaks, SQL hints, environment variables

Simple versioning

SELECT
  *,
  DATE_FORMAT(CURRENT_DATE(), 'yyyyMMdd') AS insertion_date,
  COALESCE(
    (SELECT MAX(version) FROM t WHERE insertion_date = DATE_FORMAT(CURRENT_DATE(), 'yyyyMMdd')),
    0
  ) + 1 AS version
FROM t
WITH
  versioned_latest_date AS (
    SELECT MAX(insertion_date) FROM t
  ),
  versioned_latest_version AS (
    SELECT MAX(version) FROM t WHERE data = (SELECT * FROM versioned_latest_date)
  )

SELECT *
  FROM t
  WHERE insertion_date = (SELECT * FROM versioned_latest_date)
  AND   version        = (SELECT * FROM versioned_latest_version)
SELECT *
  FROM t
  WHERE insertion_date >= DATE_FORMAT(DATE_SUB(CURRENT_DATE(), 10), 'yyyyMMdd')

Misc

SELECT
  *,
  MONOTONICALLY_INCREASING_ID() AS id
FROM t
WITH
  capitalCities AS (
    SELECT *
    FROM VALUES
      ("France" , "Paris" ),
      ("Germany", "Berlin"),
      ("Italy"  , "Rome"  )
    AS data(country, capital)
  )

SELECT *
  FROM stats
  INNER JOIN capitalCities
  ON stats.city = capitalCities.capital
WITH
  possible_values AS (SELECT EXPLODE(SEQUENCE(200, 300)) AS e)

SELECT t.*
  FROM t
  INNER JOIN possible_values
  ON t.val = possible_values.e