SQL commands are instructions used to perform specific tasks in a database. SQL statements are categorized into different types based on their functions.
1. DDL (Data Definition Language)
DDL commands are used to define and modify database structures.
| Command | Description |
|---|---|
| CREATE | Creates a database object such as a table |
| ALTER | Modifies an existing table structure |
| DROP | Deletes a table or database object |
| TRUNCATE | Removes all records from a table |
| RENAME | Changes the name of a database object |
Examples
-- Create Table
CREATE TABLE Student (
StudentID INT,
Name VARCHAR(50),
City VARCHAR(30)
);
-- Add a column
ALTER TABLE Student
ADD Email VARCHAR(50);
-- Rename table
RENAME Student TO Students;
-- Remove all records
TRUNCATE TABLE Students;
-- Delete table
DROP TABLE Students;
2. DML (Data Manipulation Language)
DML commands are used to manipulate data in tables.
| Command | Description |
|---|---|
| INSERT | Adds new records |
| UPDATE | Modifies existing records |
| DELETE | Removes records |
Examples
-- Insert Data
INSERT INTO Student
VALUES (1, 'Rahul', 'Rajkot');
-- Update Data
UPDATE Student
SET City = 'Ahmedabad'
WHERE StudentID = 1;
-- Delete Data
DELETE FROM Student
WHERE StudentID = 1;
3. DQL (Data Query Language)
DQL commands are used to retrieve data.
| Command | Description |
|---|---|
| SELECT | Retrieves data from a table |
Example
SELECT * FROM Student;
SELECT Name, City
FROM Student
WHERE City = 'Rajkot';
4. DCL (Data Control Language)
DCL commands control user access and permissions.
| Command | Description |
|---|---|
| GRANT | Gives privileges to users |
| REVOKE | Removes privileges |
Examples
-- Grant permission
GRANT SELECT ON Student TO user1;
-- Revoke permission
REVOKE SELECT ON Student FROM user1;
5. TCL (Transaction Control Language)
TCL commands manage transactions.
| Command | Description |
|---|---|
| COMMIT | Saves changes permanently |
| ROLLBACK | Undoes changes |
| SAVEPOINT | Creates a point within a transaction |
Examples
-- Save changes
COMMIT;
-- Undo changes
ROLLBACK;
-- Create savepoint
SAVEPOINT sp1;
Common SQL Statements
SELECT Statement
SELECT * FROM Student;
WHERE Clause
SELECT * FROM Student
WHERE City = 'Rajkot';
ORDER BY Clause
SELECT * FROM Student
ORDER BY Name ASC;
GROUP BY Clause
SELECT City, COUNT(*)
FROM Student
GROUP BY City;
HAVING Clause
SELECT City, COUNT(*)
FROM Student
GROUP BY City
HAVING COUNT(*) > 5;
JOIN Statement
SELECT Student.Name, Course.CourseName
FROM Student
INNER JOIN Course
ON Student.StudentID = Course.StudentID;
Summary
| Category | Commands |
|---|---|
| DDL | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| DML | INSERT, UPDATE, DELETE |
| DQL | SELECT |
| DCL | GRANT, REVOKE |
| TCL | COMMIT, ROLLBACK, SAVEPOINT |
SQL statements are used to create, modify, retrieve, control, and manage data stored in a database.