String types (VARCHAR, CHAR, TEXT) in MySQL - Time & Space Complexity
When working with string types in MySQL, it's important to understand how the size of the data affects the time it takes to store and retrieve it.
We want to see how the time needed grows as the string length or number of rows increases.
Analyze the time complexity of inserting and selecting data using different string types.
CREATE TABLE example (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
code CHAR(10),
description TEXT
);
INSERT INTO example (name, code, description) VALUES
('Alice', 'A123456789', 'Short description'),
('Bob', 'B987654321', 'Longer description text here...');
SELECT * FROM example WHERE name = 'Alice';
This code creates a table with VARCHAR, CHAR, and TEXT columns, inserts some rows, and selects data by name.
Look at what repeats when handling string data in this example.
- Primary operation: Reading or writing string data for each row.
- How many times: Once per row inserted or selected, repeated for all rows in the table.
As the number of rows grows, the total time to insert or select all rows grows roughly in direct proportion.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | 10 string reads/writes |
| 100 | 100 string reads/writes |
| 1000 | 1000 string reads/writes |
Pattern observation: The time grows linearly with the number of rows because each row's string data is handled separately.
Time Complexity: O(n)
This means the time to process string data grows directly with the number of rows involved.
[X] Wrong: "String types like TEXT always take the same time regardless of length."
[OK] Correct: Longer strings take more time to read and write, so time depends on string length and number of rows.
Understanding how string data size affects query time helps you explain database performance clearly and confidently.
"What if we changed the VARCHAR size limit from 100 to 1000? How would the time complexity change when inserting or selecting data?"