Does SELECT TOP command exist in MySQL to select limited number of records?


There is no concept of TOP in MySQL. The alternate way to write your query is using LIMIT i.e to select 2 records, you need to use TOP 2. Let us see the syntax for the same in MySQL

SELECT *FROM yourTableName ORDER BY yourColumnName DESC LIMIT 2;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table Top2Demo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(20),
   - > Age int
   - > );
Query OK, 0 rows affected (0.91 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into Top2Demo(Name,Age) values('Larry',23);
Query OK, 1 row affected (0.13 sec)
mysql> insert into Top2Demo(Name,Age) values('Bob',21);
Query OK, 1 row affected (0.10 sec)
mysql> insert into Top2Demo(Name,Age) values('Sam',19);
Query OK, 1 row affected (0.14 sec)
mysql> insert into Top2Demo(Name,Age) values('David',25);
Query OK, 1 row affected (0.15 sec)
mysql> insert into Top2Demo(Name,Age) values('Carol',22);
Query OK, 1 row affected (0.39 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from Top2Demo;

The following is the output

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Larry |   23 |
|  2 | Bob   |   21 |
|  3 | Sam   |   19 |
|  4 | David |   25 |
|  5 | Carol |   22 |
+----+-------+------+
5 rows in set (0.00 sec)

Here is the query to select top the 2 records with the help of LIMIT 2

mysql> SELECT * FROM Top2Demo ORDER BY Age DESC LIMIT 2;

The following is the output

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  4 | David |   25 |
|  1 | Larry |   23 |
+----+-------+------+
2 rows in set (0.00 sec)

Updated on: 30-Jul-2019

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements