যদি একটি সাবকোয়েরির ভেতর আরেকটি সাবকোয়েরি নেস্ট করা থাকে, তবে সেটিকে নেস্টেড সাবকোয়েরি বলা হয়। নিচে Cars, Customers, Reservations টেবিলের ডেটা ব্যবহার করে নেস্টেড সাবকোয়েরি তৈরি করা হয়েছে:
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 | +------+--------------+---------+ mysql> Select * from Customers; +-------------+----------+ | Customer_Id | Name | +-------------+----------+ | 1 | Rahul | | 2 | Yashpal | | 3 | Gaurav | | 4 | Virender | +-------------+----------+ mysql> Select * from Reservations; +------+-------------+------------+ | ID | Customer_id | Day | +------+-------------+------------+ | 1 | 1 | 2017-12-30 | | 2 | 2 | 2017-12-28 | | 3 | 2 | 2017-12-29 | | 4 | 1 | 2017-12-25 | | 5 | 3 | 2017-12-26 | +------+-------------+------------+
নেস্টেড সাবকোয়েরি উদাহরণ:
mysql> Select * from Customers where customer_id IN
(Select Customer_id from reservations where id = (Select id from cars WHERE name = 'BMW'));
+-------------+---------+
| Customer_Id | Name |
+-------------+---------+
| 2 | Yashpal |
+-------------+---------+
ব্যাখ্যা: সবচেয়ে ভেতরের সাবকোয়েরি Select id from cars WHERE name = 'BMW' প্রথমে এক্সিকিউট হয় (ID=3 রিটার্ন করে)। তারপর মাঝের সাবকোয়েরি Select Customer_id from reservations where id = 3 রান হয় (Customer_id=2 রিটার্ন করে)। শেষে আউটার কোয়েরি customer_id IN (2) দিয়ে কাস্টমার বের করে।