SQL
π§ Day 6: SQL Constraints and Table Modification Commands
π§ Day 6: SQL Constraints and Table Modification Commands
βοΈ SQL Command Categories Recap
Letβs quickly recall the main types of SQL commands:
| Category | Full Form | Purpose |
|---|---|---|
| DDL | Data Definition Language | Defines and modifies database structure |
| DML | Data Manipulation Language | Handles data (Insert, Update, Delete) |
| TCL | Transaction Control Language | Manages database transactions |
| DQL | Data Query Language | Retrieves data from tables |
ποΈ 1οΈβ£ DDL Commands β Structure Definition
| Command | Purpose |
|---|---|
| CREATE | Creates a new table or database |
| ALTER | Adds or modifies columns |
| RENAME | Changes table name |
| TRUNCATE | Deletes all data but keeps structure |
| DROP | Deletes table with structure |
πΉ Syntax:
βοΈ 2οΈβ£ DML Commands β Data Handling
| Command | Description |
|---|---|
| INSERT | Adds new records |
| UPDATE | Modifies existing data |
| DELETE | Removes records |
πΉ Basic Syntax:
πΉ Insert Multiple Rows at Once:
πΉ Insert All Example:
π 3οΈβ£ TCL Commands β Transaction Control
| Command | Description |
|---|---|
| COMMIT | Saves changes permanently |
| ROLLBACK | Reverts to the previous commit |
| SAVEPOINT | Creates a checkpoint inside a transaction |
π 4οΈβ£ DQL Command β Data Query
Used to retrieve data from tables.
π§© SQL Constraints β Ensuring Data Integrity
Constraints are rules applied to columns to maintain accuracy and consistency in data.
π Types of Constraints
| Constraint | Purpose | Allows NULL? | Allows Duplicates? |
|---|---|---|---|
| PRIMARY KEY | Ensures unique identity for each record | β No | β No |
| FOREIGN KEY | Links two tables, maintaining referential integrity | β Yes | β Yes |
| UNIQUE | Ensures all values in a column are different | β Yes | β No |
| NOT NULL | Ensures a column cannot store NULL values | β No | β Yes |
| CHECK | Validates data based on a condition | Depends | Depends |
| DEFAULT | Assigns a default value if no value is provided | β Yes | β Yes |
πΉ Example: Creating a Table with Constraints
πΉ Insert Data:
πΉ Query Data:
π οΈ Modify Existing Table Structure
You can modify column data types or constraints after creation using ALTER TABLE.
πΉ Example:
β Quick Recap
-
Constraints enforce data rules β like uniqueness, non-null, relationships, and default values.
-
Primary Key: Unique + Not Null
-
Foreign Key: Creates relationships between tables
-
Check: Validates conditions (e.g.,
CHECK (salary > 0)) -
Alter Table: Used to modify structure
-
Insert All: Helps insert multiple rows efficiently
π§Ύ Key Takeaway
Using constraints helps ensure data quality and relational consistency in your SQL databases β making your schema strong, error-free, and reliable.