Data Types (VARCHAR)
Overview
When defining a column in a table, you must strictly declare its Data Type. This tells the database exactly how many bytes to allocate on the physical hard drive, and allows it to optimize indexing. The most heavily tested concept is the difference between CHAR (Fixed-length strings) and VARCHAR (Variable-length strings), as well as precise numerical types like DECIMAL vs FLOAT.
Syntax
-- Standard SQL Data Types
-- 1. STRINGS
VARCHAR(50) -- Variable length (Up to 50 chars). Only uses the bytes it needs!
CHAR(10) -- Fixed length (Always 10 chars). Pads empty space with spaces.
TEXT -- Unlimited length (Great for blog posts, but slower to search).
-- 2. NUMBERS
INT -- Standard whole number (Usually 4 bytes, up to ~2 billion).
BIGINT -- Massive whole numbers (Required for Twitter/Snowflake IDs).
DECIMAL(10,2) -- Exact precision math! (Total 10 digits, 2 are after the decimal).
FLOAT / REAL -- Approximate math (Extremely fast, but suffers from rounding errors).
-- 3. DATES & BOOLEANS
DATE -- '2026-12-31'
TIMESTAMP -- '2026-12-31 23:59:59' (Usually timezone aware)
BOOLEAN -- TRUE / FALSE (Under the hood, often stored as TINYINT 1 or 0)Common Pitfalls
- Using
FLOATorREALfor financial currency. Floats are stored in binary, which cannot perfectly represent fractions like 0.1.0.1 + 0.2might equal0.300000000004in a Float column, destroying your accounting. ALWAYS useDECIMAL(10,2)(or store as integer cents) for money. - Using
CHAR(50)for usernames.CHARalways reserves the exact space on disk. If the username is 'Bob' (3 chars), the database fills the remaining 47 characters with invisible blank spaces, wasting massive amounts of disk space. UseVARCHAR(50).
Interview Questions
CHAR(n) data type instead of VARCHAR(n)?When you know with 100% certainty that every single entry will be exactly that length. For example: A 2-letter US State Code (CHAR(2)), a 32-character MD5 hash (CHAR(32)), or a UUID. In these cases, CHAR is slightly faster because it skips the variable-length calculation overhead.
Real-World Example
Defining a highly optimized e-commerce product schema.
CREATE TABLE products (
sku CHAR(8), -- Every SKU is exactly 8 characters
product_name VARCHAR(150), -- Names vary wildly in length
price DECIMAL(8, 2), -- Max price: 999999.99 (Exact math for money)
weight_kg FLOAT, -- Approximate math is fine for shipping weights
created_at TIMESTAMP -- Tracks the exact microsecond it was added
);Check Your Knowledge
Test your understanding of Data Types (VARCHAR) with these quick questions.