Skip to main content
Practice Problems

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 tables

Explanation of the Query

In this query:

  • The clients table is the left table.
  • The purchases table is the right table, which ensures that all its rows are included in the result set.
  • The ON clause specifies the condition for joining the two tables.

Result Interpretation

In the result of the query:

  • If there are any rows in the purchases table that do not have a corresponding entry in the clients table, the full_name will be NULL.
  • 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 | Speaker

Explanation of the Transactions Query

  • This query selects customer_name and item from the transactions table.
  • It filters out any rows where customer_name is NULL and orders the results by customer_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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems