Home >Database >Mysql Tutorial >How to Find the Minimum Value Across Multiple Columns in SQL Server?

How to Find the Minimum Value Across Multiple Columns in SQL Server?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-10 09:34:40648browse

How to Find the Minimum Value Across Multiple Columns in SQL Server?

Select minimum value from multiple columns in SQL Server

Given a table with several columns of numeric values, a common task is to find the minimum value for each row that represents the minimum value in these columns.

Three columns example

Consider the following table:

ID Col1 Col2 Col3
1 3 34 76
2 32 976 24
3 7 235 3
4 245 1 792

We want to create a new column "TheMin" that contains the minimum value for each row.

Case/When Statement

An effective way to achieve this is to use a Case/When statement, as shown below:

<code class="language-sql">SELECT Id,
       CASE 
           WHEN Col1 < Col2 AND Col1 < Col3 THEN Col1
           WHEN Col2 < Col1 AND Col2 < Col3 THEN Col2
           ELSE Col3
       END AS TheMin
FROM YourTable;</code>

This statement evaluates each line:

  1. If Col1 is smaller than Col2 and Col3, assign Col1 to TheMin.
  2. If Col2 is smaller than Col1 and Col3, assign Col2 to TheMin.
  3. Otherwise, assign Col3 to TheMin.

Results

The output will be a table with a new "TheMin" column containing the minimum value for each row:

ID Col1 Col2 Col3 TheMin
1 3 34 76 3
2 32 976 24 24
3 7 235 3 3
4 245 1 792 1

The above is the detailed content of How to Find the Minimum Value Across Multiple Columns in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn