100 Days of SQL

sql

Day 17 – SQL Joins

In SQL, a JOIN operation is used to combine rows from two or more tables based on a related column between them. The JOIN operation is a fundamental concept in SQL and is essential for querying data from multiple tables in a relational database.

There are several types of JOIN operations available in SQL, including:

  • Inner Join: Returns only the rows that have matching values in both tables.
  • Left Join: Returns all the rows from the left table and the matched rows from the right table. If there is no match, the result will contain NULL values for the right table columns.
  • Right Join: Returns all the rows from the right table and the matched rows from the left table. If there is no match, the result will contain NULL values for the left table columns.
  • Full Outer Join: Returns all the rows from both tables, matching them where possible and adding NULL values where there is no match.

The syntax for a JOIN operation depends on the type of join and the database system you’re using. Here’s an example of an inner join:


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

In this example, table1 and table2 are the names of the two tables being joined, and column is the related column between the two tables. The ON keyword specifies the condition for the join.

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Note that the result of a join operation is a new table that includes all the columns from both tables. The columns that are not used for the join will be duplicated in the result table. You can use column aliases to differentiate between the duplicated columns.

Join operations can be used in combination with other SQL operations like WHERE, GROUP BY, and ORDER BY to create complex queries that retrieve specific data from multiple tables.