SQL Commands and Statements

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.

CommandDescription
CREATECreates a database object such as a table
ALTERModifies an existing table structure
DROPDeletes a table or database object
TRUNCATERemoves all records from a table
RENAMEChanges 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.

CommandDescription
INSERTAdds new records
UPDATEModifies existing records
DELETERemoves 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.

CommandDescription
SELECTRetrieves 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.

CommandDescription
GRANTGives privileges to users
REVOKERemoves 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.

CommandDescription
COMMITSaves changes permanently
ROLLBACKUndoes changes
SAVEPOINTCreates 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

CategoryCommands
DDLCREATE, ALTER, DROP, TRUNCATE, RENAME
DMLINSERT, UPDATE, DELETE
DQLSELECT
DCLGRANT, REVOKE
TCLCOMMIT, ROLLBACK, SAVEPOINT

SQL statements are used to create, modify, retrieve, control, and manage data stored in a database.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *