MySQL LIMIT to select a single row


To select a single row in MySQL, you can use LIMIT. At first, let us create a table. The query to create a table is as follows −

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

Insert some records in the table using insert command. The query is as follows −

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Larry',24,98);
Query OK, 1 row affected (0.15 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('John',23,89);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Mike',21,85);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Sam',26,56);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Carol',21,59);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('Bob',20,91);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectWithPrimaryKey(Name,Age,Marks) values('David',28,93);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from selectWithPrimaryKey;

The following is the output −

+----+-------+------+-------+
| Id | Name  | Age  | Marks |
+----+-------+------+-------+
| 1  | Larry | 24   | 98    |
| 2  | John  | 23   | 89    |
| 3  | Mike  | 21   | 85    |
| 4  | Sam   | 26   | 56    |
| 5  | Carol | 21   | 59    |
| 6  | Bob   | 20   | 91    |
| 7  | David | 28   | 93    |
+----+-------+------+-------+
7 rows in set (0.00 sec)

Here is the query to select a single row from the table using LIMIT −

mysql> select *from selectWithPrimaryKey where Id = 10 or Age = 29 or Marks = 89 limit 1;

The following is the output −

+----+------+------+-------+
| Id | Name | Age  | Marks |
+----+------+------+-------+
| 2  | John | 23   | 89    |
+----+------+------+-------+
1 row in set (0.00 sec)

Updated on: 30-Jun-2020

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements