SQL Data Types
Every column in a SQL table must have a data type that defines what kind of data it can store.
💡 Choosing the right data type is crucial for data integrity, storage efficiency, and query performance.
String Types
CREATE TABLE products (
sku CHAR(10), -- Fixed length (always 10 chars)
name VARCHAR(255), -- Variable length (up to 255)
description TEXT -- Very large text
);
| Type | Max Size | Best For |
|---|---|---|
CHAR(n) | n characters | Fixed codes, IDs |
VARCHAR(n) | n characters | Names, emails, addresses |
TEXT | ~65KB | Articles, descriptions |
Numeric Types
CREATE TABLE inventory (
price DECIMAL(10,2), -- Exact: 10 digits, 2 after decimal
quantity INTEGER, -- Whole numbers
rating SMALLINT -- Small integer
);
| Type | Storage | Range | Use Case |
|---|---|---|---|
INTEGER | 4 bytes | ±2.1 billion | Counts, IDs |
SMALLINT | 2 bytes | ±32,767 | Small numbers |
BIGINT | 8 bytes | Very large | Large counters |
DECIMAL(p,s) | Variable | Exact precision | Money |
FLOAT | 4 bytes | Approximate | Scientific |
BOOLEAN | 1 byte | TRUE/FALSE | Flags |
Date and Time Types
CREATE TABLE events (
event_date DATE, -- 2024-01-15
event_time TIME, -- 14:30:00
event_timestamp TIMESTAMP -- 2024-01-15 14:30:00
);
| Type | Format | Example |
|---|---|---|
DATE | YYYY-MM-DD | 2024-01-15 |
TIME | HH:MM:SS | 14:30:00 |
TIMESTAMP | YYYY-MM-DD HH:MM:SS | 2024-01-15 14:30:00 |
⚠️ Always use the smallest data type that can hold your data. A VARCHAR(10) is better than VARCHAR(1000) if you only need 10 characters.
✅ Key Takeaways
- Each column needs a data type that defines what it can store
- Use VARCHAR for variable text, CHAR for fixed-length text
- Use DECIMAL for exact values like money, FLOAT for approximations
- Choose the smallest type that fits your data
- BOOLEAN is great for true/false values