2024-03-11
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 a NOT NULL
and UNIQUE
. 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 quicklyCREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Data integrity ensures the accuracy, and consistency of data over its life-cycle.
Referential Integrity ensures that changes to a table do not break logic constraints of other tables.
The process of transforming normalized relations into nonnormalized physical record specifications.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
weight REAL
);
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
age INTEGER
);
INSERT INTO customers VALUES (73, "Brian", 33);
Inseting data for named columns
INSERT INTO customers (name, age) VALUES ("Brian", 33);
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;
SELECT MAX(age) FROM customers;
SELECT gender, COUNT(*) FROM students GROUP BY gender;
UPDATE customers SET age = 44 WHERE id = 73;
DELETE FROM customers WHERE id = 73;
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;