Column definitions and constraints in MySQL - Time & Space Complexity
When we create or change a table, we define columns and rules for data. Understanding how this affects time helps us know how fast the database works when adding or checking data.
We want to see how the time to add or check data grows as the table gets bigger.
Analyze the time complexity of the following code snippet.
CREATE TABLE Users (
id INT PRIMARY KEY,
username VARCHAR(50) UNIQUE,
email VARCHAR(100) NOT NULL,
age INT CHECK (age >= 18)
);
INSERT INTO Users (id, username, email, age) VALUES (1, 'alice', 'alice@example.com', 25);
This code creates a table with rules for each column and inserts one row, checking those rules.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking constraints like uniqueness and validity when inserting data.
- How many times: For each insert, the database performs index lookups to check PRIMARY KEY and UNIQUE constraints (O(log n) time).
As the table grows, checking constraints like UNIQUE or PRIMARY KEY takes more time because the database must ensure no duplicates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3 checks |
| 100 | About 7 checks |
| 1000 | About 10 checks |
Pattern observation: The number of checks grows logarithmically with the number of rows.
Time Complexity: O(log n)
This means the time to check constraints grows logarithmically as the table gets bigger.
[X] Wrong: "Checking constraints always takes the same time no matter how big the table is."
[OK] Correct: The database often needs to search indexes over existing data to ensure rules are followed, so more data means more work.
Knowing how constraints affect time helps you explain database behavior clearly. It shows you understand how data rules impact performance in real projects.
"What if we added an index on the username column? How would the time complexity change when checking uniqueness?"
Practice
Solution
Step 1: Understand the purpose of
TheNOT NULLNOT NULLconstraint prevents a column from having NULL values, meaning it must always have data.Step 2: Compare with other constraints
UNIQUEallows NULLs but no duplicates,PRIMARY KEYimpliesNOT NULLand uniqueness, andDEFAULTsets a default value but does not prevent NULL.Final Answer:
NOT NULL-> Option AQuick Check:
Prevent empty values =NOT NULL[OK]
- Confusing UNIQUE with NOT NULL
- Thinking DEFAULT prevents NULL
- Assuming PRIMARY KEY is only for uniqueness
id as an auto-incrementing primary key in MySQL?Solution
Step 1: Recall correct column definition order
In MySQL, the correct syntax places the data type first, then constraints likePRIMARY KEYandAUTO_INCREMENT.Step 2: Validate each option's syntax
id INT PRIMARY KEY AUTO_INCREMENTfollows the correct order:id INT PRIMARY KEY AUTO_INCREMENT. Others have incorrect order or missing keywords.Final Answer:
id INT PRIMARY KEY AUTO_INCREMENT-> Option CQuick Check:
Data type first, then constraints [OK]
- Placing AUTO_INCREMENT before data type
- Using PRIMARY instead of PRIMARY KEY
- Mixing order of keywords
CREATE TABLE users ( user_id INT PRIMARY KEY, email VARCHAR(100) UNIQUE NOT NULL, age INT DEFAULT 18 );
What will happen if you try to insert:
INSERT INTO users (user_id, email) VALUES (1, NULL);
Solution
Step 1: Check the email column constraints
Email is defined asUNIQUE NOT NULL, so it cannot be NULL.Step 2: Analyze the insert statement
The insert tries to set email to NULL, violating theNOT NULLconstraint, causing an error.Final Answer:
Insert fails due to NOT NULL constraint on email -> Option AQuick Check:
NOT NULL rejects NULL values [OK]
- Assuming DEFAULT applies when value is NULL
- Confusing UNIQUE with NOT NULL
- Thinking NULL is allowed if UNIQUE
CREATE TABLE products ( product_id INT PRIMARY KEY, name VARCHAR(50) UNIQUE, price DECIMAL(5,2) NOT NULL DEFAULT 0.00 );
Which of the following statements will cause an error?
Solution
Step 1: Check constraints on each insert
INSERT INTO products (product_id, name, price) VALUES (1, 'Pen', 1.50); inserts all required fields correctly. INSERT INTO products (product_id, name) VALUES (2, 'Book'); omits price but uses default 0.00, allowed. INSERT INTO products (product_id, price) VALUES (3, 2.00); omits name, which is nullable, allowed.Step 2: Identify duplicate primary key error
INSERT INTO products (product_id, name, price) VALUES (1, 'Pencil', 0.50); tries to insertproduct_id1 again, violating thePRIMARY KEYuniqueness constraint, causing an error.Final Answer:
INSERT INTO products (product_id, name, price) VALUES (1, 'Pencil', 0.50); -> Option DQuick Check:
PRIMARY KEY must be unique [OK]
- Assuming UNIQUE allows duplicates
- Forgetting DEFAULT applies only if column omitted
- Ignoring PRIMARY KEY uniqueness
orders where order_id is a primary key, customer_email must be unique and not null, and order_date defaults to the current date if not provided. Which of the following column definitions is correct?Solution
Step 1: Check constraints on
The column must be bothcustomer_emailUNIQUEandNOT NULL. Using eitherUNIQUE NOT NULLorNOT NULL UNIQUEis valid in MySQL.Step 2: Verify default for
MySQL supportsorder_dateDEFAULT CURRENT_DATEfor DATE columns.NOW()andCURRENT_TIMESTAMPreturn datetime, not date, causing errors.CURDATE()is a function and cannot be used directly as default.Step 3: Confirm full correctness
order_id INT PRIMARY KEY, customer_email VARCHAR(100) UNIQUE NOT NULL, order_date DATE DEFAULT CURRENT_DATEuses correct syntax for all constraints and default value.Final Answer:
order_id INT PRIMARY KEY, customer_email VARCHAR(100) UNIQUE NOT NULL, order_date DATE DEFAULT CURRENT_DATE -> Option BQuick Check:
Use CURRENT_DATE for DATE default [OK]
- Using NOW() or CURRENT_TIMESTAMP for DATE default
- Trying to use functions like CURDATE() as default
- Confusing UNIQUE and NOT NULL order
Ready to prove it?
Pass the test and this pattern moves unknown
