Course Content
Joins
0/1
Stored procedure
0/1
Database Design
0/1
Querying and Reporting
0/1
Data Validation and Constraints
0/1
Performance Optimization
0/1
Indexing strategies and best practices
0/1
Query Optimization Techniques
0/1
Analyzing query execution plans
0/1
Security and Access Control
0/1
Advanced Topics (optional, based on project needs)
0/1
SQL/SQL Server
About Lesson

Data Validation and Constraints

Data validation and constraints are essential components of a well-designed database. They ensure the accuracy, integrity, and consistency of the data stored in the database.

  1. NOT NULL Constraint:
  • Ensure that a column cannot contain NULL values.

CREATE TABLE Users (

  user_id INT PRIMARY KEY,

  username VARCHAR(50) NOT NULL,

  email VARCHAR(100) NOT NULL,

  password VARCHAR(100) NOT NULL

);

  1. UNIQUE Constraint:
  • Enforce the uniqueness of values in a column.

CREATE TABLE Users (

  user_id INT PRIMARY KEY,

  username VARCHAR(50) UNIQUE,

  email VARCHAR(100) UNIQUE,

  password VARCHAR(100) NOT NULL

);

  1. PRIMARY KEY Constraint:
  • Define a unique identifier for each row in a table.

CREATE TABLE Users (

  user_id INT PRIMARY KEY,

  username VARCHAR(50) UNIQUE,

  email VARCHAR(100) UNIQUE,

  password VARCHAR(100) NOT NULL

);

  1. FOREIGN KEY Constraint:
  • Establish a relationship between tables based on a column or columns.

CREATE TABLE Orders (

  order_id INT PRIMARY KEY,

  user_id INT,

  order_date DATE,

  FOREIGN KEY (user_id) REFERENCES Users(user_id)

);

  1. CHECK Constraint:
  • Specify a condition that must be true for the data in a column.

CREATE TABLE Products (

  product_id INT PRIMARY KEY,

  product_name VARCHAR(100),

  quantity INT,

  price DECIMAL(10, 2),

  CHECK (quantity >= 0 AND price > 0)

);

  1. Data Validation using Constraints:
  • Ensure a specific range of values for a column.

CREATE TABLE Employees (

  employee_id INT PRIMARY KEY,

  employee_name VARCHAR(100),

  age INT CHECK (age >= 18 AND age <= 65),

  salary DECIMAL(10, 2) CHECK (salary >= 0)

);