Bird
Raised Fist0
SQLquery~10 mins

PRIMARY KEY constraint in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - PRIMARY KEY constraint
Start Table Creation
↓
Define Columns
↓
Specify PRIMARY KEY Column(s)
↓
Enforce Uniqueness & Not Null
↓
Insert Data
↓
Check for Duplicate or NULL in PK
↓
Accept Row
↓
Table Ready with Unique Rows
↓
End
This flow shows how a PRIMARY KEY is defined during table creation and how it enforces uniqueness and no NULLs when inserting data.
Execution Sample
SQL
CREATE TABLE Students (
  ID INT PRIMARY KEY,
  Name VARCHAR(50)
);

INSERT INTO Students VALUES (1, 'Alice');
INSERT INTO Students VALUES (1, 'Bob');
Creates a Students table with ID as PRIMARY KEY, inserts a row, then tries to insert a duplicate ID which causes an error.
Execution Table
StepActionEvaluationResult
1Create table Students with ID as PRIMARY KEYTable schema set with ID unique and NOT NULLTable created successfully
2Insert (1, 'Alice')Check if ID=1 exists and is NOT NULLRow inserted
3Insert (1, 'Bob')Check if ID=1 exists and is NOT NULLError: Duplicate PRIMARY KEY value
4Insert (NULL, 'Charlie')Check if ID=NULL allowedError: PRIMARY KEY cannot be NULL
💡 Insertion stops on duplicate or NULL PRIMARY KEY violation
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4
Students Table Rowsempty[{ID:1, Name:'Alice'}][{ID:1, Name:'Alice'}][{ID:1, Name:'Alice'}]
ID Values Presentempty[1][1][1]
Key Moments - 2 Insights
Why can't we insert two rows with the same PRIMARY KEY value?
Because the PRIMARY KEY constraint enforces uniqueness, as shown in execution_table step 3 where inserting a duplicate ID causes an error.
Why is NULL not allowed in a PRIMARY KEY column?
PRIMARY KEY columns must uniquely identify rows, and NULL means unknown, so it is disallowed. See execution_table step 4 where inserting NULL ID causes an error.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 3 when inserting (1, 'Bob')?
ARow is inserted successfully
BRow is inserted but with NULL ID
CError due to duplicate PRIMARY KEY
DTable schema changes
💡 Hint
Check the 'Result' column in execution_table row 3
According to variable_tracker, how many rows are in the Students table after step 2?
A0
B1
C2
DNULL
💡 Hint
Look at 'Students Table Rows' after step 2 in variable_tracker
If we try to insert a row with ID=NULL, what does the PRIMARY KEY constraint do according to execution_table?
ARejects insertion with error
BConverts NULL to 0
CAllows insertion
DIgnores the PRIMARY KEY constraint
💡 Hint
See step 4 in execution_table for NULL ID insertion
Concept Snapshot
PRIMARY KEY constraint:
- Uniquely identifies each row
- Enforces NOT NULL and uniqueness
- Defined during table creation
- Duplicate or NULL values cause insertion errors
- Essential for data integrity
Full Transcript
The PRIMARY KEY constraint is used in SQL to uniquely identify each row in a table. When creating a table, you specify one or more columns as the PRIMARY KEY. This constraint ensures that no two rows can have the same value in the PRIMARY KEY column(s), and that these values cannot be NULL. During data insertion, the database checks if the PRIMARY KEY value already exists or is NULL. If so, it rejects the insertion with an error. This maintains data integrity by preventing duplicate or missing identifiers. For example, in the Students table, the ID column is the PRIMARY KEY. Inserting a row with ID=1 succeeds the first time but fails if attempted again or if NULL is used. This behavior is critical for reliable database operations.

Practice

(1/5)
1. What is the main purpose of a PRIMARY KEY in a database table?
easy
A. To speed up database backups
B. To uniquely identify each row and prevent null values
C. To store large text data
D. To allow duplicate values in a column

Solution

  1. Step 1: Understand the role of PRIMARY KEY

    A PRIMARY KEY uniquely identifies each row and does not allow nulls, ensuring data integrity.
  2. Step 2: Compare options with PRIMARY KEY purpose

    Options A, B, and C do not describe uniqueness or null restriction, which are key features of PRIMARY KEY.
  3. Final Answer:

    To uniquely identify each row and prevent null values -> Option B
  4. Quick Check:

    PRIMARY KEY = unique + not null [OK]
Hint: PRIMARY KEY means unique and no nulls [OK]
Common Mistakes:
  • Thinking PRIMARY KEY allows duplicates
  • Confusing PRIMARY KEY with foreign key
  • Assuming PRIMARY KEY stores large text
2. Which of the following is the correct syntax to define a PRIMARY KEY on the id column during table creation?
easy
A. CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50));
B. CREATE TABLE users (id INT, name VARCHAR(50) PRIMARY KEY);
C. CREATE TABLE users (id INT, PRIMARY KEY name);
D. CREATE TABLE users (id INT, name VARCHAR(50), PRIMARY KEY id);

Solution

  1. Step 1: Review correct PRIMARY KEY syntax inline

    PRIMARY KEY is declared after the column type, like id INT PRIMARY KEY.
  2. Step 2: Check each option's syntax

    CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(50)); correctly places PRIMARY KEY after id INT. Options B, C, and D have syntax errors or misplaced keywords.
  3. Final Answer:

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

    PRIMARY KEY follows column type inline [OK]
Hint: PRIMARY KEY goes right after column type [OK]
Common Mistakes:
  • Placing PRIMARY KEY after wrong column
  • Using PRIMARY KEY without parentheses for multiple columns
  • Syntax errors with misplaced keywords
3. Given the table creation:
CREATE TABLE orders (
order_id INT,
product_id INT,
PRIMARY KEY (order_id, product_id)
);

What will happen if you try to insert two rows with the same order_id but different product_id?
medium
A. Only the second row will be inserted
B. Only the first row will be inserted; second causes error
C. Both rows cause a syntax error
D. Both rows will be inserted successfully

Solution

  1. Step 1: Understand composite PRIMARY KEY behavior

    The PRIMARY KEY is on both order_id and product_id together, so uniqueness is checked on the pair.
  2. Step 2: Analyze insertion of rows with same order_id but different product_id

    Since product_id differs, the pair is unique, so both rows can be inserted without error.
  3. Final Answer:

    Both rows will be inserted successfully -> Option D
  4. Quick Check:

    Composite PRIMARY KEY = unique pairs [OK]
Hint: Composite key means unique pairs, not single columns [OK]
Common Mistakes:
  • Assuming order_id alone must be unique
  • Thinking composite key allows duplicates in all columns
  • Confusing syntax error with constraint violation
4. Consider this table creation:
CREATE TABLE employees (
emp_id INT,
email VARCHAR(100),
PRIMARY KEY emp_id
);

What is wrong with this statement?
medium
A. PRIMARY KEY must be declared with parentheses around column name
B. PRIMARY KEY cannot be on emp_id column
C. email column must be PRIMARY KEY instead
D. Table cannot have a PRIMARY KEY

Solution

  1. Step 1: Check syntax for table-level PRIMARY KEY

    When declaring PRIMARY KEY separately, column names must be inside parentheses, like PRIMARY KEY (emp_id).
  2. Step 2: Identify error in given statement

    The statement misses parentheses around emp_id, causing syntax error.
  3. Final Answer:

    PRIMARY KEY must be declared with parentheses around column name -> Option A
  4. Quick Check:

    Table-level PRIMARY KEY needs parentheses [OK]
Hint: Table-level PRIMARY KEY needs parentheses [OK]
Common Mistakes:
  • Omitting parentheses in table-level PRIMARY KEY
  • Thinking PRIMARY KEY can't be on emp_id
  • Confusing column-level and table-level syntax
5. You want to create a table students where each student is uniquely identified by a combination of student_id and campus_id. Which of the following statements correctly enforces this using a PRIMARY KEY?
hard
A. CREATE TABLE students (student_id INT PRIMARY KEY, campus_id INT PRIMARY KEY);
B. CREATE TABLE students (student_id INT, campus_id INT, PRIMARY KEY student_id, campus_id);
C. CREATE TABLE students (student_id INT, campus_id INT, PRIMARY KEY (student_id, campus_id));
D. CREATE TABLE students (student_id INT, campus_id INT, UNIQUE (student_id, campus_id));

Solution

  1. Step 1: Understand composite PRIMARY KEY requirement

    To uniquely identify rows by two columns, a composite PRIMARY KEY on both columns is needed.
  2. Step 2: Evaluate each option's correctness

    CREATE TABLE students (student_id INT, campus_id INT, PRIMARY KEY (student_id, campus_id)); correctly defines a composite PRIMARY KEY. CREATE TABLE students (student_id INT PRIMARY KEY, campus_id INT PRIMARY KEY); tries to assign two PRIMARY KEYs, which is invalid. CREATE TABLE students (student_id INT, campus_id INT, PRIMARY KEY student_id, campus_id); has syntax errors. CREATE TABLE students (student_id INT, campus_id INT, UNIQUE (student_id, campus_id)); uses UNIQUE but not PRIMARY KEY.
  3. Final Answer:

    CREATE TABLE students (student_id INT, campus_id INT, PRIMARY KEY (student_id, campus_id)); -> Option C
  4. Quick Check:

    Composite PRIMARY KEY uses parentheses around columns [OK]
Hint: Use parentheses for composite PRIMARY KEY columns [OK]
Common Mistakes:
  • Trying multiple PRIMARY KEYs on separate columns
  • Missing parentheses in PRIMARY KEY declaration
  • Using UNIQUE instead of PRIMARY KEY for uniqueness
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