100 Days of SQL

sql

Day 19 – SQL LEFT JOIN Keyword

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

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


SELECT *
FROM table1
LEFT 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 LEFT JOIN operation is a new table that includes all the rows from the left table and the matching rows from the right table. If there is no match, the result will contain NULL values for the right table columns.

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


SELECT table1.column1 AS column1_alias, table2.column2 AS column2_alias
FROM table1
LEFT 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 LEFT OUTER JOIN keyword can be used interchangeably with LEFT JOIN. The same is true for RIGHT JOIN and RIGHT OUTER JOIN.