Sql Data Types And Constraints Complete Guide
Understanding the Core Concepts of SQL Data Types and Constraints
SQL Data Types and Constraints: Detailed Explanation and Important Information
Introduction
SQL Data Types
SQL data types specify the kind of data that can be stored in a column. They can be broadly categorized into three types:
Numeric Types
- Integer Types
TINYINT
: Small integer with values from -128 to 127 or 0 to 255.SMALLINT
: Larger thanTINYINT
, can hold values from -32,768 to 32,767.INT
orINTEGER
: Standard integer type, typically storing values from -2,147,483,648 to 2,147,483,647.BIGINT
: Holds large integers, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.BIT(n)
: Stores binary values, useful for boolean types.
- Decimal Types
DECIMAL(p, s)
orNUMERIC(p, s)
: Fixed-point number with a precision ofp
and scale ofs
.FLOAT(n)
: Approximate floating-point value with a precision ofn
.REAL
: Single-precision floating-point number.DOUBLE PRECISION
: Double-precision floating-point number.
- Integer Types
Character Types
CHAR(n)
: Fixed-length string of exactlyn
characters.VARCHAR(n)
: Variable-length string with a length up ton
characters.TEXT
: Large text field that can hold a substantial amount of text.NCHAR(n)
andNVARCHAR(n)
: Similar toCHAR(n)
andVARCHAR(n)
, but designed to store Unicode characters.
Date and Time Types
DATE
: Stores date without the time component inYYYY-MM-DD
format.TIME
: Stores time without the date component inHH:MM:SS
format.DATETIME
: Combines date and time inYYYY-MM-DD HH:MM:SS
format.TIMESTAMP
: Stores date and time with timezone-aware information.INTERVAL
: Used to specify a time interval between two date or time values.
Binary and Boolean Types
BINARY(n)
andVARBINARY(n)
: Fixed and variable length binary strings.BLOB
: Binary Large Object, used to store large binary data such as images, files, etc.BOOLEAN
: True or False values, often implemented as an alias forTINYINT(1)
.
Other Types
ENUM(value1, value2, ...)
: A string object with a value chosen from the list of enumerated values.SET(value1, value2, ...)
: A string object that can have zero or more values from a list of enumerated values, where the values are separated by commas.
SQL Constraints
Constraints are rules enforced on the data columns of a table to limit the type of data that the table can accept. They are used to ensure the accuracy and reliability of the data in the database. Here are the main types of constraints:
NOT NULL
- Ensures that a column does not store
NULL
values. - Example:
CREATE TABLE Persons (ID INT NOT NULL, LastName VARCHAR(255) NOT NULL);
- Ensures that a column does not store
UNIQUE
- Ensures that all values in a column are different.
- Example:
CREATE TABLE Persons (ID INT UNIQUE, LastName VARCHAR(255));
PRIMARY KEY
- A combination of
UNIQUE
andNOT NULL
constraints, which uniquely identifies each row in a table. - Example:
CREATE TABLE Persons (ID INT PRIMARY KEY, LastName VARCHAR(255));
- A combination of
FOREIGN KEY
- A field in one table that uniquely identifies a row of another table, establishing a relationship between the two tables.
- Example:
CREATE TABLE Orders (OrderID INT PRIMARY KEY, OrderNumber INT NOT NULL, PersonID INT, FOREIGN KEY (PersonID) REFERENCES Persons(ID));
CHECK
- Ensures that all values in a column satisfy a specific condition.
- Example:
CREATE TABLE Persons (ID INT NOT NULL, LastName VARCHAR(255), Age INT CHECK (Age >= 18));
DEFAULT
- Provides a default value for a column when no value is specified in an
INSERT
statement. - Example:
CREATE TABLE Orders (OrderID INT PRIMARY KEY, OrderNumber INT NOT NULL, OrderDate DATE DEFAULT CURRENT_DATE);
- Provides a default value for a column when no value is specified in an
AUTO_INCREMENT
- Automatically generates a unique value for a column typically used for primary keys.
- Example:
CREATE TABLE Persons (ID INT AUTO_INCREMENT, LastName VARCHAR(255) NOT NULL, PRIMARY KEY (ID));
Importance of Data Types and Constraints
Understanding and utilizing SQL data types and constraints effectively is crucial for several reasons:
- Data Integrity: Ensures that the data stored in your database is accurate and reliable.
- Performance Optimization: Proper data types and constraints can significantly improve query performance.
- Maintainability and Scalability: Well-designed schemas can be easier to maintain and scale as the database grows.
Online Code run
Step-by-Step Guide: How to Implement SQL Data Types and Constraints
Contents
Introduction to SQL Data Types
- Numeric Types
- Date and Time Types
- Character Types
- Large Object Types
- Boolean Type
Constraints in SQL
- PRIMARY KEY
- FOREIGN KEY
- UNIQUE
- NOT NULL
- CHECK
- DEFAULT
- AUTO_INCREMENT
Examples
1. Introduction to SQL Data Types
Data types specify the kind of data that can be stored in a database table's column. They also determine how the data is processed by the SQL engine.
Numeric Types
INT
: Integer values.SMALLINT
: Small integer values.BIGINT
: Large integer values.FLOAT
: Single-precision floating point numbers.DOUBLE
: Double-precision floating point numbers.DECIMAL(precision, scale)
: Fixed-point numbers wherep
is the total number of digits ands
is the number after the decimal point.
Date and Time Types
DATE
: Year, month, day.TIME
: Hour, minute, second.DATETIME
: Date and time together.TIMESTAMP
: Similar to DATETIME but includes timezone information.YEAR
: Year value (can be used for birth years, etc.).
Character Types
CHAR(size)
: Fixed-size string with lengthsize
.VARCHAR(size)
: Variable-size string up to lengthsize
.TEXT
: Large text strings.
Large Object Types
BLOB
: Binary large object (for storing images, videos, etc.).CLOB
: Character large object (for very large text fields).
Boolean Type
BOOLEAN
: True or False values (often represented asTINYINT(1)
in MySQL).
2. Constraints in SQL
Constraints are rules enforced on data columns to limit the type of data that the column can hold.
PRIMARY KEY
Uniquely identifies each record in a table.
FOREIGN KEY
Establishes a link between the data in two tables.
UNIQUE
Ensures that all values in a column are different.
NOT NULL
Indicates that the column cannot have a NULL value.
CHECK
Ensures that all values in a column satisfy certain conditions.
DEFAULT
Provides a default value for a column when no value is specified.
AUTO_INCREMENT
Automatically generates a unique numeric value each time a new record is added.
3. Examples
Let's walk through an example by creating a few related tables with different data types and constraints.
Example: Creating a Simple Database Schema
3.1. Create departments
Table
CREATE TABLE departments (
department_id INT AUTO_INCREMENT PRIMARY KEY,
department_name VARCHAR(100) NOT NULL UNIQUE,
location VARCHAR(255)
);
Explanation:
department_id
: A numeric primary key that automatically increments.department_name
: A not-null and unique string up to 100 characters.location
: An optional string (can beNULL
.
Inserting Data into departments
Table:
INSERT INTO departments (department_name, location) VALUES
('Human Resources', 'Building 1A'),
('Finance', 'Building 1B'),
('IT', 'Building 2');
3.2. Create employees
Table
CREATE TABLE employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone_number VARCHAR(15),
hire_date DATE NOT NULL,
job_id VARCHAR(10) NOT NULL,
salary DECIMAL(8, 2) CHECK (salary > 0),
manager_id INT,
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
Explanation:
employee_id
: Numeric primary key.first_name
andlast_name
: Mandatory strings.email
: Mandatory and unique string.phone_number
: Optional string.hire_date
: Mandatory date.job_id
: Mandatory string.salary
: Mandatory decimal value greater than zero.manager_id
: Optionally references another employee in the same table.department_id
: References thedepartment_id
in thedepartments
table.
Inserting Data into employees
Table:
INSERT INTO employees (first_name, last_name, email, phone_number, hire_date, job_id, salary, department_id) VALUES
('John', 'Doe', 'johndoe@example.com', '123-456-7890', '2022-01-15', 'HR_REP', 50000.00, 1),
('Jane', 'Smith', 'janesmith@example.com', '098-765-4321', '2023-03-20', 'ACCT_REP', 60000.50, 2),
('Alice', 'Johnson', 'alicejohnson@example.com', '234-567-8901', '2023-03-10', 'DEV', 75000.75, 3);
3.3. Attempting Invalid Inserts
Let's try inserting invalid data and see what happens.
Invalid Insert: Duplicate department_name
INSERT INTO departments (department_name, location) VALUES ('Human Resources', 'Building 3A');
Result: Error: Duplicate entry for key 'uniq_department_name'
Invalid Insert: email
must be unique
INSERT INTO employees (first_name, last_name, email, phone_number, hire_date, job_id, salary, department_id)
VALUES ('Michael', 'Brown', 'johndoe@example.com', '123-456-7890', '2023-04-10', 'HR_REP', 52000.00, 1);
Result: Error: Duplicate entry for key 'uniq_email'
Invalid Insert: salary
must be greater than 0
INSERT INTO employees (first_name, last_name, email, phone_number, hire_date, job_id, salary, department_id)
VALUES ('Chris', 'Lee', 'chrislee@example.com', '111-222-3333', '2023-05-01', 'HR_REP', -5000.00, 1);
Result: Error: CHECK constraint failed
3.4. Update and Delete Operations
Updating Data:
UPDATE employees
SET salary = 53000.00
WHERE email = 'johndoe@example.com';
Deleting Data:
Before deleting, let’s ensure the foreign key constraint works correctly.
DELETE FROM departments WHERE department_id = 1;
Result: Error: Cannot delete row because it is referenced by a foreign key constraint from the employees
table.
This ensures referential integrity; we need to delete employees from the employees
table first.
DELETE FROM employees
WHERE department_id = 1;
DELETE FROM departments
WHERE department_id = 1;
Adding Default Constraint:
Modifying the departments
table to add a default location.
ALTER TABLE departments
MODIFY COLUMN location VARCHAR(255) DEFAULT 'Main Building';
Inserting Without Specifying Location:
INSERT INTO departments (department_name) VALUES ('Marketing');
SELECT * FROM departments WHERE department_id = 4;
Result: The location
field will be automatically set to 'Main Building'.
4. Adding More Constraints
Let’s enhance our employees
table further.
3.5. Create jobs
Table
CREATE TABLE jobs (
job_id VARCHAR(10) PRIMARY KEY,
job_title VARCHAR(100) NOT NULL UNIQUE,
min_salary DECIMAL(8, 2) CHECK (min_salary >= 0),
max_salary DECIMAL(8, 2) CHECK (max_salary >= 0 AND max_salary > min_salary)
);
Explanation:
job_id
: Primary key for each job.job_title
: Must be unique and non-null.min_salary
andmax_salary
: Must be positive, andmax_salary
should be greater thanmin_salary
.
Inserting Data:
INSERT INTO jobs (job_id, job_title, min_salary, max_salary)
VALUES
('HR_REP', 'Human Resources Representative', 40000.00, 60000.00),
('ACCT_REP', 'Accountant', 50000.00, 80000.00),
('DEV', 'Software Developer', 60000.00, 120000.00);
3.6. Modifying employees
Table to Add job_id
Constraint
We will use the job_id
field already present in the employees
table, along with the jobs
table.
ALTER TABLE employees
ADD CONSTRAINT fk_job_id FOREIGN KEY (job_id) REFERENCES jobs(job_id);
Now, job_id
in the employees
table must be present in the jobs
table.
-- Valid insert using existing job_id
INSERT INTO employees (first_name, last_name, email, phone_number, hire_date, job_id, salary, department_id)
VALUES ('Chris', 'Lee', 'chrislee@example.com', '123-456-7890', '2023-05-10', 'DEV', 90000.00, 3);
-- Invalid insert using non-existing job_id
INSERT INTO employees (first_name, last_name, email, phone_number, hire_date, job_id, salary, department_id)
VALUES ('Anna', 'Miller', 'annamiller@example.com', '222-333-4444', '2023-06-01', 'INVALID_JOB_ID', 80000.00, 3);
Result: Error: Foreign key constraint failed
Summary
In this guide, we covered:
- Common SQL data types such as
INT
,VARCHAR
,DATE
,DECIMAL
, etc. - Basic constraints like
PRIMARY KEY
,FOREIGN KEY
,UNIQUE
,NOT NULL
,CHECK
,DEFAULT
, andAUTO_INCREMENT
. - Practical examples demonstrating how these types and constraints work in real databases.
Login to post a comment.