Select top 1 and top 2-6 records from MySQL

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
lyleyboy
Forum Commoner
Posts: 27
Joined: Sat Mar 18, 2006 5:05 am
Location: Birmingham, UK

Select top 1 and top 2-6 records from MySQL

Post by lyleyboy »

Hi all,

I am in need of two queries from the same table. I have an ID which is an auto incremented number. There will be some gaps in the ID range.
Query 1,
I want to pull the record with the highest ID
i.e. I have records 1,3,4,6,7,9,11,15,18,20,23 I only want to pull ID 23

Query 2,
I want to pull the next five records
i.e. 23,20,18,15 and 11

I hope this makes sense to someone.

Thanks in advance
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: Select top 1 and top 2-6 records from MySQL

Post by jaoudestudios »

Makes sense :)

Query 1
SELECT * FROM *TABLE* ORDER BY id DESC LIMIT 0,1

Query 2
SELECT * FROM *TABLE* ORDER BY id DESC LIMIT 0,5

Replace *TABLE* with the name of the table in your database
lyleyboy
Forum Commoner
Posts: 27
Joined: Sat Mar 18, 2006 5:05 am
Location: Birmingham, UK

Re: Select top 1 and top 2-6 records from MySQL

Post by lyleyboy »

Superb thanks for that. I knew there would be an easy way
jaoudestudios wrote:Replace *TABLE* with the name of the table in your database
I'm not that daft :D
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: Select top 1 and top 2-6 records from MySQL

Post by Ollie Saunders »

I'm not that daft :D
Hehe, well that's good but some people are.
Post Reply