Sunday, September 24, 2023

What is the difference between LEFT JOIN and RIGHT JOIN in SQL?

LEFT JOIN and RIGHT JOIN are both types of OUTER JOINs in SQL, which means they return not only the rows that have matching values in both tables but also the unmatched rows from either the left (in the case of LEFT JOIN) or the right (in the case of RIGHT JOIN) table.

The key difference between them is the source of the unmatched rows:

  1. 1.LEFT JOIN (or LEFT OUTER JOIN):


  • A LEFT JOIN returns all rows from the left table (the first table specified in the query) and the matching rows from the right table (the second table specified in the query).
  • If there is no match in the right table, NULL values are included in the result for the columns from the right table.
  • Rows from the left table without a match in the right table will still appear in the result with NULL values for the columns from the right table.
      1. Example:

        SELECT employees.name, departments.department_name 
      2. FROM employees 
      3. LEFT JOIN departments ON employees.department_id = departments.department_id;

      4. 2.RIGHT JOIN (or RIGHT OUTER JOIN):


        • A RIGHT JOIN returns all rows from the right table and the matching rows from the left table.
        • If there is no match in the left table, NULL values are included in the result for the columns from the left table.
        • Rows from the right table without a match in the left table will still appear in the result with NULL values for the columns from the left table.

        Example:

        SELECT employees.name, departments.department_name 
      5. FROM employees
      6. RIGHT JOIN departments ON employees.department_id = departments.department_id;

      In both cases, you get all the rows from one of the tables (left or right) and the matching rows from the other table. The choice between LEFT JOIN and RIGHT JOIN depends on your preference or the structure of your data. You can often achieve the same results using either one, but it may affect the order of columns in your result set. Some SQL dialects don't support RIGHT JOIN, so you may need to use LEFT JOIN and switch the table order if necessary. 

      No comments:

      Post a Comment

      If you have any doubts. Please let me know

      How can you create an alias for a table in a SQL query?

      In SQL, you can create an alias for a table in a query to give the table a temporary, alternative name that you can use in the query. Table ...