|
1 | 1 | ---
|
2 |
| -Title: 'Primary Keys' |
3 |
| -Description: 'Primary keys are special columns used to uniquely identify each row of a table in SQL.' |
| 2 | +Title: 'PRIMARY KEYS' |
| 3 | +Description: 'Uniquely identifies each record in a table and ensures data integrity by preventing duplicate or `NULL` values in one or more specified columns.' |
4 | 4 | Subjects:
|
5 | 5 | - 'Computer Science'
|
6 | 6 | - 'Data Science'
|
7 | 7 | Tags:
|
8 |
| - - 'Comments' |
9 |
| - - 'Documentation' |
| 8 | + - 'Database' |
| 9 | + - 'Primary Key' |
| 10 | + - 'Tables' |
10 | 11 | CatalogContent:
|
11 | 12 | - 'learn-sql'
|
12 |
| - - 'paths/analyze-data-with-sql' |
| 13 | + - 'paths/data-science' |
13 | 14 | ---
|
14 | 15 |
|
15 |
| -**Primary keys** are special columns that are used to uniquely identify each row of a table in SQL. |
| 16 | +The **`PRIMARY KEY`** constraint is a fundamental database constraint that uniquely identifies each record in a table. It serves as the main identifier for rows and ensures data integrity by preventing duplicate records and null values in the specified column or columns. It combines the functionality of both `NOT NULL` and `UNIQUE` constraints, making it essential for maintaining data consistency and establishing relationships between tables. |
| 17 | + |
| 18 | +`PRIMARY KEY` constraints are used extensively in database design for creating unique identifiers, establishing table relationships through foreign keys, enabling efficient data retrieval through automatic indexing, and maintaining referential integrity across related tables. They are commonly implemented in user management systems for unique user IDs, inventory systems for product identification, order processing systems for transaction tracking, and any scenario where each record must be uniquely identifiable and accessible. |
16 | 19 |
|
17 | 20 | ## Syntax
|
18 | 21 |
|
| 22 | +The PRIMARY KEY constraint can be defined in two ways: |
| 23 | + |
| 24 | +### Method 1: Column-Level Definition |
| 25 | + |
19 | 26 | ```pseudo
|
20 |
| -CREATE TABLE table_key ( |
21 |
| - id INTEGER PRIMARY KEY, |
22 |
| - column_1 TEXT, |
23 |
| - column_2 INTEGER |
| 27 | +CREATE TABLE table_name ( |
| 28 | + column_name data_type PRIMARY KEY, |
| 29 | + column2 data_type, |
| 30 | + ... |
24 | 31 | );
|
25 | 32 | ```
|
26 | 33 |
|
27 |
| -The `PRIMARY KEY` constraint is used to create columns that uniquely identify each row. A primary key column has a few requirements: |
| 34 | +### Method 2: Table-Level Definition |
28 | 35 |
|
29 |
| -- None of the values can be `NULL`. |
30 |
| -- Each value must be unique (e.g., two rows in a `customers` table wouldn't have the same primary `customer_id`). |
31 |
| -- A table cannot have more than one primary key. |
32 |
| - |
33 |
| -Attempts to insert a row with an existing primary key will result in a constraint violation that prevents the new row from being added. |
| 36 | +```pseudo |
| 37 | +CREATE TABLE table_name ( |
| 38 | + column1 data_type, |
| 39 | + column2 data_type, |
| 40 | + ..., |
| 41 | + CONSTRAINT constraint_name PRIMARY KEY (column1) |
| 42 | +); |
| 43 | +``` |
34 | 44 |
|
35 |
| -If a table was created without a primary key, it can be added with the [`ALTER TABLE`](https://www.codecademy.com/resources/docs/sql/commands/alter-table) command. The statement below adds a primary `id` column, via the `PRIMARY KEY` constraint, to `table_name`: |
| 45 | +### Adding PRIMARY KEY to Existing Table |
36 | 46 |
|
37 | 47 | ```pseudo
|
38 | 48 | ALTER TABLE table_name
|
39 |
| -ADD PRIMARY KEY (id); |
| 49 | +ADD CONSTRAINT constraint_name PRIMARY KEY (column_name); |
40 | 50 | ```
|
41 | 51 |
|
42 |
| -## Foreign Keys |
| 52 | +**Parameters:** |
| 53 | + |
| 54 | +- `table_name`: The name of the table where the `PRIMARY KEY` constraint will be applied |
| 55 | +- `column_name`: The column or columns that will form the primary key |
| 56 | +- `data_type`: The data type of the primary key column(s) |
| 57 | +- `constraint_name`: Optional name for the `PRIMARY KEY` constraint (recommended for easier management) |
| 58 | + |
| 59 | +**Return value:** |
43 | 60 |
|
44 |
| -When the primary key for one table appears in a different table, it is called a foreign key. The most common types of [joins](https://www.codecademy.com/resources/docs/sql/joins) will be joining a foreign key from one table with the primary key from another table. |
| 61 | +The `PRIMARY KEY` constraint itself does not return a value. However, it enforces uniqueness and creates an automatic index that improves query performance when searching by the primary key column(s). |
45 | 62 |
|
46 |
| -Using the following `customers` table as an example: |
| 63 | +## Example 1: Basic Table Creation |
| 64 | + |
| 65 | +This example demonstrates creating a table with a single-column primary key for user management: |
47 | 66 |
|
48 | 67 | ```sql
|
49 |
| -CREATE TABLE customers ( |
50 |
| - customer_id INTEGER NOT NULL, |
51 |
| - first_name varchar(255), |
52 |
| - last_name varchar(255) |
| 68 | +-- Create a users table with UserID as primary key |
| 69 | +CREATE TABLE Users ( |
| 70 | + UserID INT PRIMARY KEY, |
| 71 | + Username VARCHAR(50) NOT NULL, |
| 72 | + Email VARCHAR(100) NOT NULL, |
| 73 | + DateCreated DATE |
53 | 74 | );
|
| 75 | + |
| 76 | +-- Insert sample data |
| 77 | +INSERT INTO Users (UserID, Username, Email, DateCreated) VALUES |
| 78 | +( 1, 'john_doe', '[email protected]', '2024-01-15'), |
| 79 | +( 2, 'jane_smith', '[email protected]', '2024-01-16'), |
| 80 | +( 3, 'mike_wilson', '[email protected]', '2024-01-17'); |
54 | 81 | ```
|
55 | 82 |
|
56 |
| -The `orders` table is created and joined via `FOREIGN KEY` with the existing `customer` table through its `customer_id`: |
| 83 | +Output of this code is: |
57 | 84 |
|
58 |
| -```sql |
59 |
| -CREATE TABLE orders ( |
60 |
| - order_id INTEGER NOT NULL, |
61 |
| - total_cost FLOAT, |
62 |
| - purchase_date DATE, |
63 |
| - customer_id INTEGER NOT NULL, |
64 |
| - PRIMARY KEY (order_id), |
65 |
| - FOREIGN KEY (customer_id) REFERENCES customers(customer_id) |
66 |
| -); |
| 85 | +```shell |
| 86 | +Table 'Users' created successfully with UserID as PRIMARY KEY. |
| 87 | +3 rows inserted successfully. |
67 | 88 | ```
|
68 | 89 |
|
69 |
| -The displayed `orders` table, with its primary key (`order_id`) and foreign key (`customer_id`), may look like this: |
| 90 | +The `UserID` column serves as the primary key, automatically ensuring that each user has a unique identifier. The database will reject any attempt to insert duplicate `UserID` values or `NULL` values in this column, maintaining data integrity for the user management system. |
70 | 91 |
|
71 |
| -| order_id | customer_id | total_cost | purchase_date | |
72 |
| -| -------- | ----------- | ---------- | ------------- | |
73 |
| -| 1 | 1001 | 13.99 | 2022-01-01 | |
74 |
| -| 2 | 1294 | 61.42 | 2022-01-01 | |
75 |
| -| 3 | 1001 | 23.45 | 2022-01-02 | |
| 92 | +## Example 2: E-commerce Order Management |
76 | 93 |
|
77 |
| -## Composite Keys |
| 94 | +This example shows implementing a composite primary key for order line items in an e-commerce system: |
78 | 95 |
|
79 |
| -Sometimes, having one primary key per table is not enough to uniquely identify a row. In such cases, multiple columns would work as composite keys for the table. This requirement should be detected during the designing phase of a database. |
| 96 | +```sql |
| 97 | +-- Create order items table with composite primary key |
| 98 | +CREATE TABLE OrderItems ( |
| 99 | + OrderID INT NOT NULL, |
| 100 | + ProductID INT NOT NULL, |
| 101 | + Quantity INT NOT NULL, |
| 102 | + UnitPrice DECIMAL(10,2) NOT NULL, |
| 103 | + LineTotal DECIMAL(12,2), |
| 104 | + CONSTRAINT PK_OrderItems PRIMARY KEY (OrderID, ProductID) |
| 105 | +); |
80 | 106 |
|
81 |
| -For example, a database of car parts will have to uniquely identify a row of parts. Either the `engine_ID` or `body_ID` could be used. However, this may create ambiguity as cars could get their engines swapped. |
| 107 | +-- Insert order line items |
| 108 | +INSERT INTO OrderItems (OrderID, ProductID, Quantity, UnitPrice, LineTotal) VALUES |
| 109 | +(1001, 501, 2, 29.99, 59.98), |
| 110 | +(1001, 502, 1, 45.50, 45.50), |
| 111 | +(1002, 501, 3, 29.99, 89.97), |
| 112 | +(1002, 503, 1, 15.25, 15.25); |
82 | 113 |
|
83 |
| -Depending on local regulations, a car may require an engine part ID and a body ID to be associated with a license plate. One solution might be adding more row information about the car, such as `left_door_ID`, `gearbox_ID`, etc. But then a specific car would have to be identified by two different aspects: its body and its engine. |
| 114 | +-- Attempt to insert duplicate composite key (will fail) |
| 115 | +INSERT INTO OrderItems (OrderID, ProductID, Quantity, UnitPrice, LineTotal) VALUES |
| 116 | +(1001, 501, 1, 29.99, 29.99); |
| 117 | +``` |
84 | 118 |
|
85 |
| -A composite key would be useful in this case. This is how a `vehicle_registry` table might look (extra parts/columns omitted for brevity): |
| 119 | +The output of this code will be: |
86 | 120 |
|
87 |
| -| engine_id | body_id | gearbox_id | purchase_date | |
88 |
| -| --------- | ------- | ---------- | ------------- | |
89 |
| -| 500 | abc | 001 | 2022-01-01 | |
90 |
| -| 600 | def | 002 | 2022-01-01 | |
91 |
| -| 700 | ghi | 003 | 2022-01-02 | |
| 121 | +```shell |
| 122 | +Table 'OrderItems' created successfully. |
| 123 | +4 rows inserted successfully. |
| 124 | +ERROR: Duplicate entry '1001-501' for key 'PRIMARY' |
| 125 | +``` |
92 | 126 |
|
93 |
| -The statement below creates the `vehicle_registry` table with a composite key: |
| 127 | +The composite primary key (`OrderID`, `ProductID`) ensures that each product can appear only once per order, preventing duplicate line items while allowing the same product to appear in different orders. This design maintains data integrity in e-commerce order processing. |
| 128 | + |
| 129 | +## Example 3: Adding PRIMARY KEY to Existing Table |
| 130 | + |
| 131 | +This example demonstrates adding a primary key constraint to an existing table and handling the challenges that may arise: |
94 | 132 |
|
95 | 133 | ```sql
|
96 |
| -CREATE TABLE vehicle_registry ( |
97 |
| - engine_id INTEGER, |
98 |
| - body_id TEXT, |
99 |
| - gearbox_id INTEGER, |
100 |
| - purchase_date DATE, |
101 |
| - PRIMARY KEY(engine_id, body_id, purchase_date) |
| 134 | +-- Create a products table without primary key initially |
| 135 | +CREATE TABLE Products ( |
| 136 | + ProductCode VARCHAR(20) NOT NULL, |
| 137 | + ProductName VARCHAR(100) NOT NULL, |
| 138 | + Category VARCHAR(50), |
| 139 | + Price DECIMAL(8,2) |
102 | 140 | );
|
| 141 | + |
| 142 | +-- Insert sample data |
| 143 | +INSERT INTO Products (ProductCode, ProductName, Category, Price) VALUES |
| 144 | +('LAPTOP001', 'Gaming Laptop', 'Electronics', 1299.99), |
| 145 | +('MOUSE002', 'Wireless Mouse', 'Electronics', 29.99), |
| 146 | +('DESK003', 'Standing Desk', 'Furniture', 399.99); |
| 147 | + |
| 148 | +-- Add PRIMARY KEY constraint to existing table |
| 149 | +ALTER TABLE Products |
| 150 | +ADD CONSTRAINT PK_Products PRIMARY KEY (ProductCode); |
| 151 | + |
| 152 | +-- Verify the constraint by attempting duplicate insertion |
| 153 | +INSERT INTO Products (ProductCode, ProductName, Category, Price) VALUES |
| 154 | +('LAPTOP001', 'Another Laptop', 'Electronics', 999.99); |
| 155 | +``` |
| 156 | + |
| 157 | +The output generated by this code will be: |
| 158 | + |
| 159 | +```shell |
| 160 | +Table 'Products' created successfully. |
| 161 | +3 rows inserted successfully. |
| 162 | +PRIMARY KEY constraint 'PK_Products' added successfully. |
| 163 | +ERROR: Duplicate entry 'LAPTOP001' for key 'PRIMARY' |
103 | 164 | ```
|
| 165 | + |
| 166 | +Adding a `PRIMARY KEY` constraint to an existing table requires that all existing data in the specified column(s) be unique and non-null. The database will automatically create an index on the `ProductCode` column, improving query performance for product lookups in inventory management systems. |
| 167 | + |
| 168 | +## Frequently Asked Questions |
| 169 | + |
| 170 | +### 1. Can a table have multiple primary keys? |
| 171 | + |
| 172 | +No, a table can have only one `PRIMARY KEY` constraint. However, that single primary key can consist of multiple columns (composite primary key). If you need additional unique constraints, use `UNIQUE` constraints instead. |
| 173 | + |
| 174 | +### 2. What happens if I try to insert NULL values into a primary key column? |
| 175 | + |
| 176 | +The database will reject the insertion with an error. `PRIMARY KEY` columns automatically have the `NOT NULL` constraint, so they cannot contain `NULL` values under any circumstances. |
| 177 | + |
| 178 | +### 3. What's the difference between `PRIMARY KEY` and `UNIQUE` constraints? |
| 179 | + |
| 180 | +A `PRIMARY KEY` enforces both `UNIQUE` and `NOT NULL` constraints on a column or group of columns. In contrast, `UNIQUE` allows `NULL` values (typically one per column, depending on the RDBMS). Also, a table can have only one `PRIMARY KEY` but can have multiple `UNIQUE` constraints. `PRIMARY KEY`s are also used in defining `FOREIGN KEY` relationships. |
0 commit comments