How to get the first and last record of the table in MySQL?


To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.

Let us first create a table −

mysql> create table DemoTable694 (
   EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   EmployeeName varchar(100),
   EmployeeSalary int
);
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Chris',457647);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Robert',90883);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('David',123532);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Mike',989322);
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable694;

This will produce the following output -

+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1          | Chris        | 457647         |
| 2          | Robert       | 90883          |
| 3          | David        | 123532         |
| 4          | Mike         | 989322         |
+------------+--------------+----------------+
4 rows in set (0.00 sec)

Following is the query to get first and last record −

mysql> (select *from DemoTable694 order by EmployeeId ASC LIMIT 1)
UNION
(select *from DemoTable694 order by EmployeeId DESC LIMIT 1);

This will produce the following output -

+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1          | Chris        | 457647         |
| 4          | Mike         | 989322         |
+------------+--------------+----------------+
2 rows in set (0.00 sec)

Updated on: 21-Aug-2019

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements