Retrieving the Top 10 Rows from Your Database Queries
Working with large datasets often necessitates viewing only a portion of the results. This article demonstrates how to efficiently limit query results to the first 10 rows in SQL Server and MySQL.
SQL Server: The TOP
Keyword
SQL Server utilizes the TOP
keyword to restrict the number of returned rows. To obtain the top 10 results, integrate the TOP
keyword into your query like so:
SELECT TOP 10 a.names, COUNT(b.post_title) AS num FROM wp_celebnames a JOIN wp_posts b ON INSTR(b.post_title, a.names) > 0 WHERE b.post_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY) GROUP BY a.names ORDER BY num DESC
This query returns the top 10 names
and their associated counts, ordered by num
in descending order.
MySQL: The LIMIT
Clause
MySQL employs the LIMIT
clause to achieve the same result. Simply append LIMIT 10
to the end of your query:
... ORDER BY num DESC LIMIT 10
This adds a limit of 10 rows to the query, ensuring only the first 10 results (ordered by num
descending in this example) are returned.
By using these methods, you can effectively manage large datasets and focus on the most relevant initial results.
The above is the detailed content of How to Limit Query Results to the First 10 Rows in SQL Server and MySQL?. For more information, please follow other related articles on the PHP Chinese website!