Skip to content

Commit 902dbce

Browse files
[Edit] SQL: Primary Keys (#7118)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit] SQL: Primary Keys * Update content/sql/concepts/primary-keys/primary-keys.md * Update content/sql/concepts/primary-keys/primary-keys.md * Update content/sql/concepts/primary-keys/primary-keys.md ---------
1 parent 9309787 commit 902dbce

File tree

1 file changed

+135
-58
lines changed

1 file changed

+135
-58
lines changed
Lines changed: 135 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,180 @@
11
---
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.'
44
Subjects:
55
- 'Computer Science'
66
- 'Data Science'
77
Tags:
8-
- 'Comments'
9-
- 'Documentation'
8+
- 'Database'
9+
- 'Primary Key'
10+
- 'Tables'
1011
CatalogContent:
1112
- 'learn-sql'
12-
- 'paths/analyze-data-with-sql'
13+
- 'paths/data-science'
1314
---
1415

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.
1619

1720
## Syntax
1821

22+
The PRIMARY KEY constraint can be defined in two ways:
23+
24+
### Method 1: Column-Level Definition
25+
1926
```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+
...
2431
);
2532
```
2633

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
2835

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+
```
3444

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
3646

3747
```pseudo
3848
ALTER TABLE table_name
39-
ADD PRIMARY KEY (id);
49+
ADD CONSTRAINT constraint_name PRIMARY KEY (column_name);
4050
```
4151

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:**
4360

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).
4562

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:
4766

4867
```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
5374
);
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');
5481
```
5582

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:
5784

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.
6788
```
6889

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.
7091

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
7693

77-
## Composite Keys
94+
This example shows implementing a composite primary key for order line items in an e-commerce system:
7895

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+
);
80106

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);
82113

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+
```
84118

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:
86120

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+
```
92126

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:
94132

95133
```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)
102140
);
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'
103164
```
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

Comments
 (0)