SQL Commands | DDL, DQL, DML, DCL and TCL
Commands
SQL commands are fundamental building blocks used to perform given operations on database.
The operations include queries of data. creating a table, adding data to tables, dropping the
table, modifying the table and set permission for users.
SQL Commands are mainly categorized into five categories:
SQL Commands
1. DDL - Data Definition Language
DDL (Data Definition Language) actually consists of SQL commands that can be used for
defining, altering and deleting database structures such as tables, indexes and schemas. It
simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in the database
Command Description Syntax
Create database or its objects (table, index,
CREATE TABLE table_name (column1
CREATE function, views, store procedure and
data_type, column2 data_type, ...);
triggers)
DROP Delete objects from the database DROP TABLE table_name;
ALTER TABLE table_name ADD
ALTER Alter the structure of the database
COLUMN column_name data_type;
Command Description Syntax
Remove all records from a table, including
TRUNCATE all spaces allocated for the records are TRUNCATE TABLE table_name;
removed
COMMENT ON TABLE table_name IS
COMMENT Add comments to the data dictionary
'comment_text';
RENAME TABLE old_table_name TO
RENAME Rename an object existing in the database
new_table_name;
Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
In this example, a new table called employees is created with columns for employee ID, first
name, last name and hire date.
2. DQL - Data Query Language
DQL is used to fetch data from the database. The main command is SELECT, which retrieves
records based on the query. The output is returned as a result set (a temporary table) that can
be viewed or used in applications.
Command Description Syntax
SELECT column1, column2, ...FROM table_name
SELECT It is used to retrieve data from the database
WHERE condition;
Indicates the table(s) from which to retrieve SELECT column1
FROM
data. FROM table_name;
SELECT column1
Filters rows before any grouping or
WHERE FROM table_name
aggregation
WHERE condition;
SELECT column1, AVG_FUNCTION(column2)
GROUP Groups rows that have the same values in
FROM table_name
BY specified columns.
GROUP BY column1;
SELECT column1, AVG_FUNCTION(column2)
FROM table_name
HAVING Filters the results of GROUP BY
GROUP BY column1
HAVING condition;
DISTINCT Removes duplicate rows from the result set SELECT DISTINCT column1, column2, ...
Command Description Syntax
FROM table_name;
SELECT column1
ORDER
Sorts the result set by one or more columns FROM table_name
BY
ORDER BY column1 [ASC | DESC];
By default, it sorts in ascending
LIMIT SELECT * FROM table_name LIMIT number;
order unless specified as DESC
Note: DQL has only one command, SELECT. Other terms like FROM, WHERE, GROUP BY,
HAVING, ORDER BY, DISTINCT and LIMIT are clauses of SELECT, not separate commands.
Example:
SELECT first_name, last_name, hire_date
FROM employees
WHERE department = 'Sales'
ORDER BY hire_date DESC;
This query retrieves employees first and last names, along with their hire dates, from the
employees table, specifically for those in the 'Sales' department, sorted by hire date.
3. DML - Data Manipulation Language
DML commands are used to manipulate the data stored in database tables. With DML, you can
insert new records, update existing ones, delete unwanted data or retrieve information.
Command Description Syntax
INSERT INTO table_name (column1, column2, ...) VALUES
INSERT Insert data into a table
(value1, value2, ...);
Update existing data within a UPDATE table_name SET column1 = value1, column2 = value2
UPDATE
table WHERE condition;
Delete records from a
DELETE DELETE FROM table_name WHERE condition;
database table
Example:
INSERT INTO employees (first_name, last_name, department)
VALUES ('Jane', 'Smith', 'HR');
This query inserts a new record into employees table with first name 'Jane', last name 'Smith'
and department 'HR'.
4. DCL - Data Control Language
DCL (Data Control Language) includes commands such as GRANT and REVOKE which mainly
deal with the rights, permissions and other controls of the database system. These commands
are used to control access to data in the database by granting or revoking permissions.
Command Description Syntax
Assigns new privileges to a user account, GRANT privilege_type [(column_list)] ON
GRANT allowing access to specific database [object_type] object_name TO user [WITH
objects, actions or functions. GRANT OPTION];
Removes previously granted privileges REVOKE [GRANT OPTION FOR]
from a user account, taking away their privilege_type [(column_list)] ON
REVOKE
access to certain database objects or [object_type] object_name FROM user
actions. [CASCADE];
Example:
GRANT SELECT, UPDATE ON employees TO user_name;
This command grants the user user_name the permissions to select and update records in the
employees table.
5. TCL - Transaction Control Language
Transactions group a set of tasks into a single execution unit. Each transaction begins with a
specific task and ends when all the tasks in the group are successfully completed. If any of the
tasks fail, transaction fails. Therefore, a transaction has only two results: success or failure.
Command Description Syntax
BEGIN BEGIN TRANSACTION
Starts a new transaction
TRANSACTION [transaction_name];
Saves all changes made during the
COMMIT COMMIT;
transaction
Undoes all changes made during the
ROLLBACK ROLLBACK;
transaction
Creates a savepoint within the current
SAVEPOINT SAVEPOINT savepoint_name;
transaction
Example:
BEGIN TRANSACTION;
UPDATE employees SET department = 'Marketing' WHERE department = 'Sales';
SAVEPOINT before_update;
UPDATE employees SET department = 'IT' WHERE department = 'HR';
ROLLBACK TO SAVEPOINT before_update;
COMMIT;
Introduction of Relational Algebra in DBMS
Relational Algebra is a formal language used to query and manipulate relational databases,
consisting of a set of operations like selection, projection, union, and join. It provides a
mathematical framework for querying databases, ensuring efficient data retrieval and
manipulation.
Relational algebra serves as the mathematical foundation for query SQL.
SQL queries are based on relational algebra operations, enabling users to retrieve data
effectively.
Note: Relational algebra simplifies the process of querying databases and makes it easier to
understand and optimize query execution for better performance. It is essential for learning SQL
Key Concepts in Relational Algebra
Before explaining relational algebra operations, let's define some fundamental concepts:
Relations: In relational algebra, a relation is a table that consists of rows and columns,
representing data in a structured format. Each relation has a unique name and is made up of
tuples.
Tuples: A tuple is a single row in a relation, which contains a set of values for each attribute.
It represents a single data entry or record in a relational table.
Attributes: Attributes are the columns in a relation, each representing a specific
characteristic or property of the data. For example, in a "Students" relation, attributes could
be "Name", "Age", and "Grade".
Domains: A domain is the set of possible values that an attribute can have. It defines the
type of data that can be stored in each column of a relation, such as integers, strings, or
dates.
Basic Operators in Relational Algebra
Relational algebra consists of various basic operators that help us to fetch and manipulate data
from relational tables in the database to perform certain operations on relational data. Basic
operators are fundamental operations that include selection (σ), projection (π), union (U), set
difference (−), Cartesian product (×), and rename (ρ).
SQL Aggregate functions
SQL Aggregate Functions are used to perform calculations on a set of rows and return a single
value. These functions are particularly useful when we need to summarize, analyze or group
large datasets in SQL databases.
They are often used with GROUP BY clause in SQL to summarize data for each group.
Commonly used aggregate functions include COUNT(), SUM(), AVG(), MIN() and MAX().
Key Features of Aggregate Functions
Operate on groups of rows: They work on a set of rows and return a single value.
Ignore NULLs: Most aggregate functions ignore NULL values, except for COUNT(*).
Used with GROUP BY: To perform calculations on grouped data, often use aggregate
functions with GROUP BY.
Can be combined with other SQL clauses: Aggregate functions can be used alongside
HAVING, ORDER BY and other SQL clauses to filter or sort results.
Commonly Used SQL Aggregate Functions
Below are the most frequently used aggregate functions in SQL.
1. Count()
It is used to count the number of rows in a table. It helps summarize data by giving the total
number of entries. It can be used in different ways depending on what you want to count:
COUNT(*): Counts all rows.
COUNT(column_name): Counts non-NULL values in the specified column.
COUNT(DISTINCT column_name): Counts unique non-NULL values in the column.
Examples:
-- Total number of records in the table
SELECT COUNT(*) AS TotalRecords FROM Employee;
-- Count of non-NULL salaries
SELECT COUNT(Salary) AS NonNullSalaries FROM Employee;
-- Count of unique non-NULL salaries
SELECT COUNT(DISTINCT Salary) AS UniqueSalaries FROM Employee;
2. SUM()
It is used to calculate the total of a numeric column. It adds up all non-NULL values in that
column for Example, SUM(column_name) returns sum of all non-NULL values in the specified
column.
Examples:
-- Calculate the total salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;
-- Calculate the sum of unique salaries
SELECT SUM(DISTINCT Salary) AS DistinctSalarySum FROM Employee;
3. AVG()
It is used to calculate average value of a numeric column. It divides sum of all non-NULL values
by the number of non-NULL rows for Example, AVG(column_name) returns average of all non-
NULL values in the specified column.
Examples:
-- Calculate the average salary
SELECT AVG(Salary) AS AverageSalary FROM Employee;
-- Average of distinct salaries
SELECT AVG(DISTINCT Salary) AS DistinctAvgSalary FROM Employee;
4. MIN() and MAX()
The MIN() and MAX() functions return the smallest and largest values, respectively, from a
column.
Examples:
-- Find the highest salary
SELECT MAX(Salary) AS HighestSalary FROM Employee;
-- Find the lowest salary
SELECT MIN(Salary) AS LowestSalary FROM Employee;
Examples Queries
Let's consider a demo Employee table to demonstrate SQL aggregate functions. This table
contains employee details such as their ID, Name and Salary.
Id Name Salary
1 A 802
2 B 403
Id Name Salary
3 C 604
4 D 705
5 E 606
6 F NULL
1. Count Total Number of Employees
SELECT COUNT(*) AS TotalEmployees FROM Employee;
Output:
TotalEmployees
2. Calculate Total Salary
SELECT SUM(Salary) AS TotalSalary FROM Employee;
Output:
TotalSalary
3120
3. Find Average Salary
SELECT AVG(Salary) AS AverageSalary FROM Employee;
Output:
AverageSalary
624
4. Find Highest and Lowest Salary
SELECT MAX(Salary) AS HighestSalary FROM Employee;
Output:
HighestSalary
802
A mapping cardinality is a
data constraint that specifies
how many entities an entity
can be related to in a
relationship set.
Example: A student can only
work on two projects, the
number of students that
work on one project is not
limited.
A binary relationship set is a
relationship set on two entity
sets. Mapping cardinalities on
binary relationship
sets are simplest.
Consider a binary relationship
set R on entity sets A and B.
There are four possible
mapping cardinalities in this
case:
1. one-to-one - an entity in A is
related to at most one entity in
B, and an entity in B is related
to at most
one entity in A.
2. one-to-many - an entity in A
is related to any number of
entities in B, but an entity in B
is related to at
most one entity in A.
3. many-to-one - an entity in A
is related to at most one entity
in B, but an entity in B is
related to any
number of entities in A.
4. many-to-many - an entity in
A is related to any number of
entities in B, but an entity in B
is related to
any number of entities in A.
A mapping cardinality is a
data constraint that specifies
how many entities an entity
can be related to in a
relationship set.
Example: A student can only
work on two projects, the
number of students that
work on one project is not
limited.
A binary relationship set is a
relationship set on two entity
sets. Mapping cardinalities on
binary relationship
sets are simplest.
Consider a binary relationship
set R on entity sets A and B.
There are four possible
mapping cardinalities in this
case:
1. one-to-one - an entity in A is
related to at most one entity in
B, and an entity in B is related
to at most
one entity in A.
2. one-to-many - an entity in A
is related to any number of
entities in B, but an entity in B
is related to at
most one entity in A.
3. many-to-one - an entity in A
is related to at most one entity
in B, but an entity in B is
related to any
number of entities in A.
4. many-to-many - an entity in
A is related to any number of
entities in B, but an entity in B
is related to
any number of entities in A.