Constraints in SQL
Constraints in SQL act as data quality guardrails, enforcing rules to ensure accuracy, consistency, and integrity within your database tables.
40. PRIMARY KEY: Uniquely Identifies Each Record in a Table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
employee_id is designated as the primary key, ensuring that each employee record has a unique identifier.
41. FOREIGN KEY: Establishes a Relationship Between Two Tables
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
department_id column in the employees table is a foreign key that references the department_id column in the departments table, establishing a relationship between the two tables.
42. UNIQUE: Ensures That All Values in a Column Are Unique
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
email column must contain unique values for each employee.
43. NOT NULL: Ensures That a Column Does Not Contain NULL Values
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL
);
first_name and last_name columns must have values and cannot be NULL.
44. CHECK: Specifies a Condition That Must Be Met for a Column’s Value
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
age INT CHECK (age >= 18)
);
age column must have a value of 18 or greater due to the CHECK constraint.
SQL Cheat Sheet
In this article, we will explore the ultimate SQL cheat sheet with the PDF, covering a wide range of SQL commands, Joins in SQL, CRUD Operations, SQL Trigger, SQL Transactions, and advanced topics to help master SQL effectively.
SQL (Structured Query Language) is a Query language used for managing and manipulating relational databases databases. It allows users to interact with databases. SQL allows users to perform various tasks such as querying data, updating data, inserting new records, deleting records, creating and modifying database schemas, and managing permissions.
Table of Content
- Create a Database in SQL
- Creating Data in SQL
- Reading/Querying Data in SQL
- Updating/Manipulating Data in SQL
- Deleting Data in SQL
- Filtering Data in SQL
- SQL Operator
- Aggregation Data in SQL
- Constraints in SQL
- Joins in SQL
- SQL Functions
- Subqueries in SQL
- Views in SQL
- Indexes in SQL
- Transactions in SQL
- Advanced Mixed Data in SQL
- SQL Cheat Sheet PDF
Contact Us