In this tutorial, we will focus on defining data types and constraints in SQL. These two elements are essential to ensure the integrity and optimal performance of your database.
By the end of this tutorial, you will be able to:
- Understand the concept of data types in SQL
- Define constraints in SQL
- Apply these concepts in your database design
Basic understanding of SQL commands and database concepts will be beneficial.
Data types in SQL define the kind of data that can be stored inside a table column. Different types of data include integer, date, string, etc.
Constraints in SQL are rules enforced on data columns on a table. They ensure the accuracy and reliability of the data in the table.
CREATE TABLE Employees (
ID INT,
Name VARCHAR (20),
BirthDate DATE,
Salary DECIMAL (8, 2)
);
In this code snippet, we are creating a table called "Employees" with four columns: ID, Name, BirthDate, and Salary. Each column has a specific data type defined.
INT
: Integer data typeVARCHAR(20)
: Variable character string with a maximum length of 20 charactersDATE
: Date data typeDECIMAL(8, 2)
: Decimal data type with 8 digits in total and 2 digits after the decimal pointCREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
BirthDate DATE,
Salary DECIMAL (8, 2) CHECK (Salary > 0)
);
Here, we are defining constraints on the columns:
PRIMARY KEY
: The ID column is the primary key and cannot have duplicate or null valuesNOT NULL
: The Name column cannot have null valuesCHECK
: The Salary column must have a value greater than 0In this tutorial, we went over SQL data types and constraints. We learned how to define data types for table columns and how to enforce rules on these columns using constraints.
The next step in your learning could be to delve deeper into the different types of constraints available in SQL: UNIQUE
, FOREIGN KEY
, DEFAULT
, among others.
Create a table called "Products" with the following columns: ProductID (integer and primary key), ProductName (string with a maximum length of 30 characters and not null), and Price (decimal with a maximum of 5 digits in total and 2 after the decimal point, must be positive).
Create a table called "Orders" with the following columns: OrderID (integer and primary key), ProductID (integer and foreign key referencing ProductID in the Products table), and OrderDate (date).
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR (30) NOT NULL,
Price DECIMAL (5, 2) CHECK (Price > 0)
);
ProductID is the primary key, ProductName can't be null, and Price must be positive.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
ProductID INT,
OrderDate DATE,
FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
);
OrderID is the primary key. ProductID is a foreign key referencing the ProductID in the Products table.
Keep practicing and exploring more about SQL data types and constraints to enhance your skills!