Create Table
Identify Primary Key
Column Constraint
Table Constraint
NOT NULL
⚠️ Note: A
NOT NULL
constraint guarantees that no value of the corresponding field in any record of the table can be set toNULL
. ANOT NULL
constraint is always declared as a column constraint.
Implicit NULL
Explicit NULL
Error
Both statements will be rejected. With a
NOT NULL
constraint, you can’t insert a row without providing a value for the field.
Note
If there is a
default
value, you can insert a row without providing a value for theNOT NULL
field. But still, you can’t insert a row with explicitNULL
.
Foreign Key
-
NULL
Customers (but Not in Games) -
NULL
Games (but Not in Customers)
Note
We omit the check if any value in the set to be checked is
NULL
. We check all constraints independently and must satisfy all constraints.
CHECK
Constraint
Note
A
CHECK
constraint is declared as a column or a table constraint with theCHECK
keyword followed by the SQL condition in parenthesis. If the condition involves more than one column, it should be a table constraint.
Violate CHECK
Constraint
Error
Discounting all the prices by $5.5 creates negative prices. This operation will be aborted and rolled back.
Cascade UPDATE
and DELETE
ON UPDATE CASCADE
andON DELETE CASCADE
propagate the update or deletion.
CASE
keyword
We can do this but not preferrable.
COALESCE
keyword
COALESCE(x1, x2, x3, ...)
returns the first non-NULL
(from left-to-right) of its argument.
COALESCE(NULL, 1, NULL, 2)
is1
.COALESCE(NULL, NULL, NULL)
isNULL
.
Counting with NULL
COUNT(*)
countsNULL
values.COUNT(att)
,AVG(att)
,MAX(att)
,MIN(attt)
eliminateNULL
values.
JOIN
keyword
CROSS JOIN vs INNER JOIN
While inner join is a popular construct, there is no added expressiveness or performance in INNER JOIN. The two queries below are equivalent.
Natural Join
If we managed to give the same name to columns with the same meaning across the tables, we can use natural join. NATURAL JOIN joins rows that have the same values for columns with the same name. It also prints only one of the two columns.
Outer Join
WIP
Good Practices
Avoid NULL
It is generally a good idea to constrain all attributes to be not NULL unless there is a good design or tuning reason for not doing so.
Justify Cascade
Think carefully about which foreign keys should be subject to cascade.
Defer Constraints
It is generally a good idea to defer all the constraints that can be deferred. A deferred constraint is checked at the end of a transaction and not immediately after each operation.
Play the Devil’s Advocate
Given the complete schema for the three tables, try and find out the scenario in which an operation (insertion, deletion, update) on a table or a transaction containing a set of operation on one or more tables violate which constraint on which table.