 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements
 