Home >Database >Mysql Tutorial >How to Find the Second Largest Value in a Database Column Using SQL?

How to Find the Second Largest Value in a Database Column Using SQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-13 14:46:47294browse

How to Find the Second Largest Value in a Database Column Using SQL?

Trick to get the second largest value in a column

In database tables, it is very useful to retrieve the second largest value in a specific column. One way is to use SQL queries.

SQL query statement:

To find the second largest value in the column named "col" in the table named "table", use the following query:

<code class="language-sql">SELECT MAX(col)
FROM table
WHERE col < (SELECT MAX(col) FROM table);</code>

Instructions:

  • The outer SELECT statement retrieves the maximum value of the "col" column.
  • Subquery (SELECT MAX(col) FROM table) Finds the maximum value in the "col" column.
  • The
  • WHERE clause ensures that only rows with values ​​less than the maximum value are selected. This excludes the largest value and returns the second largest value.

Example:

Consider the following form:

id col
1 5
2 10
3 7
4 10

Running this query will return the second largest value, 7.

<code class="language-sql">SELECT MAX(col)
FROM table
WHERE col < (SELECT MAX(col) FROM table);</code>

The above is the detailed content of How to Find the Second Largest Value in a Database Column Using 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