Data types in SQL define the type of data that can be stored in a column or variable. They ensure data integrity by enforcing constraints on the kind of values that can be inserted into a table.
Key Points
Purpose:
Defines the format and limitations of data in a database.
Helps in optimizing storage and retrieval of data.
Categories:
SQL data types are broadly classified into the following categories:Numeric Types: For numbers.
String (Character) Types: For text data.
Date/Time Types: For dates and times.
Binary Types: For binary data like images or files.
Special Types: For specific database systems (e.g., JSON, XML).
Variations Across Databases:
While SQL has standard data types, the implementation may vary between databases like MySQL, PostgreSQL, SQL Server, etc.
Categories of SQL Data Types
1. Numeric Data Types
Used for storing numbers.
Type | Description | Example |
INT | Integer (whole number) | 10 , -20 |
BIGINT | Large integer | 9223372036854775807 |
SMALLINT | Small integer | 32767 |
DECIMAL(p, s) | Fixed-point number with precision | DECIMAL(10, 2) → 123.45 |
NUMERIC(p, s) | Synonym for DECIMAL | NUMERIC(5, 3) → 12.345 |
FLOAT | Approximate floating-point number | 3.14 , -0.001 |
REAL | Single-precision floating-point | 2.718 |
BIT | Binary (0 or 1) | 0 , 1 |
2. String (Character) Data Types
Used for text or character data.
Type | Description | Example |
CHAR(n) | Fixed-length string | CHAR(5) → 'abc ' |
VARCHAR(n) | Variable-length string | VARCHAR(10) → 'hello' |
TEXT | Large variable-length string | 'This is a long text.' |
NCHAR(n) | Fixed-length Unicode string | NCHAR(5) → 'abcd ' |
NVARCHAR(n) | Variable-length Unicode string | NVARCHAR(10) → 'world' |
CLOB | Character large object | 'Large text data' |
3. Date and Time Data Types
Used for storing date, time, and timestamp values.
Type | Description | Example |
DATE | Date (YYYY-MM-DD) | 2024-12-21 |
TIME | Time (HH:MI:SS) | 13:45:30 |
TIMESTAMP | Date and time | 2024-12-21 13:45:30 |
DATETIME | Synonym for TIMESTAMP in some DBs | 2024-12-21 13:45:30 |
INTERVAL | Time interval | INTERVAL '5 DAYS' |
4. Binary Data Types
Used for storing binary data like images or files.
Type | Description | Example |
BINARY(n) | Fixed-length binary data | BINARY(5) |
VARBINARY(n) | Variable-length binary data | VARBINARY(10) |
BLOB | Binary large object | Binary image data |
5. Special Data Types
Used for non-standard data or database-specific needs.
Type | Description | Example |
JSON | JSON-formatted data | '{"key": "value"}' |
XML | XML-formatted data | <tag>value</tag> |
ENUM | Enumerated list of values | 'small', 'medium', 'large' |
GEOMETRY | Spatial data | POINT(10 20) |
Choosing the Right Data Type
Use the smallest data type that can accommodate your data to optimize storage.
Use
CHAR
for fixed-length data andVARCHAR
for variable-length data.Use
DECIMAL
orNUMERIC
for precise calculations like monetary data.Use binary types for storing media or file data.