Friday, December 20, 2024

MySQL LEAST() Function

 The LEAST() function in MySQL is used to return the smallest value from a list of expressions. It compares two or more values and returns the smallest (minimum) value based on the data type and collation.

Syntax:

LEAST(value1, value2, ..., valueN)

Key Points:

  1. The arguments (value1, value2, ..., valueN) can be column names, constants, or expressions.
  2. If any argument is NULL, the result is NULL.
  3. Data types of the arguments must be compatible for comparison.
  4. String comparisons are performed lexicographically based on the collation.

Example Use Cases:

Example 1: Basic Numeric Comparison

SELECT LEAST(10, 20, 5, 30) AS SmallestValue;
-- Output: 5

Example 2: String Comparison

SELECT LEAST('apple', 'banana', 'cherry') AS SmallestString;
-- Output: 'apple' (alphabetical comparison)

Example 3: With NULL Values

SELECT LEAST(10, 20, NULL, 5) AS Result;
-- Output: NULL

Example 4: Column Values

CREATE TABLE TestTable (A INT, B INT, C INT);
INSERT INTO TestTable (A, B, C) VALUES (10, 20, 5), (30, 15, 25), (NULL, 40, 35);

SELECT A, B, C, LEAST(A, B, C) AS SmallestValue
FROM TestTable;

-- Output:
-- A     B     C     SmallestValue
-- 10    20    5     5
-- 30    15    25    15
-- NULL  40    35    NULL

The LEAST() function is handy when you need to identify the smallest value across multiple columns or expressions.

No comments:

Post a Comment