Sobes.tech
Junior — Middle

Show an example of using a nested SQL query.

sobes.tech AI

Answer from AI

A nested SQL query (subquery) is a query that is embedded within another query. For example, in PHP using PDO, you can execute a query that selects users who have orders:

$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'password');

$sql = "SELECT * FROM users WHERE id IN (SELECT user_id FROM orders WHERE amount > 100)";
$stmt = $pdo->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($users as $user) {
    echo $user['name'] . "\n";
}

Here, the nested query SELECT user_id FROM orders WHERE amount > 100 selects the IDs of users whose order amount is greater than 100, and the outer query retrieves the data of these users.

Show an example of using a nested SQL query. — PHP - sobes.tech