In SQL, data types specify the kind of data that can be stored within a column. Choosing the correct data type is crucial for data integrity, storage efficiency, and query performance. This lesson covers common data types and their subtypes used in SQL databases, along with their value ranges.
Numeric data types are used to store numerical values.
INT
or INTEGER
: Typically a 4-byte integer.SMALLINT
: Typically a 2-byte integer.BIGINT
: Typically an 8-byte integer.TINYINT
: Typically a 1-byte integer.TINYINT
: -128 to 127 (signed) or 0 to 255 (unsigned)SMALLINT
: -32,768 to 32,767INT
: -2,147,483,648 to 2,147,483,647BIGINT
: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807DECIMAL(10, 2)
can store numbers with 10 total digits, 2 of which are after the decimal point.FLOAT
: Single-precision floating-point number.DOUBLE
/ DOUBLE PRECISION
: Double-precision floating-point number.REAL
: A synonym for FLOAT
in some databases.Character data types are used to store text.
CHAR(10)
stores strings of exactly 10 characters.VARCHAR(255)
stores strings up to 255 characters long.VARCHAR
.Date and time data types are used to store temporal values.
TIMESTAMP
often has special behavior related to time zones and automatic updates.It's important to understand the concept of NULL
in SQL. NULL
represents a missing or unknown value. A column can be defined to allow or disallow NULL
values. Unlike other data types, NULL
is not a data type itself, but rather a property of a column. It's crucial to handle NULL
values properly in queries to avoid unexpected results. Comparisons with NULL
should be done using IS NULL
or IS NOT NULL
.
VARCHAR
instead of CHAR
unless you need fixed-length strings.DECIMAL
for exact numeric values, especially when dealing with currency.By understanding the available data types and their characteristics, you can design databases that are efficient, reliable, and easy to maintain.
Key Takeaways from this Lesson:
INTEGER
, DECIMAL
, and FLOAT
are used for storing numerical data, each with different characteristics regarding precision and range.CHAR
, VARCHAR
, and TEXT
are used for storing text data, with varying length constraints and storage implications.DATE
, TIME
, and DATETIME
are used for storing temporal data, with specific formats that vary across database systems.BOOLEAN
, BLOB
, and JSON
provide support for storing boolean values, binary data, and semi-structured data, respectively.NULL
represents a missing or unknown value and is not a data type itself. It's crucial to handle NULL
values properly in queries.