MySQL LEAST() and GREATEST()

The LEAST() function returns the smallest value from a list of arguments, while GREATEST() returns the largest value. They are useful for comparing multiple values.

Examples

1. Using LEAST() to Find the Minimum Value

SELECT LEAST(5, 10, 3) AS smallest_value;

Code Explanation: This query returns the smallest value from the list: 3.

2. Using GREATEST() to Find the Maximum Value

SELECT GREATEST(5, 10, 3) AS largest_value;

Code Explanation: This query returns the largest value from the list: 10.

Best Practices

  • Use LEAST() and GREATEST() to simplify comparisons between multiple values.
  • Be aware of NULL values, as they can affect the result.

Key Takeaways

  • LEAST() returns the smallest value from a list.
  • GREATEST() returns the largest value from a list.