Get only a single value from a specific MySQL row?


For this, use SELECT INTO variable with where clause. Let us first create a table −

mysql> create table DemoTable1896
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20),
   StudentMarks int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Chris',56);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('David',98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Mike',89);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Sam',78);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1896;

This will produce the following output −

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|         1 | Chris       |           56 |
|         2 | David       |           98 |
|         3 | Mike        |           89 |
|         4 | Sam         |           78 |
+-----------+-------------+--------------+
4 rows in set (0.00 sec)

Here is the query to get value from a specific MySQL row −

mysql> set @Name:=NULL;
Query OK, 0 rows affected (0.00 sec)
mysql> select StudentName into @Name from DemoTable1896 where StudentMarks=98;
Query OK, 1 row affected (0.00 sec)

Now you can display the value of the above variable −

mysql> select @Name;

This will produce the following output −

+-------+
| @Name |
+-------+
| David |
+-------+
1 row in set (0.00 sec)

Updated on: 27-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements