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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: