Bird
Raised Fist0
SQLquery~10 mins

Primary keys and uniqueness in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Primary keys and uniqueness
Start Table Creation
↓
Define Columns
↓
Set Primary Key?
No→No uniqueness guaranteed
Yes↓
Primary Key: Unique + Not Null
↓
Insert Rows
↓
Check Uniqueness on Insert
↓
Unique
↓
Insert
↓
End
When creating a table, you define a primary key column that must be unique and not null. When inserting data, the database checks this uniqueness and rejects duplicates or nulls.
Execution Sample
SQL
CREATE TABLE Users (
  UserID INT PRIMARY KEY,
  UserName VARCHAR(50)
);

INSERT INTO Users VALUES (1, 'Alice');
INSERT INTO Users VALUES (1, 'Bob');
This code creates a Users table with UserID as primary key, inserts a row with UserID 1, then tries to insert another row with the same UserID which violates uniqueness.
Execution Table
StepActionUserID ValueUniqueness CheckResult
1Create table with UserID as PRIMARY KEYN/AN/ATable created
2Insert row (1, 'Alice')1No existing UserID=1Row inserted
3Insert row (1, 'Bob')1UserID=1 already existsInsert rejected: duplicate primary key
💡 Insert rejected at step 3 because UserID 1 already exists, violating primary key uniqueness
Variable Tracker
VariableStartAfter Step 2After Step 3
Users Table RowsEmpty[{UserID:1, UserName:'Alice'}][{UserID:1, UserName:'Alice'}] (no change due to rejection)
Key Moments - 2 Insights
Why can't we insert two rows with the same primary key value?
Because the primary key must be unique for each row. As shown in execution_table step 3, the database rejects the insert to keep uniqueness.
Can a primary key column have NULL values?
No, primary keys cannot be NULL. They must have a value that uniquely identifies each row. This is part of the primary key constraint.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 3 when inserting UserID=1 again?
AThe row is inserted successfully
BThe insert is rejected due to duplicate primary key
CThe existing row is updated
DThe insert is ignored silently
💡 Hint
Check the 'Result' column in execution_table row for step 3
According to variable_tracker, what is the state of the Users table after step 3?
AContains one row with UserID=1
BIs empty
CContains two rows with UserID=1
DContains one row with UserID=NULL
💡 Hint
Look at the 'Users Table Rows' row after step 3 in variable_tracker
If the primary key constraint was removed, what would happen at step 3?
AInsert would be rejected
BInsert would cause an error unrelated to uniqueness
CInsert would succeed allowing duplicate UserID
DInsert would update the existing row
💡 Hint
Primary key enforces uniqueness; without it duplicates are allowed
Concept Snapshot
Primary keys uniquely identify each row in a table.
They must be unique and NOT NULL.
Database rejects inserts violating primary key uniqueness.
Use PRIMARY KEY in CREATE TABLE to enforce this.
Uniqueness ensures data integrity and fast lookups.
Full Transcript
This lesson shows how primary keys enforce uniqueness in SQL tables. When you create a table with a primary key column, the database ensures no two rows have the same value in that column and that the value is not null. The example creates a Users table with UserID as the primary key. Inserting a row with UserID 1 succeeds. Trying to insert another row with UserID 1 fails because it violates uniqueness. The execution table traces these steps, showing the insert rejection. The variable tracker shows the table state after each step. Key moments clarify why duplicates and nulls are not allowed in primary keys. The quiz tests understanding of these concepts by referencing the execution visuals.

Practice

(1/5)
1. Which of the following is TRUE about a PRIMARY KEY in a SQL table?
easy
A. It allows duplicate values but no NULLs.
B. It uniquely identifies each row and cannot contain NULL values.
C. It can contain multiple NULL values.
D. It is used only for indexing and does not enforce uniqueness.

Solution

  1. Step 1: Understand the role of PRIMARY KEY

    A PRIMARY KEY uniquely identifies each row in a table and does not allow NULL values to ensure every row is distinct.
  2. Step 2: Compare options with PRIMARY KEY properties

    It uniquely identifies each row and cannot contain NULL values. correctly states uniqueness and no NULLs. Other options contradict these rules.
  3. Final Answer:

    It uniquely identifies each row and cannot contain NULL values. -> Option B
  4. Quick Check:

    PRIMARY KEY = unique + no NULL [OK]
Hint: Primary key = unique + no NULL values [OK]
Common Mistakes:
  • Thinking primary keys allow NULLs
  • Confusing primary key with unique constraint
  • Assuming primary key allows duplicates
2. Which SQL statement correctly defines a column id as a primary key in a table?
easy
A. CREATE TABLE users (id INT, name VARCHAR(50) PRIMARY KEY);
B. CREATE TABLE users (id INT UNIQUE, name VARCHAR(50));
C. CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50));
D. CREATE TABLE users (id INT NOT NULL, name VARCHAR(50));

Solution

  1. Step 1: Identify correct PRIMARY KEY syntax

    The correct syntax to define a primary key inline is column_name data_type PRIMARY KEY.
  2. Step 2: Check each option

    CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50)); uses correct syntax. CREATE TABLE users (id INT UNIQUE, name VARCHAR(50)); uses UNIQUE, not PRIMARY KEY. CREATE TABLE users (id INT NOT NULL, name VARCHAR(50)); only uses NOT NULL. CREATE TABLE users (id INT, name VARCHAR(50) PRIMARY KEY); incorrectly assigns PRIMARY KEY to the wrong column.
  3. Final Answer:

    CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50)); -> Option C
  4. Quick Check:

    PRIMARY KEY syntax = column_name data_type PRIMARY KEY [OK]
Hint: PRIMARY KEY goes right after column type [OK]
Common Mistakes:
  • Using UNIQUE instead of PRIMARY KEY
  • Placing PRIMARY KEY on wrong column
  • Omitting PRIMARY KEY keyword
3. Given the table employees with id as PRIMARY KEY, what happens if you run this SQL?
INSERT INTO employees (id, name) VALUES (1, 'Alice');
INSERT INTO employees (id, name) VALUES (1, 'Bob');
medium
A. The second insert fails due to duplicate primary key.
B. Both rows are inserted successfully.
C. The second insert overwrites the first row.
D. Both inserts fail because primary keys cannot be integers.

Solution

  1. Step 1: Understand PRIMARY KEY uniqueness constraint

    PRIMARY KEY enforces unique values. The first insert adds id=1 successfully.
  2. Step 2: Analyze second insert with duplicate id

    The second insert tries to add id=1 again, violating uniqueness, causing an error.
  3. Final Answer:

    The second insert fails due to duplicate primary key. -> Option A
  4. Quick Check:

    Duplicate PRIMARY KEY value causes insert failure [OK]
Hint: Duplicate primary keys cause insert errors [OK]
Common Mistakes:
  • Assuming duplicates are allowed in primary key
  • Thinking second insert overwrites first
  • Believing primary keys cannot be integers
4. You have this table definition:
CREATE TABLE products (
  product_id INT UNIQUE,
  name VARCHAR(100)
);

Which problem will occur if you try to insert two rows with product_id as NULL?
medium
A. Both rows insert successfully because UNIQUE allows multiple NULLs.
B. The second insert fails because UNIQUE does not allow duplicate NULLs.
C. Syntax error because NULL is not allowed in UNIQUE columns.
D. Both inserts fail because product_id is not a PRIMARY KEY.

Solution

  1. Step 1: Understand UNIQUE constraint with NULLs

    UNIQUE allows only one NULL in some databases, but standard SQL allows multiple NULLs because NULL means unknown.
  2. Step 2: Apply to given inserts

    In most SQL systems, inserting multiple rows with NULL in a UNIQUE column succeeds because NULLs are not considered equal.
  3. Final Answer:

    Both rows insert successfully because UNIQUE allows multiple NULLs. -> Option A
  4. Quick Check:

    UNIQUE allows multiple NULLs in most SQL [OK]
Hint: UNIQUE allows multiple NULLs, PRIMARY KEY does not [OK]
Common Mistakes:
  • Assuming UNIQUE disallows multiple NULLs
  • Confusing UNIQUE with PRIMARY KEY NULL rules
  • Expecting syntax error on NULL in UNIQUE
5. You want to create a table orders where each order has a unique order_id and a unique tracking_number that can be NULL. Which SQL definition is correct?
hard
A. CREATE TABLE orders (order_id INT UNIQUE, tracking_number VARCHAR(20) PRIMARY KEY);
B. CREATE TABLE orders (order_id INT, tracking_number VARCHAR(20) UNIQUE PRIMARY KEY);
C. CREATE TABLE orders (order_id INT PRIMARY KEY UNIQUE, tracking_number VARCHAR(20) NOT NULL UNIQUE);
D. CREATE TABLE orders (order_id INT PRIMARY KEY, tracking_number VARCHAR(20) UNIQUE);

Solution

  1. Step 1: Define order_id as PRIMARY KEY

    order_id must be unique and not NULL, so PRIMARY KEY is appropriate.
  2. Step 2: Define tracking_number as UNIQUE and nullable

    tracking_number should be unique but can be NULL, so UNIQUE constraint without NOT NULL is correct.
  3. Step 3: Evaluate options

    CREATE TABLE orders (order_id INT PRIMARY KEY, tracking_number VARCHAR(20) UNIQUE); matches requirements. CREATE TABLE orders (order_id INT UNIQUE, tracking_number VARCHAR(20) PRIMARY KEY); wrongly assigns PRIMARY KEY to tracking_number. CREATE TABLE orders (order_id INT PRIMARY KEY UNIQUE, tracking_number VARCHAR(20) NOT NULL UNIQUE); makes tracking_number NOT NULL, disallowing NULLs. CREATE TABLE orders (order_id INT, tracking_number VARCHAR(20) UNIQUE PRIMARY KEY); has invalid syntax combining UNIQUE and PRIMARY KEY on tracking_number.
  4. Final Answer:

    CREATE TABLE orders (order_id INT PRIMARY KEY, tracking_number VARCHAR(20) UNIQUE); -> Option D
  5. Quick Check:

    PRIMARY KEY unique + NOT NULL, UNIQUE allows NULL [OK]
Hint: PRIMARY KEY = unique+not null; UNIQUE allows NULL [OK]
Common Mistakes:
  • Making UNIQUE column NOT NULL when NULLs allowed
  • Assigning PRIMARY KEY to wrong column
  • Combining UNIQUE and PRIMARY KEY on same column incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard