Data types in SQL are fundamental in defining the kind of data that can be stored in a database. They ensure data consistency, optimize storage, and enhance database performance.
A data type defines the type of value that a column can store in an SQL table. For instance:
SQL data types are broadly categorized into the following:
Used for storing text or character-based data.
For storing numbers, integers, and floating-point values.
For storing temporal data.
For binary data such as images or files.
n
characters. If the data is shorter, it is padded with spaces.
CREATE TABLE employees (
name CHAR(10),
email VARCHAR(50)
);
Output: Inserting “John” into name
will pad it to “John “.
p
total digits and s
digits after the decimal point.
CREATE TABLE sales (
sale_id INT,
sale_amount DECIMAL(10, 2)
);
YYYY-MM-DD
.YYYY-MM-DD HH:MM:SS
.
CREATE TABLE events (
event_name VARCHAR(100),
event_date DATE
);
Output: Storing 2024-11-12
in event_date
.
Binary types store data in binary format, suitable for images or files.
CREATE TABLE files (
file_id INT,
file_data BLOB
);
CREATE TABLE products (
category ENUM('Electronics', 'Clothing', 'Furniture'),
specifications JSON
);
Choosing the correct data type involves:
DECIMAL
for financial data.VARCHAR.
Creating a Table with Varied Data Types
CREATE TABLE student_records (
student_id INT,
student_name VARCHAR(50),
birth_date DATE,
GPA DECIMAL(3, 2),
profile_picture BLOB
);
INSERT INTO student_records
VALUES (1, 'Alice', '2001-03-10', 3.75, NULL);
Output: A table with the specified types, ensuring the correct format for each column.
CHAR
for known fixed-size strings.TEXT
or BLOB
unless necessary.p
and s
for DECIMAL
.p
) is the total number of digits.s
) is the number of digits after the decimal.Convert between data types using:
SELECT CAST(123.45 AS INT);
Understanding SQL data types is essential for efficient database design. Proper selection ensures data integrity, reduces storage costs, and optimizes performance. Happy Coding!❤️