SQL
Retrieve Related Data Across Multiple Tables with INNER JOIN
Discover how to combine rows from two or more related tables based on common columns using INNER JOIN, fetching comprehensive datasets from different entities for web display.
SELECT
o.order_id,
u.username,
p.product_name,
oi.quantity,
oi.price_at_order
FROM
orders o
INNER JOIN
users u ON o.user_id = u.user_id
INNER JOIN
order_items oi ON o.order_id = oi.order_id
INNER JOIN
products p ON oi.product_id = p.product_id
WHERE
o.order_date >= '2023-01-01';
How it works: This query illustrates how to link data from several tables using `INNER JOIN`. Each `INNER JOIN` clause connects two tables (e.g., `orders` and `users`) based on a matching column (`user_id`). This allows fetching a unified result set that includes information from all joined tables, such as order details, customer names, and product information, essential for displaying complex user-facing data.