Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find first and last record from mysql table

Tags:

I have one table I want to find first and last record that satisfy criteria of particular month.

like image 811
chetan Avatar asked Apr 29 '10 07:04

chetan


2 Answers

SELECT  (SELECT column FROM table WHERE [condition] ORDER BY column LIMIT 1) as 'first', (SELECT column FROM table WHERE [condition] ORDER BY column DESC LIMIT 1) as 'last' 

This worked for me when I needed to select first and the last date in the event series.

like image 154
bdereta Avatar answered Sep 25 '22 06:09

bdereta


First and last make sense only when you have the output of the query sorted on a field(s).

To get the first record:

select col1 from tab1 order by col1 asc limit 1; 

To get the last record:

select col1 from tab1 order by col1 desc  limit 1; 
like image 21
codaddict Avatar answered Sep 23 '22 06:09

codaddict