Sql SELECT from multiple tables
To extract data from multiple SQL tables, INNER JOIN is your ladder to climb data mountains. It brings together related records. Fields common to the tables are your hitch points.
The query puts in your shopping basket field1
from first_table
and field2
from second_table
, but only when their id
fields are twins.
Deciphering JOIN types: read their minds
Different JOIN types shape data differently:
- INNER JOIN: The snob. Parties only with records that are common in both tables.
- LEFT JOIN (or LEFT OUTER JOIN): The clingy type. Holds onto all records from the left table, and drags in matching records from the right table. If the right side has no match, "NULL" is their plus one.
- RIGHT JOIN (or RIGHT OUTER JOIN): Same as LEFT JOIN, but flips the roles. ALL records from the right table (including those with no match on the left side) march into the result set.
- FULL JOIN (or FULL OUTER JOIN): The extrovert. Invites all records when there's a match in either left or right table.
Bringing together customer and product data: the matchmaker
Need to display customer and product figures as a pair? A LEFT JOIN will do, ensuring all products are escorted by a customer, even if it's "NULL":
// @Santa, this fills up your stocking with NULL for naughty customers who didn't buy a product!
The UNION: the peace-maker
Sometimes, you want to unite similar data from different tables. UNION creates harmony by fusing two or more datasets:
// Sure beats writing a constitution! Just remember to select the same number of columns, in the same order, with compatible data types. Or else… chaos!
Query optimization: your coding fitness regime
For big-league joins and unions:
- Adopt aliases to simplify your query life.
- Verify your join conditions. Don't match apples and oranges!
- Put UNION ALL in your toolkit for faster operation, when you're cool with duplicates.
- Index foreign keys. Your joins will thank you.
Was this article helpful?