Advertisement
Advertisement


SQL - Select first 10 rows only?


Question

How do I select only the first 10 results of a query?

I would like to display only the first 10 results from the following query:

SELECT 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
2015/04/16
1
125
4/16/2015 2:56:00 AM

Accepted Answer

In SQL server, use:

select top 10 ...

e.g.

select top 100 * from myTable
select top 100 colA, colB from myTable

In MySQL, use:

select ... order by num desc limit 10
2017/07/20
175
7/20/2017 1:13:25 AM

Depends on your RDBMS

MS SQL Server

SELECT TOP 10 ...

MySQL

SELECT ... LIMIT 10

Sybase

SET ROWCOUNT 10
SELECT ...

Etc.

2009/12/12

In MySQL:

SELECT * FROM `table` LIMIT 0, 10
2012/10/02

The ANSI SQL answer is FETCH FIRST.

SELECT 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
FETCH FIRST 10 ROWS ONLY

If you want ties to be included, do FETCH FIRST 10 ROWS WITH TIES instead.

To skip a specified number of rows, use OFFSET, e.g.

...
ORDER BY num DESC
OFFSET 20
FETCH FIRST 10 ROWS ONLY

Will skip the first 20 rows, and then fetch 10 rows.

Supported by newer versions of Oracle, PostgreSQL, MS SQL Server, Mimer SQL and DB2 etc.

2018/07/05

In standard SQL you can use:

... FETCH FIRST 10 ROWS ONLY

This is supported in DB2, PostgreSQL and Oracle 12.1 (and later)

2020/02/19

Oracle

WHERE ROWNUM <= 10  and whatever_else ;

ROWNUM is a magic variable which contains each row's sequence number 1..n.

2009/12/12

Source: https://stackoverflow.com/questions/1891789
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]