Uniting Data: Understanding Joins in SQL Server
product_id | product_name | category | price | stock |
---|---|---|---|---|
1 | Wireless Mouse | Electronics | 1200 | 25 |
2 | Yoga Mat | Fitness | 800 | 50 |
3 | Bluetooth Speaker | Electronics | 2500 | 15 |
4 | Water Bottle | Fitness | 300 | 100 |
5 | Smartwatch | Electronics | 5000 | 10 |
order_id | product_id | order_date | quantity |
---|---|---|---|
101 | 1 | 2025-01-01 | 2 |
102 | 2 | 2025-01-02 | 5 |
103 | 3 | 2025-01-02 | 1 |
104 | 5 | 2025-01-03 | 2 |
105 | 4 | 2025-01-03 | 10 |
NULL
.NULL
.NULL
.product_name | quantity | order_date |
---|---|---|
Wireless Mouse | 2 | 2025-01-01 |
Yoga Mat | 5 | 2025-01-02 |
Bluetooth Speaker | 1 | 2025-01-02 |
Smartwatch | 2 | 2025-01-03 |
Water Bottle | 10 | 2025-01-03 |
product_id
values in both tables are returned.
product_name | quantity | order_date |
---|---|---|
Wireless Mouse | 2 | 2025-01-01 |
Yoga Mat | 5 | 2025-01-02 |
Bluetooth Speaker | 1 | 2025-01-02 |
Water Bottle | 10 | 2025-01-03 |
Smartwatch | 2 | 2025-01-03 |
products
even if there’s no matching product_id
in orders
.
products
table, use a RIGHT JOIN.
product_name | quantity | order_date |
---|---|---|
Wireless Mouse | 2 | 2025-01-01 |
Yoga Mat | 5 | 2025-01-02 |
Bluetooth Speaker | 1 | 2025-01-02 |
Smartwatch | 2 | 2025-01-03 |
Water Bottle | 10 | 2025-01-03 |
product_name | quantity | order_date |
---|---|---|
Wireless Mouse | 2 | 2025-01-01 |
Yoga Mat | 5 | 2025-01-02 |
Bluetooth Speaker | 1 | 2025-01-02 |
Smartwatch | 2 | 2025-01-03 |
Water Bottle | 10 | 2025-01-03 |
NULL
values where necessary.
product_name | order_date |
---|---|
Wireless Mouse | 2025-01-01 |
Wireless Mouse | 2025-01-02 |
Wireless Mouse | 2025-01-03 |
… |