[TODO]
- Querrying SELECT, FROM, WHERE, ORDER BY
- Subquerries
- JOINS
- UNIONS?
- Triggers, stored procedures
Guide
Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
NOT NULL
- Ensures that a column cannot have a NULL valueUNIQUE
- Ensures that all values in a column are differentPRIMARY KEY
- A combination of aNOT NULL
andUNIQUE
. Uniquely identifies each row in a tableFOREIGN KEY
- Prevents actions that would destroy links between tablesCHECK
- Ensures that the values in a column satisfies a specific conditionDEFAULT
- Sets a default value for a column if no value is specifiedCREATE INDEX
- Used to create and retrieve data from the database very quickly
Syntax
(
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Data Integrity
Data integrity ensures the accuracy, and consistency of data over its life-cycle.
Referential Integrity
Referential Integrity ensures that changes to a table do not break logic constraints of other tables.
Relations
One-to-One
One-to-Many (Associative)
Denormalization
The process of transforming normalized relations into nonnormalized physical record specifications.
Examples from Khan Academy
Creating tables
(
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
weight REAL
);
(
id INTEGER PRIMARY KEY,
age INTEGER
);
Inserting data
INSERT INTO customers VALUES (73, "Brian", 33);
Inseting data for named columns
INSERT INTO customers (name, age) VALUES ("Brian", 33);
Querying Data
SELECT * FROM customers;
SELECT name, age FROM customers;
SELECT * FROM customers
WHERE age > 21;
Filter with multiple conditions
SELECT * FROM customers
WHERE age < 21 AND state = "NY";
SELECT * FROM customers
WHERE plan IN ("free", "basic");
SELECT * FROM customers
WHERE age > 21 ORDER BY age DESC;
SELECT name, CASE WHEN age > 18 THEN "adult" ELSE "minor" END "type" FROM customers;
Aggregating data
SELECT MAX(age) FROM customers;
SELECT gender, COUNT(*) FROM students GROUP BY gender;
Updating and deleting data
UPDATE customers SET age = 44 WHERE id = 73;
DELETE FROM customers WHERE id = 73;
Joining related tables
SELECT customers.name, orders.time FROM customers
JOIN orders ON customers.id = order.customer_id;
SELECT customers.name, orders.item FROM customers
LEFT OUTER JOIN orders ON customers.id = orders.customer_id;