SQL (Structured Query Language) allows for various data types, which are crucial in defining the nature of data that can be stored in a database. Choosing the right data type is essential for optimizing storage and ensuring data integrity. Below are three diverse examples showcasing different SQL data types in practical scenarios.
The INTEGER data type is commonly used for storing whole numbers. It is ideal for primary keys, counters, or any numerical fields that do not require decimal precision.
CREATE TABLE Employees (
EmployeeID INTEGER PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INTEGER
);
INSERT INTO Employees (EmployeeID, FirstName, LastName, Age)
VALUES (1, 'John', 'Doe', 30),
(2, 'Jane', 'Smith', 28);
SELECT * FROM Employees;
VARCHAR (Variable Character) allows for the storage of strings of varying lengths. This is particularly useful for text fields, such as names, addresses, or descriptions, where the length can differ significantly.
CREATE TABLE Products (
ProductID INTEGER PRIMARY KEY,
ProductName VARCHAR(100),
Description VARCHAR(255),
Price DECIMAL(10, 2)
);
INSERT INTO Products (ProductID, ProductName, Description, Price)
VALUES (1, 'Laptop', 'High-performance laptop', 999.99),
(2, 'Smartphone', 'Latest model smartphone', 699.99);
SELECT * FROM Products;
The DATE data type is used for storing date values. This is particularly useful in applications that require tracking of events, such as order dates, birth dates, or appointment schedules.
CREATE TABLE Orders (
OrderID INTEGER PRIMARY KEY,
OrderDate DATE,
CustomerID INTEGER,
TotalAmount DECIMAL(10, 2)
);
INSERT INTO Orders (OrderID, OrderDate, CustomerID, TotalAmount)
VALUES (1, '2023-10-01', 101, 250.00),
(2, '2023-10-05', 102, 150.50);
SELECT * FROM Orders;
CURRENT_DATE
, DATEADD
, and DATEDIFF
.By understanding and utilizing these examples of SQL data types with examples, you can effectively design your database schema to meet your application’s requirements.