Keys, Join, and Union Flashcards
Primary Keys
are used to uniquely identify a row on a table.
Natural Key
a unique value in the data that can be used to identify a specific row on the table. (example a student id)
Surrogate Key
a generated unique value that is used when no natural key is available (example a sequentially generated number)
Composite Key
when a 2 or more columns are used as the key to identify a unique row on a table. (example a card suit and rank)
Foreign Key
Exist in other tables to reference a unique related row in the source table. Used to create relationships between tables.
Usually References a primary key, but can reference any column that contains a unique value that can be used to identify a specific row.
Can reference a composite key, but all columns that make up the primary key on the source table must be referenced on the table.
Cardinality, Degrees of Cardinality
One-to-One (1:1)
One-to-Many (1:N)
Many-to-Many (M:N)
One-to-One (1:1) Cardinality
One entity of data on a table relates to a single entity of data on another table.
An entity on one table relates to a single entity on a second table.
Requires no extra tables, a foreign key can be used either way without duplicating data.
One-to-Many (1:N) Cardinality
One entity of data on a table relates to a multiple entities of data on another table.
An entity on one table can relate to multiple entities on a second table.
Requires no extra table, the table on the 1 side’s primary key can be added to the table with the M relationships without duplication of data
Many-to-Many (M:N) Cardinality
Multiple entities of data on a table relates to a multiple entities of data on another table.
Joins
SQL JOINs allow us to create queries that produce data from one or more tables.
Related records are “joined” into a single result.
Joins are referred to as INNER and OUTER.
Inner Join(default)
Selects all rows from both participating tables as long as there is a match between the columns.
Left Join
Left Outer Join
SELECT one.number AS one_number, one.description as one_description, two.number as two_number, two.description as two_description
FROM one
LEFT JOIN two ON one.number = two.number
I’d stress that things that don’t have a match on the right have null values for columns from that table in the results.
Right Join
Right Outer Join
SELECT one.number AS one_number, one.description as one_description, two.number as two_number, two.description as two_description
FROM one
RIGHT JOIN two ON one.number = two.number
Question: What is the difference between a LEFT JOIN and a LEFT OUTER JOIN?
Answer: Nothing, they are the same!
Question: What is the difference between a RIGHT JOIN and RIGHT OUTER JOIN?
Answer: Nothing, they are the same!