You are on page 1of 19

Department of Computer Science and Engineering

Course Title: Database Management System


Class/Semester: II-I CSE,CSE(AI&ML),CSE(DS)
Course Instructor: Dr T.V.S Sriram
Unit III: Structured Query Language
UNIT-3
SQL: Concept of different Database Languages over SQL - DDL, DML, DCL., Set operations, SQL
Commands, Nested queries, Aggregate Functions, Null Value, Referential Integrity Constraints, views,
Embedded SQL, Triggers, Cursors, Stored procedures, ODBC and JDBC.

SQL is a database language designed for the retrieval and management of data in a relational
database. ... Five types of SQL queries are

1) Data Definition Language (DDL)


2) Data Manipulation Language (DML)
3) Data Control Language(DCL)
4) Transaction Control Language(TCL)
5) Data Query Language (DQL)

Definition Language (DDL)

it is considered to be a subset of SQL (Structured Query Language). SQL often uses imperative verbs
with normal English such as sentences to implement database modifications. Hence, DDL does not
show up as a different language in an SQL database, but does define changes in the database
schema.

It is used to establish and modify the structure of objects in a database by dealing with descriptions of
the database schema. Unlike data manipulation language (DML) commands that are used for data
modification purposes, DDL commands are used for altering the database structure such as creating
new tables or objects along with all their attributes (data type, table name, etc.).

Commonly used DDL in SQL querying are CREATE, ALTER, DROP, and TRUNCATE.

Create
This command builds a new table and has a predefined syntax. The CREATE statement syntax is:

CREATE TABLE [table name] ([column definitions]) [table parameters];

For example:

CREATE TABLE Employee (Employee Id INTEGER PRIMARY KEY, First name CHAR (50) NULL,
Last name CHAR (75) NOT NULL);

The mandatory semi-colon at the end of the statement is used to process every command before it. In
this example, the string CHAR is used to specify the data type.
In this example, the string CHAR is used to specify the data type. Other data types can be DATE,
NUMBER, or INTEGER.

Alter
An alter command modifies an existing database table. This command can add up additional column,
drop existing columns and even change the data type of columns involved in a database table.

An alter command syntax is:

ALTER object type object name parameters;

For example:

ALTER TABLE Employee ADD PRIMARY KEY (employee_pk);

In this example, we added a unique primary key to the table to add a constraint and enforce a unique
value. The constraint “employee_pk” is a primary key and is on the Employee table.

Drop
A drop command is used to delete objects such as a table, index or view. A DROP statement cannot be
rolled back, so once an object is destroyed, there’s no way to recover it.

Drop statement syntax is:

DROP object type object name;

For example:

DROP TABLE Employee;

In this example, we’re deleting the Employee table.

Truncate
Similar to DROP, the TRUNCATE statement is used to quickly remove all records from a table.
However, unlike DROP that completely destroys a table, TRUNCATE preserves its full structure to be
reused later.

Truncate statement syntax is:

TRUNCATE TABLE table_name;

For example:

TRUNCATE TABLE Employee;

In this example, we’re marking all the extents of the Employee table for deallocation, so they’re
considered empty for reuse.
Other statements
Other commonly used commands include RENAME and COMMENT. The first one is used with the
ALTER TABLE statement to change the name of an object (table, column, etc.). COMMENT is used to
add single line, multi-line and in-line comments.

What Does Data Manipulation Language (DML) Mean?

A data manipulation language (DML) is a family of computer languages including commands permitting
users to manipulate data in a database. This manipulation involves inserting data into database tables,
retrieving existing data, deleting data from existing tables and modifying existing data. DML is mostly
incorporated in SQL databases. SELECT is the most widely used DML command in SQL.

SELECT: This command is used to retrieve rows from a table. The syntax is

SELECT [column name(s)] from [table name] where [conditions];

UPDATE: This command modifies data of one or more records. An update command syntax is

UPDATE [table name] SET [column name = value] where [condition];

INSERT: This command adds one or more records to a database table. The insert command syntax is

INSERT INTO [table name] [column(s)] VALUES [value(s)];

DELETE: This command removes one or more records from a table according to specified conditions.

Delete command syntax is

DELETE FROM [table name] where [condition];

Data Control Language(DCL):


• DCL is used to control user access in a database.
• This command is related to the security issues.
• Using DCL command, it allows or restricts the user from accessing data in database schema.
DCL commands are as follows,
1. GRANT
2. REVOKE
• It is used to grant or revoke access permissions from any database user.

1. GRANT COMMAND

• GRANT command gives user's access privileges to the database.


• This command allows specified users to perform specific tasks.
Syntax:
GRANT <privilege list>
ON <relation name or view name>
TO <user/role list>;

Example : GRANT Command

GRANT ALL ON employee


TO ABC;
[WITH GRANT OPTION]

In the above example, user 'ABC' has been given permission to view and modify the records in the
'employee' table.

2. REVOKE COMMAND

• REVOKE command is used to cancel previously granted or denied permissions.


• This command withdraw access privileges given with the GRANT command.
• It takes back permissions from user.
Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user name>;

Example : REVOKE Command

REVOKE UPDATE
ON employee
FROM ABC;

Difference between GRANT and REVOKE command.

GRANT REVOKE

GRANT command allows a user to perform REVOKE command disallows a user to perform
certain activities on the database. certain activities.

It grants access privileges for database objects to It revokes access privileges for database objects
other users. previously granted to other users.

Example: Example:

GRANT privilege_name REVOKE privilege_name


ON object_name ON object_name
TO
FROM
{ {
user_name|PUBLIC|role_name
} user_name|PUBLIC|role_name
}
[WITH GRANT OPTION];

Transaction Control Language(TCL)


• This command is used to manage the changes made by DML statements.
• TCL allows the statements to be grouped together into logical transactions.
TCL commands are as follows:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
4. SET TRANSACTION

1. COMMIT COMMAND

• COMMIT command saves all the work done.


• It ends the current transaction and makes permanent changes during the transaction.
Syntax:
commit;

2. SAVEPOINT COMMAND

• SAVEPOINT command is used for saving all the current point in the processing of a
transaction.
• It marks and saves the current point in the processing of a transaction.

Syntax:
SAVEPOINT <savepoint_name>

Example:
SAVEPOINT no_update;

• It is used to temporarily save a transaction, so that you can rollback to that point whenever
necessary.

3. ROLLBACK COMMAND

• ROLLBACK command restores database to original since the last COMMIT.


• It is used to restores the database to last committed state.
Syntax:
ROLLBACK TO SAVEPOINT <savepoint_name>;

Example:
ROLLBACK TO SAVEPOINT no_update;

4. SET TRANSACTION
• SET TRANSACTION is used for placing a name on a transaction.

Syntax:
SET TRANSACTION [Read Write | Read Only];

• You can specify a transaction to be read only or read write.


• This command is used to initiate a database transaction.

Difference between ROLLBACK and COMMIT commands.

ROLLBACK COMMIT
ROLLBACK command is used to undo the The COMMIT command is used to save the modifications
changes made by the DML commands. done to the database values by the DML commands.
It rollbacks all the changes of the current It will make all the changes permanent that cannot be
transaction. rolled back.
Syntax: Syntax:
DELETE FROM table_name ROLLBACK COMMIT;

Data Query Language (DQL)

Data Query Language (DQL) is part of the base grouping of SQL sub-languages. ... DQL
statements are used for performing queries on the data within schema objects. The purpose of DQL
commands is to get the schema relation based on the query passed to it. Although often considered
part of DML, the SQL SELECT statement is strictly speaking an example of DQL. When adding FROM
or WHERE data manipulators to the SELECT statement the statement is then considered part of the
DML.

SQL Set Operation

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation

1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
o In the union operation, all the number of datatype and columns must be same in both the tables
on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;

Example:

The First table

NAME

1 Jack

2 Harry

3 Jackson
The Second table

ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:

1. SELECT * FROM First


2. UNION
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David

2. Union All

Union All operation is equal to the Union operation. It returns the set without removing duplication and
sorting the data.

Syntax:

1. SELECT column_name FROM table1


2. UNION ALL
3. SELECT column_name FROM table2;

Example: Using the above First and Second table.


Union All query will be like:

1. SELECT * FROM First


2. UNION ALL
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the common rows
from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax

1. SELECT column_name FROM table1


2. INTERSECT
3. SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First


2. INTERSECT
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME
3 Jackson
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the rows
which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.

Syntax:

1. SELECT column_name FROM table1


2. MINUS
3. SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

1. SELECT * FROM First


2. MINUS
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

NESTED QUERY /SUB QUERIES/INNER QUERIES :

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause. A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
OR
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within
the WHERE clause.
OR
A subquery is used to return data that will be used in the main query as a condition to further restrict the
data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Types of SQL Subqueries
• Single Row Subquery. Returns zero or one row in results.
• Multiple Row Subquery. Returns one or more rows in results.
• Multiple Column Subqueries. Returns one or more columns.
• Correlated Subqueries. ...
• Nested Subqueries.

There are a few rules that subqueries must follow −


• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple columns are in
the main query for the subquery to compare its selected columns.
• An ORDER BY command cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY command can be used to perform the same function as the
ORDER BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value operators such
as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator
can be used within the subquery.
What is difference between subquery and nested query?
When a query is included inside another query, the Outer query is known as Main Query, and Inner
query is known as Subquery. In Nested Query, Inner query runs first, and only once. Outer query is
executed with result from Inner query. Hence, Inner query is used in execution of Outer query.
Difference between Nested Subquery, Correlated Subquery and Join Operation
Subquery
When a query is included inside another query, the Outer query is known as Main Query, and Inner
query is known as Subquery.

Nested Query –
In Nested Query, Inner query runs first, and only once. Outer query is executed with result from Inner
query.Hence, Inner query is used in execution of Outer query.
Example –
• Orders (OrderID, CustomerID, OrderDate);

Customers (CustomerID, CustomerName, ContactName, Country);


Find details of customers who have ordered.
SELECT * FROM Customers WHERE
CustomerID IN (SELECT CustomerID FROM Orders);
• Correlated Query –
In Correlated Query, Outer query executes first and for every Outer query row Inner query
is executed. Hence, Inner query uses values from Outer query.
Example –
• Orders (OrderID, CustomerID, OrderDate);

Customers (CustomerID, CustomerName, ContactName, Country);


Find details of customers who have ordered.
SELECT * FROM Customers where
EXISTS (SELECT CustomerID FROM Orders
WHERE Orders.CustomerID=Customers.CustomerID);
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

Now, let us check the following subquery with a SELECT statement.


SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY >4500);
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Types of SQL Aggregation Function

1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.

Syntax

1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30
Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()

Skip Ad
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 5
Com2 3
2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.

Syntax

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING


1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;

Output:

Com1 335
Com3 170
3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG function returns the
average of all non-Null values.

Syntax

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

Output:

67.00
4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines the largest
value of all selected values of a column.

Syntax

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function

MIN function is used to find the minimum value of a certain column. This function determines the smallest
value of all selected values of a column.

Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10
Most Important SQL Commands and Statements
1. Select Statement

2. Update Statement

3. Delete Statement

4. Create Table Statement

5. Alter Table Statement

6. Drop Table Statement

7. Create Database Statement

8. Drop Database Statement

9. Insert Into Statement

10. Truncate Table Statement

11. Describe Statement


12. Distinct Clause

13. Commit Statement


14. Rollback Statement
15. Create Index Statement
16. Drop Index Statement
17. Use Statement

Let's discuss each statement in short one by one with syntax and one example:

15. CREATE INDEX Statement

This SQL statement creates the new index in the SQL database table.

Syntax of CREATE INDEX Statement:

1. CREATE INDEX index_name


2. ON table_name ( column_name1, column_name2, …, column_nameN );

Example of CREATE INDEX Statement:

CREATE INDEX idx_First_Name

1. ON employee_details (First_Name);

This example creates an index idx_First_Name on the First_Name column of


the Employee_details table.

16. DROP INDEX Statement

This SQL statement deletes the existing index of the SQL database table.

Syntax of DROP INDEX Statement:DROP INDEX index_name;

Example of DROP INDEX Statement:DROP INDEX idx_First_Name;

This example deletes the index idx_First_Name from the SQL database.

17. USE Statement

This SQL statement selects the existing SQL database. Before performing the operations on the
database table, you have to select the database from the multiple existing databases.

Syntax of USE Statement:USE database_name;

Example of USE DATABASE Statement:

1. USE Company;

This example uses the company database.

NULL VALUES

What are null values ? How dbms deals with null values?
The fields can take on null values if they are not declared as not null. We can restrict the insertion of null
vales for the field declaring that field as not null. It means the field cannot take null values. For primary
key constraint, the field which is declared as primary key is also declared as not null. It is done implicitly
in DBMS.

EX: CREATE TABLE student ( sid NOT NULL ,


Snamechar(10) NOT NULL ,
Project varchar(15),
Class int,
Primary key (sid));
In this declaration , creation of student table , sid is the primary key hence it must be unique and it
should be not null. We can restrict entering null values in the field.

You might also like