SQL GCD function
Returns the greatest common divisor of two integers: gcd(12, 18) is 6, computed with the Euclidean algorithm where it is not built in.
- Kategorie
- Math
- Returns
integer / bigint- In this category
- 50 of 82
Syntax
GCD(a, b)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Not built in | No built-in; recursive CTE or a T-SQL function implementing the Euclidean algorithm |
| PostgreSQL | Ja | Built in since PostgreSQL 13; gcd(0, 0) is 0 |
| MySQL | Not built in | No built-in; recursive CTE on 8.0+ |
| SQLite | Not built in | No built-in; recursive CTE |
| Oracle | Not built in | No built-in; recursive subquery factoring |
Beispiele
PostgreSQL
SELECT GCD(12, 18) AS six; -- 6
PostgreSQL
SELECT GCD(width, height) AS aspect_step FROM media_assets;
SQLite
WITH RECURSIVE g(a, b) AS ( SELECT 48, 18 UNION ALL SELECT b, a % b FROM g WHERE b <> 0 ) SELECT a FROM g WHERE b = 0; -- 6
Gut zu wissen
- gcd(0, 0) is defined as 0 on PostgreSQL; gcd(x, 0) is x.
- PostgreSQL also accepts numeric: gcd(12.0, 18.0) is 6.0, and gcd(1.5, 0.5) is 0.5, so fractional inputs are not truncated first.
- The Euclidean fallback is three lines: r = a % b, then loop with (b, r) until r is 0; a recursive CTE expresses it with a running modulo.
Questions about GCD
Which engines have a GCD function?
PostgreSQL 13 and later. SQL Server, MySQL, SQLite and Oracle have none; implement the Euclidean algorithm as a recursive CTE or a stored function.
What is gcd(0, 0)?
0, by the convention PostgreSQL adopts: every integer divides zero, and the greatest common divisor of the all-zero pair is defined as zero.
Why is GCD useful in SQL?
Aspect ratios, shard sizing and periodic scheduling: gcd(width, height) gives the largest unit both dimensions share, so ratios reduce cleanly.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.