Which query includes all orders and their customers, even if an order has no customer (rare scenario)?

Study for the SQL Basics Test. Improve your knowledge with multiple choice questions and detailed explanations. Prepare effectively to master SQL concepts!

Multiple Choice

Which query includes all orders and their customers, even if an order has no customer (rare scenario)?

Explanation:
The idea is to keep every order and bring in the related customer data when it exists. That’s exactly what a left outer join does: it returns all rows from the orders table and, where there’s a matching customer, fills in the customer fields; where there isn’t a match, those customer fields are NULL. So the query you want is: SELECT * FROM orders o LEFT JOIN customers c ON o.customer_id = c.id; If an order has no customer, the order still appears with NULLs in the customer columns. An inner join would drop such orders, which isn’t desirable here. A full join would also include customers with no orders, and a right join would preserve all customers instead of all orders, so they don’t fit the requirement.

The idea is to keep every order and bring in the related customer data when it exists. That’s exactly what a left outer join does: it returns all rows from the orders table and, where there’s a matching customer, fills in the customer fields; where there isn’t a match, those customer fields are NULL. So the query you want is: SELECT * FROM orders o LEFT JOIN customers c ON o.customer_id = c.id; If an order has no customer, the order still appears with NULLs in the customer columns. An inner join would drop such orders, which isn’t desirable here. A full join would also include customers with no orders, and a right join would preserve all customers instead of all orders, so they don’t fit the requirement.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy