Home >Database >Mysql Tutorial >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:
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!