SQL Tutorial
SQL data types are used to define the type of data that can be stored in a database table column. The specific data types supported can vary between different relational database management systems (RDBMS), but there are several common ones:
INTEGER: This is used to store whole numbers without fractional components, such as 3, 10, -100, etc.
DECIMAL or NUMERIC: These are used for precision fixed-point number data.
FLOAT or REAL: These are used for floating point number data. They are typically used for scientific calculations where the precision required can vary.
CHAR: This is a fixed-length string data type. For example, CHAR(5) will always store 5 characters. If you store 'abc' it will be stored as 'abc ', with two trailing spaces.
VARCHAR: This is a variable-length string data type. It can store up to a certain maximum number of characters, and no space is used to pad shorter strings. For example, VARCHAR(5) can store 'abc' as 'abc' without trailing spaces.
BOOLEAN: This data type stores true or false values.
DATE: This is used for date values in the format 'YYYY-MM-DD'.
TIME: This is used for time values in the format 'HH:MI:SS'.
DATETIME: This is used for values that contain both date and time.
BLOB or BYTEA: These are used for storing binary data, such as images or files.
TEXT: This is used for long string data, and can be significantly larger than the VARCHAR type can accommodate.
Each RDBMS may have its own additional data types, or may use slightly different names for the above data types. For example, in SQL Server, you'd use INT instead of INTEGER, and NVARCHAR instead of VARCHAR.
It's also important to understand the range of each data type, and how much storage space they use, as this can affect both the performance of your SQL queries and the amount of disk space your database uses. Always consult the documentation for your specific RDBMS to understand its data types.
Numeric Data Types in SQL:
CREATE TABLE ExampleTable ( IntegerColumn INT, DecimalColumn DECIMAL(10,2), FloatColumn FLOAT );
Character Data Types in SQL:
CREATE TABLE ExampleTable ( CharColumn CHAR(10), VarcharColumn VARCHAR(255), TextColumn TEXT );
Date and Time Data Types in SQL:
CREATE TABLE ExampleTable ( DateColumn DATE, TimeColumn TIME, DateTimeColumn DATETIME );
Boolean Data Type in SQL:
CREATE TABLE ExampleTable ( BooleanColumn BOOLEAN );
Binary Data Types in SQL:
CREATE TABLE ExampleTable ( BinaryColumn BLOB, VarbinaryColumn VARBINARY(1024) );
VARCHAR vs CHAR in SQL:
CREATE TABLE ExampleTable ( VarcharColumn VARCHAR(255), CharColumn CHAR(10) );
SQL Custom or User-Defined Data Types:
CREATE TYPE Color AS ENUM ('Red', 'Green', 'Blue'); CREATE TABLE Products ( ProductID INT, ProductName VARCHAR(255), ProductColor Color );