Primary Key
In relational algebra, a primary key is a unique identifier for a tuple (row) in a relation (table). It ensures that no two tuples have the same value for the primary key attribute(s), thereby maintaining the integrity and uniqueness of the data within the relation.
Key characteristics of a primary key:
- Uniqueness: Each value of the primary key must be unique across the relation.
- Non-nullability: Primary key attributes cannot contain NULL values.
- Minimality: The primary key must be minimal, meaning no subset of the primary key attributes can uniquely identify a tuple.
- Composite Key: A primary key can be composed of multiple attributes, known as a composite key.
Declaring a Table with a Primary Key
CREATE TABLE orders (
INT,
order_id INT,
product_id INT,
quantity PRIMARY KEY (order_id)
);
Declaring a table with an Auto-generated Primary Key
A primary key can be auto-generated by the database system.
In PostgreSQL, you can use the
SERIAL
data type to auto-generate unique IDs for the primary key.The
SERIAL
type automatically increments the ID for each new record.CREATE TABLE customers ( PRIMARY KEY, customer_id SERIAL VARCHAR(100), name VARCHAR(100), email VARCHAR(15), phone_number VARCHAR(50) country );
Integrity Constraints
- Integrity constraints are rules that ensure the accuracy and consistency of data in a database.
- Types of integrity constraints:
Primary Key Constraint: Ensures that each record has a unique identifier.
Foreign Key Constraint: Ensures that a value in one table matches a value in another table, creating a relationship between the tables.
Unique Constraint: Ensures that all values in a column are unique.
Not Null Constraint: Ensures that a column cannot have NULL values.
Check Constraint: Ensures that all values in a column satisfy a specific condition.
CREATE TABLE Employees ( PRIMARY KEY, EmployeeID SERIAL VARCHAR(100) NOT NULL, Name VARCHAR(100) UNIQUE, Email DECIMAL CHECK (Salary > 0) Salary );
ALTER and DROP
- ALTER:
Used to modify an existing database object, such as a table.
Example:
ALTER TABLE products ADD COLUMN stock INT;
- DROP:
Used to delete an existing database object, such as a table.
Example:
DROP TABLE products;
Foreign Keys
- A foreign key is a field (or collection of fields) in one table that uniquely identifies a row in another table.
- It creates a relationship between two tables, ensuring referential integrity.
- Key characteristics:
- Referential Integrity: Ensures that a value in the foreign key column(s) must match a value in the primary key column(s) of the referenced table.
erDiagram CUSTOMERS { int customer_id PK varchar name varchar email varchar phone_number } ORDERS { int order_id PK date order_date int customer_id FK } CUSTOMERS ||--o{ ORDERS : has
CREATE TABLE orders (
PRIMARY KEY,
order_id SERIAL DATE,
order_date INT,
customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);