📜  SQL ORDER BY LIMIT(1)

📅  最后修改于: 2023-12-03 15:35:04.555000             🧑  作者: Mango

SQL ORDER BY LIMIT

In SQL, the ORDER BY clause is used to sort the result set in a specific order, while the LIMIT clause is used to limit the number of rows returned in the result set. Combining both clauses can provide a more refined and efficient query result.

Syntax

The basic syntax of combining ORDER BY and LIMIT in SQL is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC
LIMIT [no_of_rows];
  • column1, column2, ...: The columns specified in the SELECT statement to be fetched.
  • table_name: The table from where the data is to be fetched.
  • ORDER BY column1, column2, ...: Specifies the column(s) by which the result set should be sorted, either in ascending (ASC) or descending (DESC) order.
  • LIMIT [no_of_rows]: Specifies the maximum number of rows to be returned in the result set.
Example

Suppose we have a table named customers containing the following data:

| id | name | age | email | |----|----------|-----|------------------------| | 1 | Alice | 25 | alice@example.com | | 2 | Bob | 32 | bob@example.com | | 3 | Charlie | 19 | charlie@example.com | | 4 | David | 27 | david@example.com | | 5 | Elizabeth| 28 | elizabeth@example.com | | 6 | Frank | 30 | frank@example.com | | 7 | George | 22 | george@example.com |

To retrieve the top 3 oldest customers in descending order of age, we can use the following SQL query:

SELECT id, name, age, email
FROM customers
ORDER BY age DESC
LIMIT 3;

The result will be:

| id | name | age | email | |----|----------|-----|-----------------------| | 2 | Bob | 32 | bob@example.com | | 6 | Frank | 30 | frank@example.com | | 5 | Elizabeth| 28 | elizabeth@example.com |

In this example, we sorted the result set by the age column in descending order using the DESC keyword. We then used the LIMIT keyword to return only the first 3 rows. The result set contains the top 3 oldest customers in the table.

Conclusion

The SQL ORDER BY LIMIT is a powerful feature that allows you to sort and limit the result set in SQL queries. By combining both clauses, you can achieve more efficient and refined data retrieval.