

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
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)
- Related Questions & Answers
- MySQL query to select top 10 records?
- How to select sum or 0 if no records exist in MySQL?
- Select from table where value does not exist with MySQL?
- How to select from MySQL table A that does not exist in table B?
- MySQL - Select all records if it contains specific number?
- Select a fixed number of random records from a MySQL table?
- MySQL query to select bottom n records
- Select all records if it contains specific number in MySQL?
- MySQL SELECT from table A that does not exist in table B using JOINS?
- MySQL query to select top n rows efficiently?
- Print structured MySQL SELECT at command prompt
- Combine SELECT & SHOW command results in MySQL?
- Select columns of an R data frame and skip if does not exist.
- Explain Select command in DBMS
- Select records from MySQL NOW() -1 Day?
Advertisements