SQL Interview Questions · Question 07

Write a query to display each order with the customer name?

Interview preparation resource from Gate Smashers.

Interview-ready answer

SELECT o.order_id, c.customer_name, o.amount, o.status FROM Orders AS o JOIN Customers AS c ON o.customer_id = c.customer_id; -- Joins Orders to Customers using customer_id to display each order with the customer name. Use LEFT JOIN instead of JOIN if you need to include orders without a matching customer.

Customers
customer_idcustomer_namecity
1Aditi SharmaDelhi
2Rahul VermaMumbai
3Simran KaurChandigarh
4Arjun NairBengaluru
Orders
order_idcustomer_idamountstatus
50112400Delivered
50213200Delivered
50321800Delivered
50424100Pending
5053950Cancelled
SQL querysql
SELECT o.order_id, c.customer_name, o.amount, o.status
FROM Orders AS o
JOIN Customers AS c ON o.customer_id = c.customer_id;
Understand it clearly

Direct query

Use an equi-join between Orders and Customers on the customer_id column. The query returns order-level details together with the customer's name. See the SQL code block in the content blocks below for the exact statement.

Relationship key

customer_id is the relationship key linking the two tables: Orders.customer_id corresponds to Customers.customer_id.

  • Key: customer_id ties Orders to Customers.
  • Returned columns: order_id, customer_name, amount, status (as shown in the query).

Join behavior and when to use

The supplied query uses an INNER JOIN (written as JOIN) which returns only orders that have a matching customer row. If you need to preserve orders that lack a matching customer (orphaned orders), use a LEFT JOIN with Orders as the left table.

  • INNER JOIN: Returns only orders with a matching customer.
  • LEFT JOIN: Returns all orders; customer columns will be NULL where no matching customer exists.

Sample data

The following tables are the sample Customers and Orders data referenced by the query. Use them to verify the query's behavior.

Quick comparison
BasisINNER JOINLEFT JOIN
Returned rowsOnly orders that have a matching customer row.All orders; unmatched customers show NULL for customer columns.
When to useWhen you only want orders with existing customers.When you must keep orphaned orders visible even if customer is missing.