Comprehensive SQL Commands Guide
Comprehensive SQL Commands Guide
Just Do It
MARZ TECHNOLOGIES Karaikudi + 91 90427 10472
Contents
SQL COMMANDS ..................................................................................................... 4
Data Definition Language (DDL) ............................................................................. 4
1. CREATE Command ..................................................................................... 4
2. ALTER Command ....................................................................................... 4
3. DROP Command ........................................................................................... 5
4. TRUNCATE Command.................................................................................... 6
5. RENAME Command ....................................................................................... 6
Data Manipulation Language (DML) in SQL ............................................................. 6
1. INSERT Command ...................................................................................... 6
2. UPDATE Command ........................................................................................ 7
3. DELETE Command ........................................................................................ 7
4. SELECT Command ........................................................................................ 7
Data Query Language (DQL) .................................................................................. 8
SELECT Command ............................................................................................ 8
Data Control Language (DCL) ................................................................................ 8
1. GRANT Command ......................................................................................... 8
2. REVOKE Command........................................................................................ 8
Transaction Control Language (TCL) ....................................................................... 9
1. COMMIT Command ....................................................................................... 9
2. ROLLBACK Command ................................................................................... 9
3. SAVEPOINT Command ............................................................................. 10
Key Differences Between DROP, TRUNCATE, and DELETE ...................................... 11
SQL Constraints..................................................................................................... 12
Types of SQL Constraints .................................................................................... 12
1. NOT NULL................................................................................................ 12
2. UNIQUE................................................................................................... 12
3. PRIMARY KEY ........................................................................................... 12
4. FOREIGN KEY........................................................................................... 13
5. CHECK .................................................................................................... 13
6. DEFAULT.................................................................................................. 13
7. AUTO_INCREMENT (IDENTITY in SQL Server) .............................................. 13
1
FILTERING AND SORTING DATA ............................................................................... 14
Filtering Data ...................................................................................................... 14
Using IS NULL Operator ...................................................................................... 15
Operators in SQL ................................................................................................ 15
Sorting Data ....................................................................................................... 15
Combining Filtering and Sorting ........................................................................... 16
Limiting Results (TOP, FETCH) .............................................................................. 16
Aggregate Functions ........................................................................................... 16
Grouping Data .................................................................................................... 17
GROUP BY AND HAVING ......................................................................................... 18
Using GROUP BY ................................................................................................ 18
Using GROUP BY with HAVING............................................................................. 18
Using Multiple Columns in GROUP BY .................................................................. 18
Using HAVING with GROUP BY and Aggregate Functions ....................................... 19
Key Differences Between WHERE and HAVING Clauses ........................................ 19
SQL FUNCTIONS.................................................................................................... 20
Aggregate Functions ........................................................................................... 20
String Functions ................................................................................................. 20
Date Functions ................................................................................................... 21
Mathematical Functions ..................................................................................... 22
Ranking Functions in SQL ....................................................................................... 23
RANK() ............................................................................................................... 23
DENSE_RANK() ................................................................................................... 24
ROW_NUMBER()................................................................................................. 24
JOINS IN SQL ......................................................................................................... 25
Example Tables in SQL Server .............................................................................. 25
1. INNER JOIN .................................................................................................... 26
2. LEFT JOIN (LEFT OUTER JOIN) .......................................................................... 27
3. RIGHT JOIN (RIGHT OUTER JOIN) ..................................................................... 28
4. FULL OUTER JOIN ........................................................................................... 28
5. CROSS JOIN ................................................................................................... 29
6. SELF JOIN ....................................................................................................... 29
2
SUBQUERIES IN MS SQL SERVER ............................................................................ 32
Example 1: Subquery in the SELECT Clause .......................................................... 32
Example 2: Subquery in the WHERE Clause .......................................................... 33
Example 3: Subquery in the FROM Clause ............................................................ 33
Example 4: Correlated Subquery ......................................................................... 34
VIEWS IN SQL SERVER ........................................................................................... 35
Creating a View .................................................................................................. 35
Alter a view ........................................................................................................ 36
Dropping a View (DROP VIEW) ............................................................................. 36
Updatable Views ................................................................................................ 36
INDEX ................................................................................................................... 38
Create an Index .................................................................................................. 38
Query the Table Using the Indexed Column........................................................... 39
STORED PROCEDURES .......................................................................................... 40
CREATING STORED PROCEDURES WITHOUT PARAMETERS ...................................... 40
CREATING A STORED PROCEDURES WITH PARAMETERS ......................................... 41
CREATING STORED PROCEDURE TO CREATE A TABLE .............................................. 41
CREATING STORED PROCEDURE TO INSERT DATA INTO A TABLE .............................. 42
CREATING STORED PROCEDURE TO UPDATE DATA IN THE TABLE ............................. 42
User-defined function (UDF) in SQL Server .................................................................. 43
Types of User-Defined Functions: ........................................................................ 43
Creating a Scalar Function .................................................................................. 43
Creating a Table-Valued Function:........................................................................ 44
Difference Between Stored Procedures and Functions ............................................. 46
Triggers in MS SQL Server ....................................................................................... 47
DML Triggers in MS SQL Server............................................................................. 47
Temporary tables in SQL Server ................................................................................. 50
3
SQL COMMANDS
SQL commands can be classified into five categories based on functionality, along with
their syntax and examples:
4. TRUNCATE – Removes all records from a table but retains its structure.
1. CREATE Command
Syntax:
Example:
2. ALTER Command
Used to modify an existing database object, such as adding, deleting, or
modifying columns.
4
Syntax (Add a Column):
3. DROP Command
Used to delete a database object permanently.
Syntax :
5
4. TRUNCATE Command
Used to remove all records from a table without deleting its structure.
Syntax :
5. RENAME Command
Used to rename an existing table.
Syntax :
DML commands are responsible for inserting, updating, deleting, and retrieving data
from tables.
1. INSERT Command
Syntax:
6
Example:
2. UPDATE Command
Used to modify existing records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
UPDATE Employees
SET Age = 31
WHERE EmpID = 101;
3. DELETE Command
Used to remove records from a table.
Syntax:
4. SELECT Command
Used to retrieve data from a table.
Syntax:
7
Data Query Language (DQL)
DQL is used to retrieve data from the database.
SELECT Command
Fetches records from a table
Syntax:
1. GRANT Command
The GRANT command is used to give access permissions to a user for performing
specific actions on a database object.
Syntax:
Grant SELECT and INSERT privileges on the Customers table to the user John:
2. REVOKE Command
The REVOKE command is used to take back previously granted permissions from
a user or role.
8
Syntax:
Revoke the INSERT privilege from the user John on the Customers table:
These commands are used to control the changes made by DML (Data Manipulation
Language) statements such as INSERT, UPDATE, and DELETE. TCL ensures the
integrity and consistency of the database.
1. COMMIT Command
• The COMMIT command is used to save all the changes made by the current
transaction permanently in the database.
Syntax:
COMMIT;
Example:
BEGIN TRANSACTION;
INSERT INTO Customers (CustomerID, Name, City) VALUES (1,
'Alice', 'New York');
COMMIT;
2. ROLLBACK Command
• The ROLLBACK command is used to undo all changes made by the current
transaction before a COMMIT is executed.
9
Syntax:
ROLLBACK;
Example:
BEGIN TRANSACTION;
UPDATE Customers SET City = 'Los Angeles' WHERE CustomerID =
1;
ROLLBACK;
This will revert the city of the customer back to its original value.
3. SAVEPOINT Command
The SAVEPOINT command allows setting a point within a transaction to which
changes can be rolled back partially, instead of rolling back the entire
transaction.
Create a Savepoint
SAVE TRANSACTION SavePoint1;
10
Simulate an Error
INSERT INTO Employees (Name, Position, Age) VALUES ('Invalid Entry', NULL, 20); --
This will fail!
Example:
BEGIN TRANSACTION;
INSERT INTO Customers (CustomerID, Name, City) VALUES (2, 'Bob',
'Chicago');
SAVEPOINT sp1;
UPDATE Customers SET City = 'San Francisco' WHERE CustomerID
= 2;
ROLLBACK TO sp1;
COMMIT;
The rollback will undo the UPDATE statement but keep the INSERT operation.
11
SQL Constraints
SQL constraints are rules enforced on table columns to maintain data integrity and
ensure accuracy and reliability. They define the rules that data must follow within a
database.
1. NOT NULL
• Ensures that a column cannot have NULL values.
Example:
2. UNIQUE
• Ensures that all values in a column are unique.
Example:
3. PRIMARY KEY
• Combines NOT NULL and UNIQUE to identify each record uniquely.
Example:
12
4. FOREIGN KEY
• Ensures referential integrity by linking one table’s column to another table’s
primary key.
Example:
5. CHECK
• Ensures that values in a column meet specific conditions.
Example:
6. DEFAULT
• Assigns a default value to a column if no value is provided.
Example:
13
FILTERING AND SORTING DATA
Filtering and sorting data in SQL is essential for retrieving specific results from a
database in an organized manner.
Filtering Data
The WHERE clause is used to filter records based on specified conditions.
Examples:
The LIKE operator is used for pattern matching with wildcard characters:
14
WHERE Name LIKE 'A____';
Find employees with a 5-letter name starting with 'A'.
Example:
Operators in SQL
Comparison Operators:
Sorting Data
The ORDER BY clause is used to sort results in ascending (ASC) or descending (DESC)
order.
Examples:
15
Sort by Multiple Columns
Using TOP
Aggregate Functions
• SUM(column_name) → Returns the total sum of a numeric column.
16
SELECT MIN(Age) AS Youngest
FROM Employees;
SELECT MAX(Salary) AS
HighestSalary FROM Employees;
Grouping Data
a) GROUP BY
17
GROUP BY AND HAVING
• GROUP BY is used with aggregate functions like SUM(), AVG(), COUNT(), MIN(),
MAX().
• HAVING filters grouped results (similar to WHERE, but for aggregated values).
• WHERE is used before GROUP BY to filter individual rows, whereas HAVING is
used after GROUP BY to filter groups.
Using GROUP BY
Suppose we want to find the total quantity sold for each product.
18
Using HAVING with GROUP BY and Aggregate Functions
If we want to filter categories where the total quantity sold is more than 5:
19
SQL FUNCTIONS
1. Aggregate Functions (Used for summarizing data)
2. String Functions (Used for string manipulation)
3. Date Functions (Used for date and time manipulation)
4. Mathematical Functions (Used for numerical calculations)
Aggregate Functions
• SUM(column_name) → Returns the total sum of a numeric column.
SELECT MAX(Salary) AS
HighestSalary FROM Employees;
String Functions
• LEN(string) → Returns the length of a string
20
SELECT LEN('SQL Server') AS
StringLength;
-- Output: 10
-- Output: Hello
Date Functions
• GETDATE() → Returns the current system date and time.
21
SELECT DATEDIFF(YEAR, '2000-01-01', GETDATE()) AS
YearsDifference;
Mathematical Functions
• ROUND(number, decimals) → Rounds a number to the specified number of
decimal places.
22
Ranking Functions in SQL
1. RANK() – Assigns a rank to each row but skips numbers when there are ties.
2. DENSE_RANK() – Assigns a rank to each row but does not skip numbers when
there are ties.
3. ROW_NUMBER() – Assigns a unique sequential number to each row, ignoring
duplicate values.
1 Alice IT 75000
2 Bob HR 60000
3 Carol IT 90000
4 Dave IT 75000
5 Eve HR 85000
RANK()
Example (Ranks employees by salary, skipping numbers for ties)
Output:
Carol 90000 1
Eve 85000 2
Alice 75000 3
Dave 75000 3
Bob 60000 5
Notice: Since Alice and Dave have the same salary, they both get rank 3, but the next
rank 4 is skipped.
23
DENSE_RANK()
Example (Ranks employees without skipping numbers)
Output:
Carol 90000 1
Eve 85000 2
Alice 75000 3
Dave 75000 3
Bob 60000 4
Difference from RANK(): The numbering remains continuous even when there are ties.
ROW_NUMBER()
Example (Assigns a unique row number)
Output:
Carol 90000 1
Eve 85000 2
Alice 75000 3
Dave 75000 4
Bob 60000 5
Unlike RANK() and DENSE_RANK(), this assigns a unique number to each row, even
when salaries are equal.
24
JOINS IN SQL
In MS SQL Server, joins retrieve data from multiple tables based on a related column.
The main types of joins are:
1. INNER JOIN
5. CROSS JOIN
6. SELF JOIN
When to Use?
• Use VARCHAR if your data is strictly in English or does not require Unicode
support (saves storage). (1 byte per character)
25
Remove Foreign key constraints While entering the orders data with customer id not in
the customers table
1. INNER JOIN
• Returns only the matching rows from both tables.
SELECT [Link],
[Link],
[Link],
[Link]
FROM Customers
INNER JOIN Orders ON [Link] = [Link];
26
2. LEFT JOIN (LEFT OUTER JOIN)
Returns all records from the left table (Customers) and matching records from the
right table (Orders). If there’s no match, NULL is returned for columns from the right
table.
SELECT [Link],
[Link],
[Link],
[Link]
FROM Customers
LEFT JOIN Orders ON [Link] = [Link];
27
3. RIGHT JOIN (RIGHT OUTER JOIN)
Returns all records from the right table (Orders) and matching records from the left
table (Customers). If no match is found, NULL appears in left table columns.
SELECT [Link],
[Link],
[Link],
[Link]
FROM Customers
RIGHT JOIN Orders ON [Link] = [Link];
SELECT [Link],
[Link],
[Link],
[Link]
FROM Customers
FULL OUTER JOIN Orders ON [Link] =
[Link];
28
5. CROSS JOIN
Produces a Cartesian product (all possible combinations of rows from both tables).
SELECT [Link],
[Link],
[Link],
[Link]
FROM Customers
CROSS JOIN Orders;
Example output:
6. SELF JOIN
29
A table joins itself. Useful for hierarchical or recursive relationships.
Consider an Employees table where each employee has a ManagerID that refers to
another employee in the same table. We want to find the names of employees along
with their managers.
SELECT
[Link] AS Employee_ID,
[Link] AS Employee_Name,
[Link] AS Manager_ID,
[Link] AS Manager_Name
FROM Employees e1
LEFT JOIN Employees e2 ON [Link] = [Link];
Explanation
• e1 represents employees.
• LEFT JOIN is used to ensure that employees without managers (like Alice) are still
included in the result.
OUTPUT:
30
• Self-Join helps retrieve hierarchical relationships.
• We alias the table to distinguish between employees and managers.
• LEFT JOIN ensures even the top-level managers (who have no superior) are
included.
31
SUBQUERIES IN MS SQL SERVER
A subquery is a query nested inside another query, such as a SELECT, INSERT, UPDATE,
or DELETE statement. Subqueries help break down complex queries and retrieve data in
multiple steps.
1. Single-Row Subquery – Returns a single row and column as a result. Used with
operators like =, >, <, >=, <=, <>.
2. Multi-Row Subquery – Returns multiple rows but only one column. These are
often paired with operators like IN, ANY, or ALL.
INSERT INTO Sales (SaleID, ProductName, Price, Quantity) VALUES (1, 'Laptop',
800.00, 3);
INSERT INTO Sales (SaleID, ProductName, Price, Quantity) VALUES (2, 'Tablet',
300.00, 5);
INSERT INTO Sales (SaleID, ProductName, Price, Quantity) VALUES (3,
'Headphones', 100.00, 10);
Query
SELECT ProductName,
Price,
Quantity,
32
(SELECT Price * Quantity FROM Sales AS S2 WHERE [Link] = [Link]) AS
TotalRevenue
FROM Sales AS S1;
OUTPUT:
Query
OUTPUT:
Query
OUTPUT:
33
Example 4: Correlated Subquery
Find all products that cost more than the average price of their own category
Query
OUTPUT:
34
VIEWS IN SQL SERVER
In MS SQL Server, a VIEW is a virtual table that is based on the result set of a SQL
query.
A view does not store data itself but retrieves data dynamically from the underlying
tables whenever it is queried.
• Must not use DISTINCT, GROUP BY, HAVING, JOIN, or AGGREGATE FUNCTIONS.
Creating a View
The basic syntax for creating a view:
Example Table:
35
Now, we create a view that selects only customers from the USA:
Output:
Alter a view
If you need to change an existing view:
Output:
Updatable Views
Condition for Updatable View:
• Must not use DISTINCT, GROUP BY, HAVING, JOIN, or AGGREGATE FUNCTIONS.
36
Updating Data Through View
UPDATE US_Customers
SET CustomerName = 'Jonathan'
WHERE CustomerID = 1;
Output:
Output:
Output:
37
INDEX
An index is a database object that improves the speed of data retrieval operations on a
table.
Output table:
Create an Index
CREATE INDEX IDX_Salary
ON Employees_table (Salary);
Explanation:
• IDX_Salary: The name of the index (you can use any name you prefer).
• (Salary): The column on which the index is created. This makes queries on Salary
faster.
38
Query the Table Using the Indexed Column
The index on the Salary column allows SQL Server to quickly locate rows where the
Salary is greater than 55000 without scanning the entire table.
1. Improved Query Performance: Indexes reduce the time to search and retrieve
data from a table.
2. Efficient Sorting: Sorting operations (e.g., ORDER BY) on indexed columns are
faster.
3. Drawback: Indexes slightly slow down INSERT, UPDATE, and DELETE operations
because the index needs to be maintained.
39
STORED PROCEDURES
• A stored procedure is a prepared SQL code that can be saved for reuse.
• If you have an SQL query that you use repeatedly, you can save it as a stored
procedure and then call it whenever needed.
• Additionally, you can pass parameters to a stored procedure so that it can
perform actions based on the parameter value(s) passed to it.
sql_statement
END;
EXECUTE SYNTAX
EXEC procedure_name;
EXAMPLE
CREATE PROCEDURE GetStudentDetails
AS
BEGIN
END
EXEC GetStudentDetails
40
CREATING A STORED PROCEDURES WITH
PARAMETERS
END
EXEC GetStudentAge 27
EXAMPLE
CREATE PROC StudentNameDetails
@StudentName varchar(150) = '%'
AS
BEGIN
select * from StudentDetails
where StudentName LIKE @StudentName;
END
EXEC StudentNameDetails's%'
EXEC CreateTableProcedure
41
CREATING STORED PROCEDURE TO INSERT DATA
INTO A TABLE
CREATE PROCEDURE InsertDataProcedure
@Name VARCHAR(150),
@City VARCHAR(150)
AS
BEGIN
INSERT INTO Student
(Name,City)
VALUES
(@Name,@City)
END
42
User-defined function (UDF) in SQL Server
A user-defined function (UDF) in SQL Server is a programmable routine that you can create
to perform a specific task.
UDFs allow you to encapsulate reusable logic that can return a scalar value or a table,
depending on the type of function.
UDFs are particularly useful for tasks that need to be executed repeatedly, such as
formatting data, performing calculations, or encapsulating complex logic.
Table-Valued Function:
Syntax:
43
Usage:
Syntax:
Usage:
44
Create the Table:
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
EmpName NVARCHAR(50),
Department NVARCHAR(50),
Salary DECIMAL(10, 2)
);
Insert Data:
INSERT INTO Employees (EmpID, EmpName, Department, Salary)
VALUES (101, 'John Doe', 'IT', 75000.00),
(102, 'Jane Smith', 'HR', 65000.00),
(103, 'Robert Brown', 'Finance', 80000.00),
(104, 'Emily White', 'IT', 70000.00);
-- Usage:
SELECT EmpName, Salary, [Link](Salary) AS Bonus
FROM Employees;
-- Usage:
SELECT * FROM [Link]('IT');
45
Difference Between Stored Procedures and Functions
Aspect Stored Procedure Function
Purpose Used to perform tasks like Primarily used to return a value
updates, inserts, or complex or perform calculations.
logic.
Perform operations
Return Type May return zero, one, or multiple Always returns a single value
values. (scalar, table).
Execution Called using EXEC or EXECUTE. Called as part of a query (e.g.,
SELECT).
Used in queries
Parameters Supports input-output Only supports input
parameters. parameters.
Transaction Can include transaction handling Cannot manage transactions.
Handling (e.g., BEGIN, COMMIT).
Usage in Cannot be directly used in SQL Can be used in queries and
Queries queries like SELECT. expressions.
46
Triggers in MS SQL Server
• A trigger in MS SQL Server is a database object that automatically executes or
"fires" in response to certain events on a table or view.
• Triggers are often used to enforce business rules, automatically update audit
logs, or validate data changes.
DML Triggers: Fired by data manipulation events such as INSERT, UPDATE, or DELETE.
47
SELECT 'INSERT', OrderID FROM INSERTED;
END;
Output:
Output:
48
AFTER UPDATE Trigger
Create the UPDATE Trigger
CREATE TRIGGER trg_AfterUpdate
ON Orders
AFTER UPDATE
AS
BEGIN
INSERT INTO AuditLog (AuditAction, OrderID)
SELECT 'UPDATE', OrderID FROM INSERTED;
END;
Output:
Key Takeaways
• Triggers help maintain data consistency, enforce rules, and automate tasks.
• Using inserted and deleted pseudo-tables, triggers can access old and new
records dynamically.
49
Temporary tables in SQL Server
Temporary tables in SQL Server exist temporarily and are deleted automatically when the
session or procedure that created them ends. They are extremely useful for storing
intermediate results during query processing.
Syntax:
50
Step 1: Set Up the Original Table
Now, calculate the total sales per customer from the Orders table and insert it into the
temporary table.
After the insertion, the #TempCustomerSales table will have the following data:
CustomerID TotalSales
101 1200
102 1200
103 2000
Use the temporary table for further analysis, such as filtering customers with total sales
exceeding ₹1,000.
51
SELECT CustomerID, TotalSales
FROM #TempCustomerSales
WHERE TotalSales > 1000;
CustomerID TotalSales
101 1200
102 1200
103 2000
Notes
1. Temporary tables are created in the tempdb database.
2. Local temporary tables (#TempTable) are only visible to the session that created
them, while global temporary tables (##TempTable) are visible across all sessions.
3. You cannot use temporary tables to persist data after the session ends.
52