Selecting all the users with maximum age values using a MySQL subquery?


Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(100),
   Age int
);
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',23);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('David',55);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Bob',53);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Mike',54);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('Sam',55);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+------+
| Name  | Age  |
+-------+------+
| Chris |   23 |
| David |   55 |
| Bob   |   53 |
| Mike  |   54 |
| Sam   |   55 |
+-------+------+
5 rows in set (0.00 sec)

Following is the query to select all the users with maximum age values −

mysql> select *from DemoTable
   where Age=(select max(Age) from DemoTable);

This will produce the following output −

+-------+------+
| Name  | Age  |
+-------+------+
| David | 55   |
| Sam   | 55   |
+-------+------+
2 rows in set (0.00 sec)

Updated on: 24-Sep-2019

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements