Selecting a single row in MySQL?

MySQLMySQLi Database

If you want to select a single row on the basis of primary key, use the WHERE clause. The syntax is as follows −

SELECT * FROM yourTableName WHERE yourPrimaryKeyColumnName = someValue;

To understand the above syntax, 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)

The following is the query to select a single row from the table −

mysql> select *from selectWithPrimaryKey where Id = 6;

Here is the output −

+----+------+------+-------+
| Id | Name | Age  | Marks |
+----+------+------+-------+
| 6  | Bob  | 20   | 91    |
+----+------+------+-------+
1 row in set (0.00 sec)
raja
Published on 01-Feb-2019 05:46:40
Advertisements