🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
Search courses…
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

SQL Data Types

SQL FundamentalsDatabase Basics🟢 Free Lesson

Advertisement

SQL Fundamentals

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 type is crucial for integrity, performance, and storage efficiency.

  • String Types — Text data from short codes to long articles
  • Numeric Types — Integers, decimals, and floating-point numbers
  • Date/Time Types — Dates, times, and timestamps

The right data type saves space, enforces rules, and speeds up queries.

Data Type Categories

SQL Data TypesStringNumericDate/TimeBinaryBooleanCHARVARCHARTEXTCLOBINTEGERSMALLINTBIGINTDECIMALFLOATDOUBLEDATETIMETIMESTAMPDATETIMEBINARYVARBINARYBLOBBOOLEANBIT

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
    notes VARCHAR(500)          -- Variable length with limit
);

String Type Comparison

TypeMax SizeStorageBest ForExample
CHAR(n)n charactersn bytesFixed codes, IDsUS state codes: 'CA', 'NY'
VARCHAR(n)n charactersActual length + 1-2 bytesNames, emails'Alice Johnson'
TEXT~65KBActual length + 1-2 bytesArticles, descriptionsBlog content
CLOBVery largeVariableDocument storageFull articles

CHAR vs VARCHAR

CHAR(10) - Fixed LengthCA 10 bytesNY 10 bytesAlways 10 bytes (padded)VARCHAR(10) - VariableCA2+1 bytesCalifornia10+1Only uses what's needed

Unicode String Types

-- For international text (Chinese, Arabic, emojis, etc.)
CREATE TABLE international (
    name NVARCHAR(100),        -- Unicode variable length
    description NTEXT,         -- Unicode large text
    -- MySQL equivalent:
    name_utf8 VARCHAR(100) CHARACTER SET utf8mb4
);

Numeric Types

CREATE TABLE inventory (
    price DECIMAL(10,2),       -- Exact: 10 digits, 2 after decimal
    quantity INTEGER,           -- Whole numbers
    rating SMALLINT,            -- Small integer
    product_code BIGINT,        -- Large integer
    weight FLOAT,               -- Approximate decimal
    dimensions REAL             -- Single precision float
);

Integer Types

TypeStorageMin ValueMax ValueUse Case
SMALLINT2 bytes-32,76832,767Age, quantity, status codes
INTEGER4 bytes-2,147,483,6482,147,483,647IDs, counts, general numbers
BIGINT8 bytes-9.2 quintillion9.2 quintillionLarge counters, timestamps
SMALLINT2 bytes±32,767INTEGER4 bytes±2.1 billionBIGINT8 bytes±9.2 quintillion

Decimal vs Float

TypePrecisionStorageUse Case
DECIMAL(p,s)ExactVariableMoney, financial data
NUMERIC(p,s)ExactVariableSame as DECIMAL
FLOAT~7 digits4 bytesScientific calculations
REAL~7 digits4 bytesSame as FLOAT
DOUBLE~15 digits8 bytesHigh precision scientific
-- DECIMAL for money (exact precision)
CREATE TABLE transactions (
    id INTEGER PRIMARY KEY,
    amount DECIMAL(10,2),      -- 10 total digits, 2 after decimal
    tax_rate DECIMAL(5,4),     -- 5 total digits, 4 after decimal
    total DECIMAL(12,2)
);

-- Example values
INSERT INTO transactions VALUES (1, 99.99, 0.0825, 108.24);

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
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
TypeFormatExampleStorage
DATEYYYY-MM-DD2024-01-153 bytes
TIMEHH:MM:SS14:30:003 bytes
TIMESTAMPYYYY-MM-DD HH:MM:SS2024-01-15 14:30:004-8 bytes
DATETIMEYYYY-MM-DD HH:MM:SS2024-01-15 14:30:008 bytes
INTERVALVariesINTERVAL '1' DAY16 bytes
2024-01-15 14:30:45.1234562024Year01Month15Day14Hour30Minute45 - Second123456 - μs

Date Functions

-- Current date and time functions
SELECT CURRENT_DATE;                    -- Today's date
SELECT CURRENT_TIME;                    -- Current time
SELECT CURRENT_TIMESTAMP;               -- Current date and time

-- Date arithmetic
SELECT CURRENT_DATE + INTERVAL '7' DAY;           -- One week from now
SELECT CURRENT_DATE + INTERVAL '1' MONTH;          -- One month from now
SELECT CURRENT_DATE - INTERVAL '3' YEAR;           -- Three years ago

-- Extract components
SELECT EXTRACT(YEAR FROM CURRENT_DATE);            -- 2024
SELECT EXTRACT(MONTH FROM CURRENT_DATE);           -- 1
SELECT EXTRACT(DAY FROM CURRENT_DATE);             -- 15

Boolean Type

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    username TEXT NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    is_verified BOOLEAN DEFAULT FALSE,
    email_verified_at TIMESTAMP
);

-- Query with booleans
SELECT * FROM users WHERE is_active = TRUE;
SELECT * FROM users WHERE is_verified;
SELECT * FROM users WHERE NOT is_verified;

Binary Types

CREATE TABLE files (
    id INTEGER PRIMARY KEY,
    filename TEXT NOT NULL,
    file_data BLOB,              -- Binary Large Object
    file_hash BINARY(32),        -- Fixed length binary (SHA-256)
    thumbnail VARBINARY(10000)   -- Variable length binary
);

Data Type Selection Guide

What type of data?Is it text?YesNoFixed length?YesCHARNoMax len?<255VARCHAR>255TEXTIs itnumbers?YesNoExact?YesRange?SmallINTEGERLargeBIGINTDecimalDECIMALNoFLOAT/DOUBLEDate/Time?YesNeedtime?NoDATEYesTIMESTAMP

Common Mistakes

-- BAD: Using TEXT for everything
CREATE TABLE bad_table (
    age TEXT,           -- Should be SMALLINT
    price TEXT,         -- Should be DECIMAL
    is_active TEXT      -- Should be BOOLEAN
);

-- GOOD: Appropriate data types
CREATE TABLE good_table (
    age SMALLINT CHECK (age >= 0 AND age <= 150),
    price DECIMAL(10,2) CHECK (price >= 0),
    is_active BOOLEAN DEFAULT TRUE
);

Summary

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement