Retrieving data from multiple tables Flashcards
In MySQL what is the default JOIN type?
inner join
What two types of JOIN’s are available in MySQL?
inner and outer JOIN’s
When selecting a column that’s present on multiple tables what should be prefixed when making a selection?
the table name or alias
(customer_id being present on multiple tables)
SELECT orders.customer_id, first_name, last_name
This code has a lot of repeat words, refactor it. Using alias.
- *SELECT** order_id, orders.customer_id, first_name, last_name
- *FROM** orders
- *JOIN** customers ON orders.customer_id = customers.customer_id
- *SELECT** order_id, o.customer_id, first_name, last_name
- *FROM** orders o
- *JOIN** customers ON o.customer_id = customers.customer_id
True or False
These aliases would return the same results
FROM orders AS o
FROM orders o
True
What are the two aliases being used in this query?
- *SELECT** order_id, o.customer_id, first_name, last_name
- *FROM** orders o
- *JOIN** customers c ON o.customer_id = c.customer_id
o and c
True or False
When querying multiple tables, it’s best to:
- SELECT * (from every table)
- then make the relevant JOIN first (using aliases)
- then filter the columns needed.
True
True or False
To join multiple tables in different databases you’d prefix the database in the JOIN statement?
True
Identify the other database being used in this query?
- *SELECT** *
- *FROM** order_items oi
- *JOIN** sql_inventory.products p
- *ON** oi.product_id = p.product_id
sql_inventory
True or False
In MySQL, it’s possible to JOIN a table with itself? What is the benefit?
USE sql_hr;
- *SELECT**
e. employee_id,
e. first_name,
m. first_name AS manager - *FROM** employees e
- *JOIN** employees m ON e.reports_to = m.employee_id
True
Good for making organizational charts shows who reports to whom if the data is available.
How many tables are being joined in this query?
- *USE** sql_store;
- *SELECT**
o. order_id,
o. order_date,
c. first_name,
os. name AS status - *FROM** orders o
- *JOIN** customers c
- *ON** o.customer_id = c.customer_id
- *JOIN** order_statuses os
- *ON** o.status = os.order_status_id
3 tables
orders
customers
order_statuses
In MySQL what is a composite primary key?
A table where two columns define the primary key.
This query is an example of what?
- *SELECT** *
- *FROM** order_items oi
- *JOIN** order_item_notes oin
- *ON** oi.order_id = oin.order_id
- *AND** oi.product_id = oin.product_id
Joint compound condition, more than two columns are the primary keys.
Refactor this query using implicit join syntax
- *SELECT** *
- *FROM** orders o
- *JOIN** customers c
- *ON** o.customer_id = c.customer_id
- *SELECT** *
- *FROM** orders o, customers c
- *WHERE** o.customer_id = c.customer_id
What is a potential peril using an implicit join syntax?
If you forget the WHERE clause you’d end up with a funky cross-join.