How does right join work?
markdown
## Understanding RIGHT JOIN in SQL
### Overview of RIGHT JOIN
A **RIGHT JOIN** in SQL is used to return all rows from the right table, along with the matched rows from the left table. If there is no match, NULL values are returned for columns from the left table.
### Example Data
Here is an example of data that might be used in a RIGHT JOIN:
200 | 1 | Tablet 201 | 1 | Charger 202 | 2 | Headphones 203 | 3 | Webcam
### SQL Query Breakdown
The following SQL query demonstrates how a RIGHT JOIN is implemented:
```sql
SELECT
clients.full_name,
purchases.item
FROM
clients -- Left table
FULL OUTER JOIN
purchases -- Right table: returns all its rows
ON
clients.client_id = purchases.buyer_id; -- Condition for joining tablesExplanation of the Query
In this query:
- The
clientstable is the left table. - The
purchasestable is the right table, which ensures that all its rows are included in the result set. - The
ONclause specifies the condition for joining the two tables.
Result Interpretation
In the result of the query:
- If there are any rows in the
purchasestable that do not have a corresponding entry in theclientstable, thefull_namewill beNULL. - For example, if there is an order for a Monitor that does not have a matching client, the order will still be included in the result due to the nature of the RIGHT JOIN.
Additional Example
Consider the following SQL query that filters out NULL customer names from a transactions table:
sql
SELECT customer_name, item
FROM transactions
WHERE customer_name IS NOT NULL
ORDER BY customer_name;
-- Sample data for 'transactions' table
-- customer_name | item
--
-- Charlie | Tablet
-- Charlie | Charger
-- Dana | Headphones
-- NULL | SpeakerExplanation of the Transactions Query
- This query selects
customer_nameanditemfrom thetransactionstable. - It filters out any rows where
customer_nameis NULL and orders the results bycustomer_name. - The sample data shows that while there is a NULL entry for
Speaker, it will not be included in the final output due to the filtering condition.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.