Week+3SQL
Week+3SQL
Subqueries
• Subqueries are queries embedded into other queries.
• Subqueries merge data from multiple sources together.
• Helps with adding other filtering criteria.
Example: Need to know the region each customer is from who has had an
order with freight over 100.
The innermost query is used to filter for customers that we are getting back.
The first thing we want to go over with joins is that these joins are what
associate the correct records from each table on the fly.(what does this
mean?)
To explain, we’ll go back to our example of you have a table that list the different
customer demographics but you want to know all of the orders that the customer has
made. So, a join will allow you to associate the correct customer information with the
correct order, quickly and on the fly with your query.
• Joins are not permanent. They persist for the duration of the query
execution.
How to do this?
So again, we're still listing out the columns
that we want from both tables.
SELECT suppliers.company_name,
product_name,
unit_price
FROM Suppliers INNER JOIN Products
ON Suppliers.supplier_id = Products.supplier_id
Example:
SELECT o.order_id, c.company_name, e.last_name
FROM (orders o INNER JOIN Customers c
ON o.customer_id = c.Customer_id )
INNER JOIN Employees e ON o.Employee_id = e.Employee_id
Aliases and Self Joins
What is an alias?
• SQL aliases give a table or a column a temporary name.
• Make column names more readable
• An alias exist only for duration of a query.
SELECT column_name
FROM table_name AS alias_name
Self Joins
SELECT column_name(s)
FROM table T1, table T2
WHERE condition
Left join returns all records from the left table (table 1)
and the matched records from the right table (table2).
The result is NULL from the right side, when there is no
match.
Right join is the same as left join except the order of tables are switched.
It returns all the records from the right table, and matched records from the left table.
The result is NULL from the left side, when there is no match.
The following will select all the customers and all the orders. (Full Join)
Example: