Diverse Examples of SQL Data Types

Explore practical examples of SQL data types to enhance your database knowledge.
By Jamie

Understanding SQL Data Types

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.

Example 1: INTEGER Data Type

Context

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;

Notes

  • The INTEGER type can store values from -2,147,483,648 to 2,147,483,647.
  • Variations include SMALLINT (smaller range) and BIGINT (larger range).

Example 2: VARCHAR Data Type

Context

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;

Notes

  • VARCHAR can store up to 65,535 bytes, depending on the maximum row size.
  • For fixed-length strings, consider using CHAR instead.

Example 3: DATE Data Type

Context

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;

Notes

  • The DATE type stores values in the format ‘YYYY-MM-DD’.
  • Useful functions for date manipulation include 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.