100 Days of SQL

sql

Day 20 – SQL RIGHT JOIN Keyword

In SQL, the RIGHT JOIN keyword is used to combine all the rows from the right table with matching rows from the left table based on a related column between them. If there is no match, the result will contain NULL values for the left table columns.

Here’s an example of how to use the RIGHT JOIN keyword:


SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

In this example, table1 is the left table, table2 is the right table, and column is the related column between the two tables. The ON keyword specifies the condition for the join.

The result of the RIGHT JOIN operation is a new table that includes all the rows from the right table and the matching rows from the left table. If there is no match, the result will contain NULL values for the left table columns.

Here’s an example of how to use column aliases with a RIGHT JOIN:


SELECT table1.column1 AS column1_alias, table2.column2 AS column2_alias
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

In this example, column1_alias and column2_alias are the aliases given to the duplicated columns in the result table. This makes it easier to refer to the columns in the SELECT statement and the result table.

Note that in some databases, such as MySQL, the RIGHT OUTER JOIN keyword can be used interchangeably with RIGHT JOIN. The same is true for LEFT JOIN and LEFT OUTER JOIN.