How can I use MySQL subquery as a table in FROM clause?


We can use a subquery as a table in the FROM clause in the same way as the result of a subquery can be used with an operator in the WHERE clause. In the following example, we are using the result of subquery as a table by writing it after the FROM clause. It is mandatory to use an alias after subquery, here we are using alias ‘C_car’. To demonstrate it we are using the data as follows from table ‘Cars’ −

mysql> Select * from Cars;
+------+--------------+---------+
| ID   | Name         | Price   |
+------+--------------+---------+
|    1 | Nexa         | 750000  |
|    2 | Maruti Swift | 450000  |
|    3 | BMW          | 4450000 |
|    4 | VOLVO        | 2250000 |
|    5 | Alto         | 250000  |
|    6 | Skoda        | 1250000 |
|    7 | Toyota       | 2400000 |
|    8 | Ford         | 1100000 |
+------+--------------+---------+
8 rows in set (0.02 sec)

mysql> Select * FROM ( Select Name, Price from Cars Where Price > 200000) C_car WHERE Name = 'Nexa';
+------+--------+
| Name | Price  |
+------+--------+
| Nexa | 750000 |
+------+--------+
1 row in set (0.00 sec)

Monica Mona
Monica Mona

Student of life, and a lifelong learner

Updated on: 22-Jun-2020

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements