PostgreSQL 18 reference · Math Functions

PostgreSQL GCD() Function

Return the greatest common divisor of two integers, the largest number that divides both. lcm() gives the least common multiple.

PostgreSQL 18 Since 13

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

gcd(a, b)  |  lcm(a, b)

Parameters

ParameterDescription
a, b Integers or numerics.

Return value

A number of the input type.

Examples

GCD and LCM
SELECT gcd(12, 18) AS gcd, lcm(4, 6) AS lcm;

Output

 gcd | lcm
-----+-----
   6 |  12
(1 row)

Run this on your computer — see “Get Started” for setup.

Simplify a fraction
SELECT 12 / gcd(12, 18) || '/' || 18 / gcd(12, 18) AS simplified;

Output

 simplified
------------
 2/3
(1 row)

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
PostgreSQL 13Added

Was this page helpful?