How can we use a MySQL subquery with FROM clause?


Subqueries can work well in a SELECT statement FROM clause. Following is the syntax for the same −

SELECT … FROM(subquery) [AS] name …

To make it understand we are using the following data 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)

Now in the following query, we are using the subquery with FROM clause −

mysql> Select Id_New, Name_New, Price_New FROM (SELECT Id as Id_New, Name as Name_New, Price as Price_New FROM Cars) as c Where Price_New > 500000;
+--------+----------+-----------+
| Id_New | Name_New | Price_New |
+--------+----------+-----------+
| 1      | Nexa     | 750000    |
| 3      | BMW      | 4450000   |
| 4      | VOLVO    | 2250000   |
| 6      | Skoda    | 1250000   |
| 7      | Toyota   | 2400000   |
| 8      | Ford     | 1100000   |
+--------+----------+-----------+
6 rows in set (0.00 sec)

Updated on: 22-Jun-2020

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements