Unit 2
Unit 2
SQL
SQL is a language to specify queries in structured manner.
Structured means relational data.
SQL is a language to specify queries in a relational database.
SQL is a standard language for accessing and manipulating databases.
IBM Sequel language developed as part of System R project at the IBM San
Jose Research Laboratory.
Renamed Structured Query Language (SQL).
SQL allows users to communicate with Relational Databases and retrieve
data from their table.
In database management systems like PostgreSQL, MySQL, Microsoft
SQL Server, Oracle Database and many others, SQL in DBMS is widely
used in these.
SQL
Characteristics of SQL
SQL in DBMS is a Domain-specific language:
Domain-specific language means it will only work with relational databases, because in a
relational database, the data is stored in the form of Tables or relations, and each table has rows
and columns.
SQL in DBMS is considered as the declarative language:
Declarative language basically tells what to do. like the simple query needs to be written which
will tell what to do and all the things will be taken care of by the database then.
SQL is an ANSI and ISO standard computer language for creating and manipulating databases.
ANSI- American National Standards Institute
ISO- International Organization for Standardization
SQL allows the user to create, update, delete, and retrieve data from a database.
SQL is very simple and easy to learn.
Advantages of SQL
Faster Query Processing –
• Large amount of data is retrieved quickly and efficiently. Operations like Insertion, deletion,
manipulation of data is also done in almost no time.
No Coding Skills –
• For data retrieval, large number of lines of code is not required. All basic keywords such as
SELECT, INSERT INTO, UPDATE, etc. are used and also the syntactical rules are not complex in
SQL, which makes it a user-friendly language.
Standardized Language –
• Due to documentation and long establishment over years, it provides a uniform platform
worldwide to all its users.
Advantages of SQL
Portable –
• It can be used in programs in PCs, server, laptops independent of any platform
(Operating System, etc). Also, it can be embedded with other applications as per
need/requirement/use.
Interactive Language –
• Easy to learn and understand, answers to complex queries can be received in
seconds.
Multiple data views –
• We can provide different views of contents of a database to different users.
Advantages of SQL
Data Integrity:
• SQL databases enforce data integrity by enforcing constraints such as unique
keys, primary keys, and foreign keys, which help prevent data duplication and
maintain data accuracy.
Backup and Recovery:
• SQL databases have built-in backup and recovery tools that help recover data in
case of system failures, crashes, or other disasters.
Data Consistency:
• SQL databases ensure consistency of data across multiple tables through the use
of transactions, which ensure that changes made to one table are reflected in all
related tables.
Database Management Unit 2
Department of Computer Engineering, ZCOER, Pune
Disadvantages of SQL
Cost – Some versions are costly and hence, programmers cannot access it.
Difficulty in Interfacing: Interfacing an SQL database is more complex than adding a
few lines of code.
Complexity: SQL databases can be complex to set up and manage, requiring skilled
database administrators to ensure optimal performance and maintain data integrity.
varchar(n): A VARIABLE length string (can contain letters, numbers, and special
characters). The size parameter specifies the maximum string length in characters - can be
from 0 to 65535.
Time: it is used to specify the time format. Its format is hh:mm:ss. Its supported range is
from '-838:59:59' to '838:59:59'
SQL Literals
A literal is a source code representation of a specific data value.
There are several types of SQL literals –
strings, integers, decimal numbers and date and time values.
String Literal: String literals are always in single quotes (‘).
E.g. 'Hello, world!’
Integer Literal: Integer literals can be both positive and negative numbers, but they
cannot contain decimal fractions.
E.g. 435, +435, -435
SQL Literals
Decimal Literal: Decimal literals can be both positive and negative numbers and
contain decimal fractions.
E.g. 43.5, +43.5, -43.5
Date and Time Literal: symbolic representations of date and time values enclosed in
single quote.
E.g. 'May 09, 2019’, '2019/05/09’, '2019/05/09 10:47:33'
SQL
SQL commands mainly categorized into five categories as:
1. DDL – Data Definition Language
2. DML – Data Manipulation Language
3. DCL – Data Control Language
4. TCL – Transaction Control Language
DDL
Data Definition Language
DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
All the command of DDL are auto-committed that means it permanently save all the changes in the
database.
DDL
List of DDL commands:
• CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
• DROP: It is used to delete both the structure and record stored in the table.
• ALTER: This is used to alter the structure of the database.
Alter command is helpful to change or modify the structure of the database or its object.
• TRUNCATE: This is used to remove all records from a table, including all spaces allocated
for the records are removed.
• RENAME: This is used to rename an object existing in the database.
CREATE:
It is used to create database,tables.
his command is used to create a new table in SQL. The user has to give information like
table name, column names, and their datatypes.
Syntax: CREATE DATABASE DATABASE_NAME;
CRAETE DATABASE STUDENT;
DROP:
This command is used to remove an existing table along with its structure
from the Database.
TRUNCATE:
It is used to delete all the rows from the table and free the space containing the table.
Syntax: TRUNCATE TABLE table_name;
Example: TRUNCATE TABLE EMPLOYEE;
RENAME:
RENAME command is used to set a new name for any existing table.
Following is the syntax,
Syntax:
RENAME TABLE old_table_name to new_table_name
Example:
RENAME TABLE student to students_info;
The above query will rename the table student to students_info.
ALTER:
It is used to alter the structure of the database. This change could be either to modify the
characteristics of an existing attribute or probably to add a new attribute.
To add a new column in the table
• Syntax: ALTER TABLE table_name ADD column_name COLUMN-definition;
• Example: ALTER TABLE STUDENT_DETAILS ADD(ADDRESS VARCHAR2(20));
DML
Data Manipulation Language
• DML commands are used to modify the database. It is responsible for all form of changes
in the database.
• The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
• Here are some commands that come under DML:
• SELECT
• INSERT
• UPDATE
• DELETE
UPDATE:
This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]
For example:
UPDATE students SET User_Name = ’ABC' WHERE Student_Id = '3'
DELETE
Delete command is used to delete records from a database table.
The syntax for the delete command is as follows –
Syntax:
Delete from <table_name>WHERE condition;
Example
DELETE from Employee WHERE Emp_id=002;
SELECT:
Select command is used to retrieve data from the database.
Display all records:
Syntax: SELECT * FROM TABLE_NAME;
Example: select * from student;
DCL
DCL
Grant:
It is used to give user access privileges to a database.
Syntax: GRANT SELECT, UPDATE,
DELETE,INSERT ON MY_TABLE TO SOME_USER, ANOTHER_USER;
Example: GRANT SELECT, INSERT ON STUDENT TO RADHIKA;
• Revoke:
• It is used to take back permissions from the user.
• Syntax: REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
• Example: REVOKE SELECT, INSERT ON STUDENT TO RADHIKA;
Commit
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these
commands are not permanent, until the current session is closed, the changes made by these
commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Rollback
This command restores the database to last committed state.
If we have used the UPDATE command to make some changes into the database, and realize that
those changes were not required, then we can use the ROLLBACK command to rollback those
changes, if they were not committed using the COMMIT command.
Savepoint
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
SQL operators
An operator is a reserved word or a character.
These Operators are used to specify conditions in an SQL statement and to serve as
conjunctions for multiple conditions in a statement.
1. Arithmetic operators
2. Bitwise operators
3. Comparison operators
4. Logical operators
Arithmetic Operators
Bitwise Operators
Comparison Operators
Logical Operators
Logical Operators
ID NAME SCORE
1 NINJA_1 23
2 NINJA_2 43
3 NINJA_3 21
4 NINJA_4 43
5 NINJA_5 10
Constraints
SQL Constraints are rules used to limit the type of data that can go into a table, to maintain the
accuracy and integrity of the data inside table.
Constraints are used to make sure that the integrity of data is maintained in the database.
Constraints can be divided into the following two types,
1. Column level constraints: Limits only column data.
2. Table level constraints: Limits whole table data.
Following are the most used constraints that can be applied to a table.
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
Unique Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of
columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
UNIQUE Constraint on CREATE TABLE
• For Single Column:
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
Unique Constraint
For Multiple columns:
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns,
use the following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
Unique Constraint
UNIQUE Constraint on ALTER TABLE
For one Column:
To create a UNIQUE constraint on the "ID" column when the table is already created, use the
following SQL:
Syntax: alter table table_name add unique(column_name);
Example: ALTER TABLE Persons ADD UNIQUE (ID);
Unique Constraint
• DROP a UNIQUE Constraint:
• To drop a Single UNIQUE constraint, use the following SQL:
Syntax: alter table table_name drop index column_name;
Example: ALTER TABLE Persons DROP INDEX age;
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
1 xyz 30 1 77895 3
2 pqr 20 2 44678 3
3 22456 2
3 abc 25
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
Check Constraint
CHECK constraint is used to restrict the value of a column between a range.
It performs check on the values, before storing them into the database. Its like condition checking before
saving data into a column.
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.
CHECK on CREATE TABLE
For single column:
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created.
The CHECK constraint ensures that the age of a person must be 18, or older:
Example: CREATE TABLE Persons (
ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age
int CHECK (Age>=18));
Check Constraint
For Multiple Column:
• To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax
Example:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
Check Constraint
CHECK on ALTER TABLE
For single column:
• To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
Example: ALTER TABLE Persons ADD CHECK (Age>=18);
Check Constraint
DROP a CHECK Constraint:
• To drop a CHECK constraint, use the following SQL:
Example:
ALTER TABLE Persons DROP CHECK CHK_PersonAge;
Default Constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
Default Constraint
DEFAULT on ALTER TABLE
• To create a default constraint on the city column when the table is already used of the following
SQL:
Example:
ALTER TABLE Persons ALTER City SET DEFAULT 'Sandnes';
Sub Query
• Writing a query inside another query is known as nested query or subquery.
• The inner query gets executed first, then output of an inner query is given as input to another
query.
• It is embedded in the HAVING or WHERE clause of the SQL statements.
Following are the important rules which must be followed by the SQL Subquery:
1. The SQL subqueries can be used with the following statements along with the SQL expression
operators:
• SELECT statement,
• UPDATE statement,
• INSERT statement, and
• DELETE statement.
Sub Query
2. The subqueries in SQL are always enclosed in the parenthesis and placed on the right side of
the SQL operators.
3. We cannot use the ORDER BY clause in the subquery. But, we can use the GROUP BY clause,
which performs the same function as the ORDER BY clause.
4. If the subquery returns more than one record, we have to use the multiple value operators before
the Subquery.
5. We can use the BETWEEN operator within the subquery but not with the subquery.
Sub Query
Example
Consider the CUSTOMERS table having the following records
−
ID
ID NAME
NAME AGE
AGE ADDRESS
ADDRESS SALARY
SALARY
12 Ramesh
Khilan 35
25 Ahmedaba
Delhi 2000.00
1500.00 SELECT * FROM CUSTOMERS WHERE
d
ID IN (SELECT ID FROM CUSTOMERS
3 kaushik 23 Kota 2000.00
2 Khilan 25 Delhi 1500.00 WHERE SALARY > 4500) ;
4 Chaitali 25 Mumbai 6500.00
3 kaushik 23 Kota 2000.00
Output:
6 Komal 22 MP 4500.00
4 Chaitali 25 Mumbai 6500.00
7 Muffy 24 Indore 10000.00 ID NAME AGE ADDRESS SALARY
5 Hardik 27 Bhopal 8500.00
4 Chaitali 25 Mumbai 6500.00
6 Komal 22 MP 4500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00
7 Muffy 24 Indore 10000.00
Sub Query
2. Subqueries with the INSERT Statement:
• Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table.
• The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
• Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
Sub Query
3. Subqueries with the UPDATE Statement:
• The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
• The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
• Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The
following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
Sub Query
3. Subqueries with the UPDATE Statement:
Output
Table: Customer:
Sub Query
4. Subqueries with the DELETE Statement
• The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
• The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
• Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS
table. The following example deletes the records from the CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27.
Sub Query
4. Subqueries with the DELETE Statement
Output:
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Employee
Group By single column: Group By single column is used to place all
Sr. No. Name Age Salary the rows with the same value. These values are of that specified
column in one group. It signifies that all rows will put an equal amount
through a single column, which is of one appropriate column in one
1 Jaydip 24 25000
group.
Consider the below query:
2 Nikita 22 22000 SELECT NAME, SUM (SALARY) FROM Employee
GROUP BY NAME;
3 Athrava 25 15000
The output of the query is:
4 Nikita 22 22000
Name Salary
Employee
SELECT NAME, SUM(SALARY) FROM Employee
Sr. No. Name Age Salary GROUP BY NAME
HAVING SUM(SALARY)>45000;
1 Jaydip 24 25000
The output of the query is:
2 Nikita 22 22000
Name Salary
3 Athrava 25 15000 Jaydip 50000
4 Nikita 22 22000
5 Jaydip 24 25000
The following is the syntax to use the ORDER BY clause in a SQL statement:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
Athrava 25 35000
Index
• Indexing is a data structure technique which allows you to quickly retrieve records from a
database file.
• An Index is an ordered list of contents of a column, (or a group of columns) of a table.
• By indexing we can improve the speed of searching and retrieving the record from table.
Index is created on one or more columns. Based on the number of columns included in the index,
an index can be:
• Simple index
• Composite Index
• Syntax:
CREATE INDEX <IndexName> ON <TableName> (<ColumnName>);
Index
Creating Composite Index
• An index created on more than one column is called a Composite Index.
The syntax for creating a composite index that allows duplicate values is:
• syntax:
CREATE INDEX <Index Name> ON <Table Name> (<ColumnNamel> <ColumnName2>);
Eg. create index index2 on student_details(Name, Class);
Index
Creation of Unique index
• A unique index can also be created on one or more columns. If an index is created on a
single column, it is called a Simple Unique Index. The syntax for creating a simple unique
index is as follows:
• Syntax:
CREATE UNIQUE INDEX <Index Name> ON <Table Name> (<Column Name>);
• If an index is created on more than one column, it is called a Composite Unique Index. The
syntax for creating a composite unique index is as follows:
CREATE UNIQUE INDEX <Index Name> ON <Table Name> (<Column Name>, <Column Name>);
Sequence
• Sequence is a feature supported by some database systems to produce unique values on
demand.
• Some DBMS like MySQL supports AUTO_INCREMENT in place of Sequence.
• AUTO_INCREMENT is applied on columns, it automatically increments the column value by 1
each time a new record is entered into the table.
View
A View in SQL as a logical subset of data from one or more tables.
Views are used to restrict data access.
A View contains no data of its own but its like window through which data from tables can be viewed
or changed.
The table on which a View is based are called BASE Tables.
Complex views can be constructed on more than one base table. In particular, complex views can
contain: join conditions, a group by clause, a order by clause.
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single table or
multiple tables.
Syntax: Student_Detail
CREATE VIEW view_name AS
SELECT column1, column2..... STU_ID NAME ADDRESS
FROM table_name 1 RIYA Delhi
WHERE condition;
2 KARTIK Noida
Example 1: 3 PAYAL Ghaziabad
CREATE VIEW DetailsView AS 4 SUNNY Gurugram
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;
STU_ID NAME ADDRESS
we can query the view to view the data:- 1 RIYA Delhi
2 KARTIK Noida
SELECT * FROM DetailsView;
3 PAYAL Ghaziabad
Example 2:
create view vw_student_details as(select RollNo,Name from student_details);
2. Dropping view
A view can be deleted using the Drop View statement.
Syntax
DROP VIEW view_name;
3. Updating view
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Set Operations
The SQL Set operation is used to combine the two or more SQL SELECT statements.
Union
• The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
• 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.
• The union operation eliminates the duplicate rows from its resultset.
Syntax:
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
1 Riya 3 Tanvee
2 Vijaya 4 Sejal
3 Tanvee 5 Pooja
ID Name
Union SQL query will be:
SELECT * FROM First 1 Riya
UNION
SELECT * FROM Second; 2 Vijaya
5 Pooja
Union All
• Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;
2 Vijaya 4 Sejal
3 Tanvee 5 Pooja
ID Name
1 Riya
Union ALL SQL query will be:
2 Vijaya
SELECT * FROM First
UNION ALL 3 Tanvee
SELECT * FROM Second;
3 Tanvee
5 Pooja
Intersect
• It is used to combine two SELECT statements. The Intersect operation returns the common rows
from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the same.
• It has no duplicates and it arranges the data in ascending order by default.
Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
2 Vijaya 4 Sejal
3 Tanvee 5 Pooja
Minus
• 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.
• It has no duplicates and data arranged in ascending order by default.
Syntax
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
2 Vijaya 4 Sejal
3 Tanvee 5 Pooja
Predicates
• Predicates are keywords that specify a relationship between two expressions.
• A Predicate in DBMS is a condition expression which evaluates and results in Boolean value
either true or false which enables decision making in retrieving and manipulating a record.
Example
select empno,job,sal,hiredate from emp where [ename in('SCOTT','FORD','SMITH','JONES')];
Output:
• The details of those employees
whose salary is present in the range
between 800/- to 2900/- are
retrieved and it also considers
specified values inclusive of the
range.
Output:
Output:
Output:
Join
• In case of SQL, JOIN means "to combine two or more tables".
• The SQL JOIN clause takes records from two or more tables in a database and combines it
together.
Inner Join
The INNER JOIN keyword selects all rows from both the tables as long as the condition
satisfies. This keyword will create the result-set by combining all rows from both the tables where
the condition satisfies i.e., value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;
EMPLOYEE PROJECT
Output
Left Join
This join returns all the rows of the table on the left side of the join and matching rows for the
table on the right side of join. The rows for which there is no matching row on right side, the
result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1
LEFT JOIN table2 ON table1.matching_column = table2.matching_column;
EMPLOYEE PROJECT
Output
Right Join
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and
matching rows for the table on the left side of join. The rows for which there is no matching row on left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1
RIGHT JOIN table2 ON table1.matching_column = table2.matching_column;
EMPLOYEE PROJECT
Output
Full Join
FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN. The result-set will
contain all the rows from both the tables. The rows for which there is no matching, the result-set will
contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 FULL JOIN table2 ON
table1.matching_column = table2.matching_column;
EMPLOYEE PROJECT
Output
Set Membership
SQL allows testing tuples for membership in a relation.
use the in and not in operations for set membership
IN Operator
It is used to avoid multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
expression IN (value1, value2, .... value_n);
oexpression: It specifies a value to test.
o value1, value2,.. value_n: It specifies the values to test against expression.
Example
SELECT * FROM Students
WHERE Students IN (‘Aditee', ‘Vijaya', ‘Tanvee’);
OR
SELECT * FROM Students
WHERE name = ‘Aditee’ OR name = ‘Vijaya' OR name = ‘Tanvee’;
NOT IN Operator
Syntax
expression NOT IN (value1, value2, .... value_n);
oexpression: It specifies a value to test.
o value1, value2,.. value_n: It specifies the values to test against expression.
Example
SELECT * FROM Students
WHERE Students NOT IN (‘Aditee', ‘Vijaya', ‘Tanvee’);
Example:
Student table:
Aggregation Functions
• SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
• It is also used to summarize the data.
• Types of SQL Aggregation Function:
1. count()
2. sum()
3. avg()
4. max()
5. min()
count()
• 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.
• COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.
Syntax:
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
• Example:
STUDENT
Roll No Name Age Address
1. SELECT COUNT(*) FROM STUDENT;
1 A 15 Nashik
Output: 7
2 B 16 Pune
3 C 18 Mumbai
2. SELECT COUNT(*) FROM STUDENT;
4 D 12 Pune WHERE AGE>=18;
5 E 19 Nashik Output: 3
6 F 21 Nashik
7 G 17 Aurangabad
sum()
• Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
• Syntax:
SUM()
or
SUM( [ALL|DISTINCT] expression )
• Example:
SELECT SUM(COST) FROM PRODUCT;
• Example:
PRODUCT
2 B 3 16 35 Output: 555
6 F 2 21 75
7 G 3 17 100
avg()
• 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:
AVG()
or
AVG( [ALL|DISTINCT] expression )
• Example:
SELECT AVG(COST) FROM PRODUCT;
• Example:
PRODUCT
4 D 1 12 45
5 E 2 19 120
6 F 2 21 75
7 G 3 17 100
max()
• 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:
MAX()
or
MAX( [ALL|DISTINCT] expression )
• Example:
SELECT MAX(RATE) FROM PRODUCT;
• Example:
PRODUCT
2 B 3 16 35 Output: 21
3 C 4 18 160
4 D 1 12 45
5 E 2 19 120
6 F 2 21 75
7 G 3 17 100
min()
• 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:
MIN()
or
MIN( [ALL|DISTINCT] expression )
• Example:
SELECT MIN(COST) FROM PRODUCT;
• Example:
PRODUCT
2 B 3 16 35 Output: 20
3 C 4 18 160
4 D 1 12 45
5 E 2 19 120
6 F 2 21 75
7 G 3 17 100
Built-in Functions
Numeric Functions
Numeric Functions are used to perform operations on numbers and return numbers.
1. ABS(): It returns the absolute value of a number.
Syntax: SELECT ABS(-243.5);
Output: 243.5
2. ACOS(): It returns the cosine of a number. The specified number must be between -1 to 1, otherwise this function
returns NULL.
Syntax: SELECT ACOS(0.25);
Output: 1.318116071652818
OR
6. CEILING(): It returns the smallest integer value that is >= to a number.
Syntax: SELECT CEILING(25.75);
Output: 26
11. FLOOR(): It returns the largest integer value that is <= to a number.
Syntax: SELECT FLOOR(25.75);
Output: 25
13. LOG(): Return the natural logarithm of a number or the logarithm of a number to a specified base.
Syntax: Select Log(2);
Output: 0.693147
String Functions
String Functions are used to perform an operation on input string and return an output string.
1. ASCII(): This function is used to find the ASCII value of a character.
Syntax: SELECT ascii('t’);
Output: 116
4. CONCAT_WS(): This function is used to add two words or strings with a symbol as concatenating symbol.
Syntax: SELECT CONCAT_WS('_', ‘hello', ‘world’);
Output: hello_world
7. LOWER(): This function is used to convert the upper case string into lower case.
Syntax: SELECT LOWER(‘HELLOWORLD’);
Output: helloworld
8. REPEAT(): This function is used to write the given string again and again till the number of
times mentioned.
Syntax: SELECT REPEAT(‘hello', 2);
Output: hellohello
10. SUBSTR(): This function is used to find a sub string from the a string from the given position.
Syntax: SUBSTR('geeksforgeeks', 1, 6);
Output: ‘geeksf’
PL/ SQL
PL/SQL stands for Procedural Language extensions to the Structured Query
Language (SQL).
PL/SQL is a combination of SQL along with the procedural features of
programming languages.
Oracle uses a PL/SQL engine to processes the PL/SQL statements.
PL/SQL includes procedural language elements like conditions and loops.
It allows declaration of constants and variables, procedures and functions, types
and variable of those types and triggers.
Error handling :
PL/SQL is dealing with error handling, It's permits the smart way handling the errors and
giving user friendly error messages, when the errors are encountered.
Portable application:
Applications are written in PL/SQL are portable in any Operating system. PL/SQL
applications are independence program to run any computer.
PL/ SQL
Features of PL/SQL:
PL/SQL is basically a procedural language, which provides the functionality of
decision making, iteration and many more features of procedural programming
languages.
PL/SQL can execute a number of queries in one block using single command.
One can create a PL/SQL unit such as procedures, functions, packages, triggers,
and types, which are stored in the database for reuse by applications.
PL/SQL provides a feature to handle the exception which occurs in PL/SQL block
known as exception handling block.
Applications written in PL/SQL are portable to computer hardware or operating system
where Oracle is operational.
PL/SQL Offers extensive error checking.
PL/SQL Concepts:
Cursors, Stored Procedures, Stored Functions, Database Triggers.
The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which
can be nested within each other.
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
Output:
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
Types of Variables
• A variable is a meaningful name which facilitates a programmer to store data temporarily
during the execution of code.
• It helps you to manipulate data in PL/SQL programs.
• It is nothing except a name given to a storage area.
• Each variable in the PL/SQL has a specific data type which defines the size and layout of the
variable's memory.
3. For Loop
LOOP
<statements>
EXIT WHEN <condition>;
END LOOP
DECLARE
n number(5) : = 1;
sum number(5) : = 0;
BEGIN OUTPUT:
Loop
sum : = sum + n; sum of first 50 numbers is 1275
n : = n+1;
Exit when n > 50; PL/SQL procedure successfully
End loop; completed.
dbms_output.put_line(‘sum of first 50 numbers is’||sum);
END;
/
Cursor
Context area:
When processing an SQL statement, Oracle creates a temporary work area in the system
memory which contains all the information needed for processing the statement known
as context area.
Cursor:
A cursor is a pointer to context area i.e. Context area is controlled by the cursor. It is
used to fetch and manipulate the data returned by the SQL statement.
Note: The set of rows the cursor holds is known as active set.
A cursor is a pointer to the work area or context area, used by the oracle engine
for executing SQL statements.
Types of cursors:
1. Implicit cursors.
2. Explicit cursors.
Implicit Cursor
Implicit Cursor
• The cursor which is automatically created, maintained and closed by the Oracle engine while
execution of any DML(Data Manipulation Language) queries like INSERT, UPDATE or DELETE are
called Implicit Cursor.
• Implicit Cursors are controlled by Oracle and programmers cannot access its information.
• When a DML statement is executed an implicit cursor is created and attached to it.
• Following are the Implicit Cursor Attributes
Explicit Cursor
Explicit Cursor
• Explicit cursors are the user defined cursors to gain more control over the context area.
• The cursor which has to be created, maintained and closed by a program through PL/SQL code for
the execution of any SELECT query that returns more than one row is called Explicit Cursor.
• It is a user-defined cursor declared in the Declare section of PL/SQL block and is used in its
Executable section.
• Syntax for creating an explicit cursor:
• CURSOR cursor_name IS select_statement;
Example:
CURSOR cur_students IS
SELECT rollNo, name, address FROM students;
2. Open Cursor:
After declaring the cursor the next step is to open the cursor using open statement.
Syntax: Open cursor_name;
Example:
Open cur_students;
Example:
4. Close Cursor
The final step is to close the cursor.
Syntax: Close cursor_name;
Stored Procedure
Stored Procedures are created to perform one or more DML operations on Database.
It is nothing but the group of SQL statements that accepts some input in the form of parameters and
performs some task and may or may not returns a value.
Syntax : Creating a Procedure
CREATE or REPLACE PROCEDURE name(parameters)
IS
variables;
BEGIN
//statements;
END;
Stored Procedure
There are 3 different types of parameters, they are as follows:
IN:
• This is the Default Parameter for the procedure. It always receives the values from calling
program.
• A parameter whose value is passed into a stored procedure/function module.
• The value of an IN parameter is a constant; it can't be changed or reassigned within the module.
OUT:
• This parameter always sends the values to the calling program.
• A parameter whose value is passed out of the stored procedure/function module, back to the calling
PL/SQL block. An OUT parameter must be a variable, not a constant.
IN OUT:
This parameter performs both the operations. It Receives value from as well as sends the values to
the calling program.
Database Trigger
Triggers in oracle are blocks of PL/SQL code which oracle engine can execute automatically based
on some action or event.
A trigger is a stored procedure in database which automatically invokes whenever a special event in
the database occurs. For example, a trigger can be invoked when a row is inserted into a specified
table or when certain table columns are being updated.
Triggers are automatically and repeatedly called upon by oracle engine on satisfying certain
condition.
Database Trigger
Syntax:
create trigger [trigger_name] [before | after] {insert | update | delete} on [table_name] [for each row]
[trigger_body]
Explanation of syntax:
1.create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
2.[before | after]: This specifies when the trigger will be executed.
3.{insert | update | delete}: This specifies the DML operation.
4.on [table_name]: This specifies the name of the table associated with the trigger.
5.[for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected.
6.[trigger_body]: This provides the operation to be performed as trigger is fired
Example of Trigger
Example: Write a database trigger on Library table. The System should keep track of the records that
are being updated or deleted. The old value of updated or deleted records should be added in
Library_Audit table.
Program:
delimiter //
create trigger tr_ins77_Borrower
before insert
on table1
for each row
begin
insert into table2 values(new.rollno,new.name,new.nameofbook);
end
//
Output: Table2:
mysql> insert into table1 values(1,'gg','ggh');
rollno name nameofbook
-> //
Query OK, 1 row affected (0.06 sec) 1 gg ggh
mysql> select * from table2;
-> //
Database Management Unit 2
Thank You !!!