Multi-table queries in SQL are used to retrieve data from multiple tables by joining them based on a common column. This allows you to combine and analyze data from different tables in a single query. There are several types of joins that can be used in multi-table queries, 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 is NULL on the right side.
- 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 is NULL on the left side.
- FULL OUTER JOIN: Returns all the rows from both tables, with NULL values in the columns where there is no match.
Here's an example of an INNER JOIN query:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
This query would return a list of order IDs and customer names, where the CustomerID in the Orders table matches the CustomerID in the Customers table.
You can also use the WHERE clause to filter the data returned by a multi-table query. For example:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
WHERE Customers.Country = 'USA'
This query would return a list of order IDs and customer names for customers in the USA.
You can also use the GROUP BY clause to group the data returned by a multi-table query, and the HAVING clause to filter the groups. For example:
SELECT Customers.Country, COUNT(Orders.OrderID)
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
GROUP BY Customers.Country
HAVING COUNT(Orders.OrderID) > 100
This query would return a list of countries and the number of orders for each country, but only for countries where there are more than 100 orders.
Multi-table queries are a powerful feature of SQL that allows you to combine and analyze data from multiple tables in a single query. They can be complex, but with practice, you can use them to extract valuable insights from your data.