Getting first and last records using mysql

CREATE TABLE `friends` ( `id` int(11) NOT NULL auto_increment, `name` varchar(50) default NULL, PRIMARY KEY (`id`) )

select * from friends;

==============================
id name
==============================
1 Aditi Shastry
2 Umesh Shastry
3 Girish Bahri
4 Narendra Jattu
5 Abhishek Kumar Singh
6 Sagar Gunupati
==============================

SELECT A.* FROM (SELECT * FROM friends ORDER BY id ASC limit 1) A
UNION
SELECT B.* FROM (SELECT * FROM friends ORDER BY id DESC limit 1) B;

After running this query, you will get the following output,

==============================
id name
==============================
1 Aditi Shastry
6 Sagar Gunupati

Author: Umesh Shastry

Advertisements