In PostgreSQL, lcm()
is a mathematical function that returns the least common multiple. We pass two numbers and the function returns the smallest strictly positive number that is an integral multiple of both inputs.
Example
Here’s an example to demonstrate:
SELECT lcm(20, 15);
Result:
60
Here are some more examples:
SELECT
lcm(200, 150),
lcm(1, 2),
lcm(1024, 512),
lcm(0, 150),
lcm(1024, 1024);
Result:
lcm | lcm | lcm | lcm | lcm
-----+-----+------+-----+------
600 | 2 | 1024 | 0 | 1024
Passing a Negative Value
The function returns a positive number regardless of whether we pass positive or negative values:
SELECT
lcm(200, -150),
lcm(-200, 150),
lcm(-200, -150);
Result:
lcm | lcm | lcm
-----+-----+-----
600 | 600 | 600
Passing Zero
If either argument is zero, then zero is returned. This also applies when both are zero:
SELECT
lcm(0, 150),
lcm(200, 0),
lcm(0, 0);
Result:
lcm | lcm | lcm
-----+-----+-----
0 | 0 | 0
Passing a Null Value
If any one of the arguments is null, then null
is returned:
SELECT
lcm(null, 150),
lcm(200, null);
Result:
lcm | lcm
------+------
null | null
But if both arguments are null, an error is returned:
SELECT lcm(null, null);
Result:
ERROR: function lcm(unknown, unknown) is not unique
LINE 1: SELECT lcm(null, null);
^
HINT: Could not choose a best candidate function. You might need to add explicit type casts.
Passing the Wrong Argument Type
If any of the arguments are not numeric, an error is returned:
SELECT lcm('cat', 150);
Result:
ERROR: function lcm(unknown, unknown) is not unique
LINE 1: SELECT lcm(null, null);
^
HINT: Could not choose a best candidate function. You might need to add explicit type casts.
barney=# SELECT lcm('cat', 150);
ERROR: invalid input syntax for type integer: "cat"
LINE 1: SELECT lcm('cat', 150);
^