Data Types in SQL

Data Types in SQL

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

  1. Purpose:

    • Defines the format and limitations of data in a database.

    • Helps in optimizing storage and retrieval of data.

  2. 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).

  3. 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.

TypeDescriptionExample
INTInteger (whole number)10, -20
BIGINTLarge integer9223372036854775807
SMALLINTSmall integer32767
DECIMAL(p, s)Fixed-point number with precisionDECIMAL(10, 2)123.45
NUMERIC(p, s)Synonym for DECIMALNUMERIC(5, 3)12.345
FLOATApproximate floating-point number3.14, -0.001
REALSingle-precision floating-point2.718
BITBinary (0 or 1)0, 1

2. String (Character) Data Types

Used for text or character data.

TypeDescriptionExample
CHAR(n)Fixed-length stringCHAR(5)'abc '
VARCHAR(n)Variable-length stringVARCHAR(10)'hello'
TEXTLarge variable-length string'This is a long text.'
NCHAR(n)Fixed-length Unicode stringNCHAR(5)'abcd '
NVARCHAR(n)Variable-length Unicode stringNVARCHAR(10)'world'
CLOBCharacter large object'Large text data'

3. Date and Time Data Types

Used for storing date, time, and timestamp values.

TypeDescriptionExample
DATEDate (YYYY-MM-DD)2024-12-21
TIMETime (HH:MI:SS)13:45:30
TIMESTAMPDate and time2024-12-21 13:45:30
DATETIMESynonym for TIMESTAMP in some DBs2024-12-21 13:45:30
INTERVALTime intervalINTERVAL '5 DAYS'

4. Binary Data Types

Used for storing binary data like images or files.

TypeDescriptionExample
BINARY(n)Fixed-length binary dataBINARY(5)
VARBINARY(n)Variable-length binary dataVARBINARY(10)
BLOBBinary large objectBinary image data

5. Special Data Types

Used for non-standard data or database-specific needs.

TypeDescriptionExample
JSONJSON-formatted data'{"key": "value"}'
XMLXML-formatted data<tag>value</tag>
ENUMEnumerated list of values'small', 'medium', 'large'
GEOMETRYSpatial dataPOINT(10 20)

Choosing the Right Data Type

  1. Use the smallest data type that can accommodate your data to optimize storage.

  2. Use CHAR for fixed-length data and VARCHAR for variable-length data.

  3. Use DECIMAL or NUMERIC for precise calculations like monetary data.

  4. Use binary types for storing media or file data.