SQL right join
Created By: chatGPT
RIGHT JOIN in SQL is used to combine rows from two or more tables. It returns all rows from the right table and the matched rows from the left table. If there is no match, NULL values will appear in the result set from the left table. This is particularly useful when you want to show all records from one table regardless of whether they have matches in the other table.
SELECT a.column1, b.column2
FROM table_a a
RIGHT JOIN table_b b ON a.id = b.a_id;
In this example,
table_b
is the right table. The query returns all rows from table_b
and the corresponding rows from table_a
. If there are entries in table_b
that do not have associated records in table_a
, those rows will still be included, but with NULL values for columns from table_a
.SELECT a.name, b.order_id
FROM customers a
RIGHT JOIN orders b ON a.customer_id = b.customer_id;
A practical scenario for using RIGHT JOIN could be when you have a product table and an inventory table. If you want to list all products and see how many are in stock, but still want to list products even if they have no inventory entries, a RIGHT JOIN serves this purpose well.
SELECT p.product_name, i.stock_quantity
FROM products p
RIGHT JOIN inventory i ON p.product_id = i.product_id;