Skip to content

Instantly share code, notes, and snippets.

@nick-andren
Created November 26, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nick-andren/265e08f35b97d7cf9a16b1bbe931b832 to your computer and use it in GitHub Desktop.
Save nick-andren/265e08f35b97d7cf9a16b1bbe931b832 to your computer and use it in GitHub Desktop.
Using CTEs in SQLite to generate a square root. sqrt() isn't a native function within SQLite, so I wanted to see if I could recreate the process within a recursive CTE instead. Unfortunately, there doesn't seem to be a way to dynamically alter the initial values in a recursive CTE (at least not in a straightforward way), so this example will onl…
WITH RECURSIVE rsqrt AS (
SELECT 27 AS x,
1 AS step,
1 AS g
UNION ALL
SELECT x AS x,
step+1 AS step,
CASE WHEN g = ((x/g + g) /2.0) THEN x ELSE ((x/g + g) /2.0) END AS g
FROM rsqrt
WHERE g <> ((x/g + g) /2.0)
),
sqrt AS (
SELECT g
FROM rsqrt
ORDER BY step DESC
LIMIT 1
)
SELECT g FROM sqrt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment