Sql query fetching data from multiple tables
Fetch data from different tables using SQL JOINs. An INNER JOIN returns records with matching values in both tables:
This collects product names and their corresponding sales prices, in cases where the product IDs match in both tables.
Comprehending JOINs and table aliasing
In SQL, the JOIN
clause combines rows from two or more tables based on a related column. Understanding how to use different types of JOINs
is key to mastering data retrieval from multiple tables:
- INNER JOIN: Returns records with matching values in both tables.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table, and any matched records from the right.
- RIGHT JOIN (or RIGHT OUTER JOIN): Returns all records from the right table, and any matched records from the left.
- FULL JOIN (or FULL OUTER JOIN): Returns all records when there is a match in either left (or right) table.
Utilizing table aliases (AS
) can make the query more readable, and helps prevent issues caused by ambiguous column names:
Here, p
and s
are aliases for products
and sales
tables respectively.
Applying set operators and subqueries for complex data
Set operators like UNION
and INTERSECT
, along with subqueries can be used to achieve complex filtering.
- UNION: Combines rows from two or more select statements and removes duplicate rows.
- UNION ALL: Similar to UNION but does not remove duplicate rows.
Subqueries, or nested queries can be used in various contexts and add another dimension to our SQL querying capabilities:
In this case, the subquery fetches product_id
s from sales
table to filter products.
SQL syntax and performance oddities
When joining multiple tables, remember to account for NULL values.
To avoid fetching duplicate rows and enhance performance, DISTINCT
can be used in the select clause.
Grouping and aggregation of complex datasets
Working with aggregate functions like SUM
, AVG
, MIN
, MAX
or COUNT
, can provide valuable insights from your data.
Oh look, we now know how many items were sold in each product category.
The grand temporal showdown: Using LEAST and GREATEST
In a world where time is of essence, the LEAST
and GREATEST
functions can come in handy to quickly identify the earliest or latest records.
Was this article helpful?