SQL LCM function
Returns the least common multiple of two integers: lcm(4, 6) is 12, related to gcd by the identity lcm(a, b) * gcd(a, b) = a * b.
- Kategorie
- Math
- Returns
integer / bigint- In this category
- 51 of 82
Syntax
LCM(a, b)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Not built in | No built-in; compute via a GCD helper and the product identity |
| PostgreSQL | Ja | Built in since PostgreSQL 13; defined as abs(a * b) / gcd(a, b), and lcm(0, x) is 0 |
| MySQL | Not built in | No built-in; recursive CTE for GCD, then the identity |
| SQLite | Not built in | No built-in; same approach |
| Oracle | Not built in | No built-in; same approach |
Beispiele
PostgreSQL
SELECT LCM(4, 6) AS twelve; -- 12
PostgreSQL
SELECT LCM(cadence_a, cadence_b) AS sync_days FROM schedules;
Gut zu wissen
- lcm(0, x) is 0 on PostgreSQL: zero is the only multiple zero shares with anything.
- The product a * b can overflow bigint before the division: PostgreSQL's builtin guards internally, but a hand-rolled a * b / gcd(a, b) can overflow; divide first where possible.
- Everything about availability mirrors GCD: one builtin (PostgreSQL 13+), Euclidean fallback elsewhere.
Questions about LCM
What is the relation between LCM and GCD?
lcm(a, b) * gcd(a, b) = a * b (for positive integers). So once a GCD exists (PostgreSQL's gcd() or your own Euclidean CTE), LCM is a*b/gcd.
Which engines have LCM?
PostgreSQL 13+. Elsewhere compute abs(a * b) / gcd(a, b) with a hand-rolled GCD.
Why is lcm(0, 5) equal to 0?
PostgreSQL defines it that way: zero has no positive multiples other than zero itself, so zero is the least common multiple it shares with 5.
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.