Home >Database >Mysql Tutorial >How to Find the Maximum Date Across Multiple Columns in SQL?

How to Find the Maximum Date Across Multiple Columns in SQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-21 22:42:11923browse

How to Find the Maximum Date Across Multiple Columns in SQL?

Returning the maximum value of multiple columns in SQL

Suppose you have a table named "TableName" in your database with the following columns:

  • Number
  • Date1
  • Date2
  • Date3
  • Cost

Your goal is to retrieve a result set that displays the maximum value of the "Date" column for each row. You also need to include the "Number" and "Cost" columns.

Solution

You can achieve this result by using the MAX() function in conjunction with the VALUES table value constructor. Here is the updated query:

<code class="language-sql">SELECT Number,
       (SELECT MAX(v) FROM (VALUES (Date1), (Date2), (Date3)) AS value(v)) AS Most_Recent_Date,
       Cost
FROM TableName;</code>

Explanation

The subquery in the MAX() function uses the VALUES table value constructor to create a temporary table containing the "Date" column value. Then, the MAX() function selects the maximum value from this temporary table.

The results will be displayed in the desired format:

  • Number
  • Most_Recent_Date
  • Cost

The above is the detailed content of How to Find the Maximum Date Across Multiple Columns in SQL?. 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