You are on page 1of 156

Unit 2

SQL and PL/SQL


Dr. Nikita Kulkarni
No. of hours: 06
Lecture No. Topic & Contents Planned
7 SQL: Characteristics and advantages, SQL Data Types and Literals, DDL, DML, DCL, TCL, SQL
Operators
8 Tables: Creating, Modifying, Deleting, Updating,
9 SQL DML Queries: SELECT Query and clauses, Index and Sequence in SQL
10 Views: Creating, Dropping, Updating using Indexes, Set Operations, Predicates and Joins, Set
membership
11 Tuple Variables, Set comparison, Ordering of Tuples, Aggregate Functions, SQL Functions,
Nested Queries
12 PL/SQL: Concept of Stored Procedures & Functions, Cursors
13 Triggers, Assertions, Roles and Privileges
SQL
• SQL is Structured Query Language, which is a computer
language for storing, manipulating and retrieving data stored in
a relational database.
• SQL is the standard language for Relational Database System.
All the Relational Database Management Systems (RDMS) like
MySQL, MS Access, Oracle, Sybase, Informix, Postgres and
SQL Server use SQL as their standard database language.
• Also, they are using different dialects, such as −
• MS SQL Server using T-SQL,
• Oracle using PL/SQL,
• MS Access version of SQL is called JET SQL (native format) etc.
Applications of SQL
• SQL is one of the most widely used query language over the
databases. I'm going to list few of them here:
• Allows users to access data in the relational database management
systems.
• Allows users to describe the data.
• Allows users to define the data in a database and manipulate that data.
• Allows to embed within other languages using SQL modules, libraries &
pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in a database.
• Allows users to set permissions on tables, procedures and views.
A Brief History of SQL
• 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of
relational databases. He described a relational model for
databases.
• 1974 − Structured Query Language appeared.
• 1978 − IBM worked to develop Codd's ideas and released a
product named System/R.
• 1986 − IBM developed the first prototype of relational database
and standardized by ANSI. The first relational database was
released by Relational Software which later came to be known
as Oracle.
SQL Process
• When you are executing an SQL command
for any RDBMS, the system determines the
best way to carry out your request and SQL
engine figures out how to interpret the task.
• There are various components included in
this process.
• These components are −
• Query Dispatcher
• Optimization Engines
• Classic Query Engine
• SQL Query Engine, etc.
• A classic query engine handles all the non-
SQL queries, but a SQL query engine won't
handle logical files.
• Following is a simple diagram showing the
SQL Architecture −
What is RDBMS?
• RDBMS stands
for Relational Database Management System. RDBMS
is the basis for SQL, and for all modern database
systems like MS SQL Server, IBM DB2, Oracle,
MySQL, and Microsoft Access.
• A Relational database management system (RDBMS)
is a database management system (DBMS) that is
based on the relational model as introduced by E. F.
Codd.
• What is a table?
• The data in an RDBMS is stored in database objects
which are called as tables. This table is basically a
collection of related data entries and it consists of
numerous columns and rows.
• Remember, a table is the most common and simplest
form of data storage in a relational database. The
following program is an example of a CUSTOMERS
table −
• What is a field?
• Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table
consist of ID, NAME, AGE, ADDRESS and SALARY.
• A field is a column in a table that is designed to maintain specific information about every record in
the table.
• What is a Record or a Row?
• A record is also called as a row of data is each individual entry that exists in a table. For example,
there are 7 records in the above CUSTOMERS table. Following is a single row of data or record in
the CUSTOMERS table −

• A record is a horizontal entity in a table.


• What is a column?
• A column is a vertical entity in a table that contains all information associated with a specific field in
a table.
• For example, a column in the CUSTOMERS table is ADDRESS, which represents location
description and would be as shown below −
• What is a NULL value?
• A NULL value in a table is a value in a field that appears to be blank, which means a field
with a NULL value is a field with no value.
• It is very important to understand that a NULL value is different than a zero value or a field
that contains spaces. A field with a NULL value is the one that has been left blank during
a record creation.
• SQL Constraints
• Constraints are the rules enforced on data columns on a table. These are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data
in the database.
• Constraints can either be column level or table level. Column level constraints are applied
only to one column whereas, table level constraints are applied to the entire table.
• Following are some of the most commonly used constraints available in SQL −
• NOT NULL Constraint − Ensures that a column cannot have a NULL value.
• DEFAULT Constraint − Provides a default value for a column when none is specified.
• UNIQUE Constraint − Ensures that all the values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database table.
• FOREIGN Key − Uniquely identifies a row/record in any another database table.
• CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain
conditions.
• INDEX − Used to create and retrieve data from the database very quickly.
Data Integrity
• The following categories of data integrity exist with each
RDBMS −
• Entity Integrity − There are no duplicate rows in a table.
• Domain Integrity − Enforces valid entries for a given column by
restricting the type, the format, or the range of values.
• Referential integrity − Rows cannot be deleted, which are used by
other records.
• User-Defined Integrity − Enforces some specific business rules that
do not fall into entity, domain or referential integrity.
SQL - Data Types
• SQL Data Type is an attribute that specifies the type of data of any object.
Each column, variable and expression has a related data type in SQL. You
can use these data types while creating your tables. You can choose a
data type for a table column based on your requirement.
• SQL Server offers six categories of data types for your use which are listed
below −
1. Exact Numeric Data Types
2. Approximate Numeric Data Types
3. Date and Time Data Types
4. Character Strings Data Types
5. Unicode Character Strings Data Types
6. Binary Data Types
• Misc Data Types
Exact Numeric Data Types
Approximate Numeric Data Types

Date and Time Data Types


Character Strings Data Types

Unicode Character Strings Data Types


Binary Data Types

Misc Data Types


Operators
• What is an Operator in SQL?
• An operator is a reserved word or a character used primarily in
an SQL statement's WHERE clause to perform operation(s),
such as comparisons and arithmetic operations. These
Operators are used to specify conditions in an SQL statement
and to serve as conjunctions for multiple conditions in a
statement.
• Arithmetic operators
• Comparison operators
• Logical operators
• Operators used to negate conditions
SQL Arithmetic Operators
• Assume 'variable a' holds 10 and 'variable b' holds 20, then −
SQL Comparison Operators
• Assume 'variable a' holds 10 and 'variable b' holds 20, then −
SQL Logical Operators
CREATE Database
• The SQL CREATE DATABASE statement is used to create a new SQL database.
• Syntax
CREATE DATABASE DatabaseName;
• Always the database name should be unique within the RDBMS.
• Example
SQL> CREATE DATABASE testDB;
DROP or DELETE Database
• The SQL DROP DATABASE statement is used to drop an
existing database in SQL schema.
• Syntax
DROP DATABASE DatabaseName;
• Example
SQL> DROP DATABASE testDB;
SELECT Database, USE Statement
• When you have multiple databases in your SQL Schema, then before starting your operation, you
would need to select a database where all the operations would be performed.
• The SQL USE statement is used to select any existing database in the SQL schema.
• Syntax
USE DatabaseName;

SQL> USE AMROOD;


RENAME Database
• In some situations, database users and administrators want to
change the name of the database for some technical reasons. So,
the Rename Database statement in SQL is used to change the
name of the existing database.
• Sometimes, the Rename Database statement is used because the
developers think that the original name is not more relevant to the
data of the database, or they want to give a temporary name to that
database.
• Syntax
ALTER DATABASE old_database_name MODIFY NAME = new_data
base_name;
RENAME DATABASE old_database_name TO new_database_name;
• Example 1: Suppose we want to rename the Student
Database. For this, we have to type the following query in SQL:
ALTER DATABASE Student MODIFY NAME = College ;
RENAME DATABASE Student TO College
• Example 2: Suppose we want to rename the Department
Database. For this, we have to type the following query in SQL:
ALTER DATABASE Department MODIFY NAME = Company ;
RENAME DATABASE Department TO Company;
SELECT Database
• Suppose database users and administrators want to perform some
operations on tables, views, and indexes on the specific existing
database in SQL. Firstly, they have to select the database on which
they want to run the database queries.
• Any database user and administrator can easily select the particular
database from the current database server using the USE statement
in SQL.
• Syntax of USE statement in SQL
USE database_name;
In this syntax, we have to define the name of the database after
the USE keyword and the name of the database must be unique.
• Syntax of USE statement in MySQL
USE database_name;
• Example 1: Suppose, you want to work with
the Hospital database. For this firstly, you have to check that if
the Hospital database exists on the current database server or
not by using the following query:
SHOW DATABASES;
• If the Hospital database is shown in the output, then you have
to execute the following query to select the Hospital database:
USE Hospital;
CREATE Table
• Creating a basic table involves naming the table and defining its columns and
each column's data type.
• The SQL CREATE TABLE statement is used to create a new table.
• Syntax

• CREATE TABLE is the keyword telling the database system what you want to do.
In this case, you want to create a new table. The unique name or identifier for the
table follows the CREATE TABLE statement.
• Then in brackets comes the list defining each column in the table and what sort of
data type it is. The syntax becomes clearer with the following example.
• A copy of an existing table can be created using a combination of the CREATE
TABLE statement and the SELECT statement.
• Example
• The following code block is an example, which creates a
CUSTOMERS table with an ID as a primary key and NOT NULL
are the constraints showing that these fields cannot be NULL
while creating records in this table −
Topics of SQL TABLE Statement
• SQL TABLE Variable: What TABLE variable can do?
• SQL CREATE TABLE: How to create a table using SQL query>
• SQL DROP TABLE: How to drop a table?
• SQL DELETE TABLE: How to delete all the records of a table?
• SQL RENAME TABLE: How to rename a table?
• SQL TRUNCATE TABLE: How to truncate a table?
• SQL COPY TABLE: How to copy a table?
• SQL TEMP TABLE: What is temporary table? What are the advantage of temporary table?
• SQL ALTER TABLE: How to add, modify, rename and drop column.
DROP or DELETE Table
• The SQL DROP TABLE statement is used to remove a table
definition and all the data, indexes, triggers, constraints and
permission specifications for that table.
• NOTE − You should be very careful while using this command
because once a table is deleted then all the information
available in that table will also be lost forever.
• Syntax
DROP TABLE table_name;
• Example

• This means that the CUSTOMERS table is available in the data


SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)base, so let us now drop it
as shown below.
SQL> DESC CUSTOMERS;
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist
DELETE TABLE
• The DELETE statement is used to delete rows from a table. If
you want to remove a specific row from a table you should use
WHERE condition.
DELETE FROM table_name [WHERE condition];
• But if you do not specify the WHERE condition it will remove all
the rows from the table.
DELETE FROM table_name;
• There are some more terms similar to DELETE statement like
as DROP statement and TRUNCATE statement but they are not
exactly same there are some differences between them.
Difference between DELETE and
TRUNCATE statements
• There is a slight difference b/w delete and truncate statement.
The DELETE statement only deletes the rows from the table
based on the condition defined by WHERE clause or delete all
the rows from the table when condition is not specified.
• But it does not free the space containing by the table.
• The TRUNCATE statement: it is used to delete all the rows
from the table and free the containing space.
TRUNCATE TABLE employee;
Difference b/w DROP and TRUNCATE
statements
• When you use the drop statement it deletes the table's row
together with the table's definition so all the relationships of that
table with other tables will no longer be valid.
• When you drop a table:
• Table structure will be dropped
• Relationship will be dropped
• Integrity constraints will be dropped
• Access privileges will also be dropped
• On the other hand when we TRUNCATE a table, the table
structure remains the same, so you will not face any of the
above problems.
RENAME TABLE

• In some situations, database administrators and users want to


change the name of the table in the SQL database because
they want to give a more relevant name to the table.
• Any database user can easily change the name by using the
RENAME TABLE and ALTER TABLE statement in Structured
Query Language.
• The RENAME TABLE and ALTER TABLE syntax help in
changing the name of the table.
• Syntax:
RENAME old_table _name To new_table_name ;
Examples of RENAME statement in SQL
• Here, we have taken the following two different SQL examples, which will help you how to
change the name of the SQL table in the database using RENAME statement:
• Example 1: Let's take an example of a table named Cars:

• Table: Cars
• Suppose, you want to change the above table name into "Car_2021_Details". For this,
you have to type the following RENAME statement in SQL:
RENAME Cars To Car_2021_Details ;
• After this statement, the table "Cars" will be changed into table name "Car_2021_Details".
Syntax of ALTER TABLE statement in
SQL
ALTER TABLE old_table_name RENAME TO new_table_name;

• In the Syntax, we have to specify the RENAME TO keyword


after the old name of the table.
• Examples of ALTER TABLE statement in SQL
• Here, we have taken the following three different SQL
examples, which will help you how to change the name of the
table in the SQL database using ALTER TABLE statement:
• Example 1: Let's take an example of a table named Bikes:

• Table : Bikes
• Suppose, you want to change the name of the above table into
"Bikes_Details" using ALTER TABLE statement. For this, you have to type
the following query in SQL:
ALTER TABLE Bikes RENAME TO Bikes_Details ;
• After this statement, the table "Bikes" will be changed into the table name
"Bikes_Details".
TRUNCATE TABLE
• A truncate SQL statement is used to remove all rows (complete data) from
a table. It is similar to the DELETE statement with no WHERE clause.
• TRUNCATE TABLE Vs DELETE TABLE
• Truncate table is faster and uses lesser resources than DELETE TABLE command.
• TRUNCATE TABLE Vs DROP TABLE
• Drop table command can also be used to delete complete table but it deletes table
structure too. TRUNCATE TABLE doesn't delete the structure of the table.
• TRUNCATE TABLE table_name;
• For example, you can write following command to truncate the data of
employee table
TRUNCATE TABLE Employee;
• Note: The rollback process is not possible after truncate table statement.
Once you truncate a table you cannot use a flashback table statement to
retrieve the content of the table.
COPY TABLE
• If you want to copy the data of one SQL table into another SQL
table in the same SQL server, then it is possible by using the
SELECT INTO statement in SQL.
• The SELECT INTO statement in Structured Query Language
copies the content from one existing table into the new table.
SQL creates the new table by using the structure of the existing
table.
• Syntax of SELECT INTO statement in SQL
SELECT * INTO New_table_name FROM old_table_name;
Examples of SELECT INTO statement in
SQL
• In this article, we have taken the following three different SQL examples which will help you how to
copy the content of one table into another table in SQL:
• Example 1: In this example, we have a table called Cars with three columns:

Table: Cars

• Suppose you want to copy the content of the above Car table into the new table Car_Details. For this, you have to type the following query in SQL:
SELECT * INTO Car_Details FROM Cars;

• Let's check the Car_Details table is created successfully or not in the database:

SELECT * FROM Car_Details;

Table: Car_Details
TEMP TABLE
• The concept of temporary table is introduced by SQL server. It
helps developers in many ways:
• Temporary tables can be created at run-time and can do all
kinds of operations that a normal table can do. These temporary
tables are created inside tempdb database.
• There are two types of temp tables based on the behavior and
scope.
1.Local Temp Variable
2.Global Temp Variable
• Local Temp Variable
• Local temp tables are only available at current connection time.
It is automatically deleted when user disconnects from
instances. It is started with hash (#) sign.

• Global Temp Variable


• Global temp tables name starts with double hash (##). Once
this table is created, it is like a permanent table. It is always
ready for all users and not deleted until the total connection is
withdrawn.
ALTER TABLE
• The ALTER TABLE statement in Structured Query Language
allows you to add, modify, and delete columns of an existing
table. This statement also allows database users to add and
remove various SQL constraints on the existing tables.
• Any user can also change the name of the table using this
statement.
ALTER TABLE ADD Column statement in
SQL
• In many situations, you may require to add the columns in the existing table. Instead of creating a
whole table or database again you can easily add single and multiple columns using the ADD
keyword.
• Syntax of ALTER TABLE ADD Column statement in SQL
ALTER TABLE table_name ADD column_name column-definition;
• The above syntax only allows you to add a single column to the existing table. If you want to add
more than one column to the table in a single SQL statement, then use the following syntax:
• Examples of ALTER TABLE ADD Column statement in SQL
• Here, we have taken the following two different SQL examples,
which will help you how to add the single and multiple columns in the
existing table using ALTER TABLE statement:
• Example 1: Let's take an example of a table named Cars:

Table: Cars
• Suppose, you want to add the new column Car_Model in the above
table. For this, you have to type the following query in the SQL:
ALTER TABLE Cars ADD Car_Model Varchar(20);
• This statement will add the Car_Model column to the Cars table.
SQL SELECT
• The most commonly used SQL command is SELECT
statement. It is used to query the database and retrieve
selected data that follow the conditions we want.
• In simple words, we can say that the select statement used to
query or retrieve data from a table in the database.
• Let's see the syntax of select statement.

• Here expression is the column that we want to retrieve.


Optional clauses in SELECT statement
• There are some optional clauses in SELECT statement:
• [WHERE Clause] : It specifies which rows to retrieve.
• [GROUP BY Clause] : Groups rows that share a property so
that the aggregate function can be applied to each group.
• [HAVING Clause] : It selects among the groups defined by the
GROUP BY clause.
• [ORDER BY Clause] : It specifies an order in which to return
the rows.
For example, let a database table:
student_details;

• From the above example, select the first name of all the students. To do so, query
should be like this:
SELECT first_name FROM student_details;
• Note: the SQL commands are not case sensitive. We can also write the above SELECT
statement as:
select first_name from student_details;
• Now, you will get following data:
SELECT UNIQUE
• Actually, there is no difference between DISTINCT and UNIQUE.
• SELECT UNIQUE is an old syntax which was used in oracle
description but later ANSI standard defines DISTINCT as the official
keyword.
• After that oracle also added DISTINCT but did not withdraw the
service of UNIQUE keyword for the sake of backward compatibility.
• In simple words, we can say that SELECT UNIQUE statement is
used to retrieve a unique or distinct element from the table.
• Let's see the syntax of select unique statement.
SELECT UNIQUE column_name
FROM table_name;
• SQL SELECT DISTINCT statement can also be used for the same
cause.
SELECT DISTINCT
• The SQL DISTINCT command is used with SELECT key word
to retrieve only distinct or unique data.
• In a table, there may be a chance to exist a duplicate value and
sometimes we want to retrieve only unique values. In such
scenarios, SQL SELECT DISTINCT statement is used.
• Note: SQL SELECT UNIQUE and SQL SELECT DISTINCT
statements are same.
• Let's see the syntax of select distinct statement.
SELECT DISTINCT column_name ,column_name
FROM table_name;
Example

• Here is a table of students from where we want to retrieve


distinct information For example: distinct home-town.
SELECT DISTINCT home_town
FROM students
• Now, it will return two rows.
SELECT COUNT
• The SQL COUNT() function is used to return the number of rows in a
query.
• The COUNT() function is used with SQL SELECT statement and it is
very useful to count the number of rows in a table having enormous
data.
• For example: If you have a record of the voters in selected area and
want to count the number of voters then it is very difficult to do it
manually but you can do it easily by using the SQL SELECT COUNT
query.
• Let's see the syntax of SQL COUNT statement.
SELECT COUNT (expression)
FROM tables
WHERE conditions;
Let's see the examples of sql select
count function.
• SQL SELECT COUNT(column_name)
SELECT COUNT(name) FROM employee_table;
It will return the total number of names of employee_table. But null
fields will not be counted.
• SQL SELECT COUNT(*)
SELECT COUNT(*) FROM employee_table;
The "select count(*) from table" is used to return the number of
records in table.
• SQL SELECT COUNT(DISTINCT column_name)
SELECT COUNT(DISTINCT name) FROM employee_table;
It will return the total distinct names of employee_table.
SQL Clauses
• WHERE
• AND
• OR
• WITH
• AS
• HAVING
WHERE
• A WHERE clause in SQL is a data manipulation language
statement.
• WHERE clauses are not mandatory clauses of SQL DML
statements. But it can be used to limit the number of rows affected
by a SQL DML statement or returned by a query.
• Actually. it filters the records. It returns only those queries which fulfill
the specific conditions.
• WHERE clause is used in SELECT, UPDATE, DELETE statement
etc.
• Let's see the syntax for sql where:
SELECT column1, column 2, ... column n
FROM table_name
WHERE [conditions]
• WHERE clause uses some conditional selection
AND
• The SQL AND condition is used in SQL query to create two or
more conditions to be met.
• It is used in SQL SELECT, INSERT, UPDATE and DELETE
• Let's see the syntax for SQL AND:
• SELECT columns FROM tables WHERE condition 1 AND
condition 2;
• The SQL AND condition require that both conditions should be
met.
• The SQL AND condition also can be used to join multiple tables
in a SQL statement.
• To understand this concept practically, let us see some
Consider we have an employee table created into the database with the following
data:

• SQL "AND" example with "SELECT" statement


• This is how an SQL "AND" condition can be used in the SQL SELECT statement.
Example 1:
• Write a query to get the records from emp tables in which department of the employee is IT and location is Chennai.
Query:
SELECT *FROM emp WHERE Department = "IT" AND Location = "Chennai";
OR
• The SQL OR condition is used in SQL query to create a SQL statement where records are returned
when any one condition met. It can be used in
a SELECT statement, INSERT statement, UPDATE statement or DELETE statement.
• Let's see the syntax for the OR condition:
SELECT columns FROM tables WHERE condition 1 OR condition 2;

• SQL "OR" example with SQL SELECT


• This is how an SQL "OR" condition can be used in the SQL SELECT statement.
Example 1:
• Write a query to get the records from emp tables in which department of the employee is IT or location is Chennai.
Query:
SELECT *FROM emp WHERE Department = "IT" OR Location = "Chennai";
WITH CLAUSE
• The SQL WITH clause is used to provide a sub-query block which can be referenced in several places within the main
SQL query. It was introduced by oracle in oracle 9i release2 database.
• There is an example of employee table:
• Syntax for the SQL WITH clause -
• This syntax is for SQL WITH clause using a single sub-query alias.
WITH <alias_name> AS (sql_sub-query_statement)
SELECT column_list FROM <alias_name> [table name]
[WHERE <join_condition>]
• When you use multiple sub-query aliases, the syntax will be as follows.
WITH <alias_name_A> AS (sql_sub-query_statement)
<alias_name_B> AS (sql_sub-query_statement_from_alias_name_A
Or sql_sub-query_statement)
SELECT <column_list>
FROM <alias_name_A >,< alias_name_B >, [tablenames]
[WHERE < join_condition>]
ORDER BY Clause
• The SQL ORDER BY clause is used for sorting data in ascending and descending order based on one or more columns.
• Some databases sort query results in ascending order by default.
• SQL ORDER BY syntax:
SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ASC | DESC];
• Let us take a CUSTOMERS table having the following records:

• This is an example that would sort the result in ascending order by NAME and SALARY.
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;
INSERT
• SQL INSERT statement is a SQL query. It is used to insert a
single or a multiple records in a table.
• There are two ways to insert data in a table:
1.By SQL insert into statement
1. By specifying column names
2. Without specifying column names
2.By SQL insert into select statement
1. Inserting data directly into a table
• You can insert a row in the table by using SQL INSERT INTO
command.
• There are two ways to insert values in a table.
• In the first method there is no need to specify the column name
where the data will be inserted, you need only their values.
INSERT INTO table_name
VALUES (value1, value2, value3....);
• The second method specifies both the column name and values
which you want to insert.
INSERT INTO table_name (column1, column2, column3....)
VALUES (value1, value2, value3.....);
• Let's take an example of table which has five records within it.
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (1, ABHIRAM, 22, ALLAHABAD);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (2, ALKA, 20, GHAZIABAD);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (3, DISHA, 21, VARANASI);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (4, ESHA, 21, DELHI);
INSERT INTO STUDENTS (ROLL_NO, NAME, AGE, CITY)
VALUES (5, MANMEET, 23, JALANDHAR);
• It will show side table as the final result.
• Create a record in CUSTOMERS table by using this syntax also.
INSERT INTO CUSTOMERS
VALUES (6, PRATIK, 24, KANPUR);
• The following table will be as follow:
2) Inserting data through SELECT
Statement
• SQL INSERT INTO SELECT Syntax
INSERT INTO table_name
[(column1, column2, .... column)]
SELECT column1, column2, .... Column N
FROM table_name [WHERE condition];
• Note: when you add a new row, you should make sure that data
type of the value and the column should be matched.
• If any integrity constraints are defined for the table, you must
follow them.
Example

• Populate one table using another table


INSERT Multiple Rows
• Many times developers ask that is it possible to insert multiple rows into a single table in a single statement. Currently,
developers have to write multiple insert statements when they insert values in a table. It is not only boring but also time-
consuming.
• Let us see few practical examples to understand this concept more clearly. We will use the MySQL database for writing
all the queries.
Example 1:
• To create a table in the database, first, we need to select the database in which we want to create a table.
USE dbs;
• Then we will write a query to create a table named student in the selected database 'dbs’.
CREATE TABLE student(ID INT, Name VARCHAR(20), Percentage INT, Location VARCHAR(20), DateOfBirth DATE);
• The student table is created successfully.
• Now, we will write a single query to insert multiple records in the student table:
INSERT INTO student(ID, Name, Percentage, Location, DateOfBirth) VALUES(1, "Manthan Koli", 79, "Delhi", "2003-08-
20"), (2, "Dev Dixit", 75, "Pune", "1999-06-17"), (3, "Aakash Deshmukh", 87, "Mumbai", "1997-09-
12"), (4, "Aaryan Jaiswal", 90, "Chennai", "2005-10-02"), (5, "Rahul Khanna", 92, "Ambala", "1996-03-
04"), (6, "Pankaj Deshmukh", 67, "Kanpur", "2000-02-02"), (7, "Gaurav Kumar", 84, "Chandigarh", "1998-07-
06"), (8, "Sanket Jain", 61, "Shimla", "1990-09-08"), (9, "Sahil Wagh", 90, "Kolkata", "1968-04-
03"), (10, "Saurabh Singh", 54, "Kashmir", "1989-01-06");
• To verify that multiple records are inserted in the student table,
we will execute the SELECT query
SELECT *FROM student;
UPDATE
• The SQL UPDATE Query is used to modify the existing records in a table.
You can use the WHERE clause with the UPDATE query to update the
selected rows, otherwise all the rows would be affected.
• Syntax

• You can combine N number of conditions using the AND or the OR


operators.
Example
Consider the CUSTOMERS table having the following records −

• The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table,
you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the
following code block.
SQL UPDATE with JOIN
• SQL UPDATE JOIN means we will update one table using another
table and join condition.
• Let us take an example of a customer table. I have updated
customer table that contains latest customer details from another
source system. I want to update the customer table with latest data.
In such case, I will perform join between target table and source
table using join on customer ID.
• Let's see the syntax of SQL UPDATE query with JOIN statement.
UPDATE customer_table
INNER JOIN
Customer_table
ON customer_table.rel_cust_name = customer_table.cust_id
SET customer_table.rel_cust_name = customer_table.cust_name
How to use multiple tables in SQL UPDATE statement with
JOIN
Let's take two tables, table 1 and table 2.

• Create table1 • Create table2


1. CREATE TABLE table1 (column1 INT, CREATE TABLE table2 (column1 INT, column2 I
column2 INT, column3 VARCHAR (10 NT, column3 VARCHAR (100))
0)) INSERT INTO table2 (col1, col2, col3)
INSERT INTO table1 (col1, col2, col3) SELECT 1, 21, 'TWO-ONE'
SELECT 1, 11, 'FIRST' UNION ALL
SELECT 11, 22, 'TWO-TWO'
UNION ALL
UNION ALL
SELECT 11,12, 'SECOND' SELECT 21, 23, 'TWO-THREE'
UNION ALL UNION ALL
SELECT 21, 13, 'THIRD' SELECT 31, 24, 'TWO-FOUR'
• Now check the content in the table.
UNION ALL
SELECT * FROM table_1
SELECT 31, 14, 'FOURTH' SELECT * FROM table_2
• Our requirement is that we have table 2 which has two rows where Col 1 is 21 and 31. We want to
update the value from table 2 to table 1 for the rows where Col 1 is 21 and 31.
• We want to also update the values of Col 2 and Col 3 only.
• The most easiest and common way is to use join clause in the update statement and use multiple
tables in the update statement.
1. UPDATE table 1
2. SET Col 2 = t2.Col2,
3. Col 3 = t2.Col3
4. FROM table1 t1
5. INNER JOIN table 2 t2 ON t1.Col1 = t2.col1
6. WHERE t1.Col1 IN (21,31)
• Check the content of the table
• SELECT FROM table 1
• SELECT FROM table 2
UPDATE DATE
• How to update a date and time field in SQL?
• If you want to update a date & time field in SQL, you should use the following query.
• let's see the syntax of sql update date.
1. UPDATE table
2. SET Column_Name = 'YYYY-MM-DD HH:MM:SS'
3. WHERE Id = value
• Let us check this by an example:
• Firstly we take a table in which we want to update date and time fields.
• If you want to change the first row which id is 1 then you should write the following syntax:
1. UPDATE table
2. SET EndDate = '2014-03-16 00:00:00.000'
3. WHERE Id = 1
• Note: you should always remember that SQL must attach default 00:00:00.000 automatically.
• This query will change the date and time field of the first row in that above assumed table.
DELETE
• The SQL DELETE statement is used to delete rows from a table. Generally DELETE statement
removes one or more records from a table.
• SQL DELETE Syntax
• Let's see the Syntax for the SQL DELETE statement:
1. DELETE FROM table_name [WHERE condition];
• Here table_name is the table which has to be deleted. The WHERE clause in SQL DELETE
statement is optional here.
• Example
• Let us take a table, named "EMPLOYEE" table.
• Example of delete with WHERE clause is given below:
1.DELETE FROM EMPLOYEE WHERE ID=101;
• Resulting table after the query:

• Another example of delete statement is given below


1.DELETE FROM EMPLOYEE;
• Resulting table after the query:

• Invalid DELETE Statement for ORACLE database


• You cannot use * (asterisk) symbol to delete all the records.
1.DELETE * FROM EMPLOYEE;
DELETE ROW
• Let us take an example of student.
• Original table:

• If you want to delete a student with id 003 from the


student_name table, then the SQL DELETE query should be
like this:
1.DELETE FROM student_name
2.WHERE id = 003;
• Resulting table after SQL DELETE query:
DELETE ALL ROWS

• The statement SQL DELETE ALL ROWS is used to delete all


rows from the table. If you want to delete all the rows from
student table the query would be like,
1.DELETE FROM STUDENT_NAME;
• Resulting table after using this query:
DELETE DUPLICATE ROWS

• If you have got a situation that you have multiple duplicate records in
a table, so at the time of fetching records from the table you should
be more careful. You make sure that you are fetching unique records
instead of fetching duplicate records.
• To overcome with this problem we use DISTINCT keyword.
• It is used along with SELECT statement to eliminate all duplicate
records and fetching only unique records.
• SYNTAX:
• The basic syntax to eliminate duplicate records from a table is:
1.SELECT DISTINCT column1, column2,....columnN
2.FROM table _name
3.WHERE [conditions]
EXAMPLE:

• Firstly we should check the SELECT query


and see how it returns the duplicate
percentage records.
1.SQL > SELECT PERCENTAGE FROM STU
DENTS
2.ORDER BY PERCENTAGE;
• Now let us use SELECT query with DISTINCT keyword and see
the result. This will eliminate the duplicate entry.
1.SQL > SELECT DISTINCT PERCENTAGE FROM STUDENTS

2.ORDER BY PERCENTAGE;
DELETE DATABASE

• You can easily remove or delete indexes, tables and databases with the
DROP statement.
• The DROP index statement is:
• Used to delete index in the table
DROP INDEX index_name ON table_name
• DROP DATABASE Statement:
• The drop database statement is used to delete a database.
1.DROP DATABASE database_name
Note:
• We should always note that in RDBMS, database name should be unique.
• We should always remember that DROP database command may be the
cause of loss of all information so we should always be careful while doing
this operation.
DELETE VIEW
• Before knowing about what is SQL delete view, it is important to know -
• What is SQL view?
• A view is a result set of a stored query on the data.
• The SQL view is a table which does not physically exist. It is only a virtual table.
• SQL VIEW can be created by a SQL query by joining one or more table.
• Syntax for SQL create view -
1.CREATE VIEW view_name AS
2.SELECT columns
3.FROM tables
4.WHERE conditions;
• If you want to delete a SQL view, It is done by SQL DROP command you should use the
following syntax:
• SQL DROP VIEW syntax:
1.DROP VIEW view_name
• Why use the SQL DROP VIEW statement?
• When a view no longer useful you may drop the view permanently. Also if a view needs
change within it, it would be dropped and then created again with changes in appropriate
places.
DELETE JOIN
• This is very commonly asked question that how to delete or update rows using join clause
• It is not a very easy process, sometimes, we need to update or delete records on the basis of complex WHERE
clauses.
• There are three tables which we use to operate on SQL syntax for DELETE JOIN.
• These tables are table1, table2 and target table.
• SQL Syntax for delete JOIN
1. DELETE [target table]
2. FROM [table1]
3. INNER JOIN [table2]
4. ON [table1.[joining column] = [table2].[joining column]
5. WHERE [condition]
• Syntax for update
1. UPDATE [target table]
2. SET [target column] = [new value]
3. FROM [table1]
4. INNER JOIN [table2]
5. ON [table1.[joining column] = [table2].[joining column]
6. WHERE [condition]
SQL JOIN

• As the name shows, JOIN means to combine something. 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.
• ANSI standard SQL defines five types of JOIN :
1.inner join,
2.left outer join,
3.right outer join,
4.full outer join, and
5.cross join.
Why SQL JOIN is used?

• If you want to access more than one table through a select


statement.
• If you want to combine two or more table then SQL JOIN
statement is used .it combines rows of that tables in one table
and one can retrieve the information by a SELECT statement.
• The joining of two or more tables is based on common field
between them.
• SQL INNER JOIN also known as simple join is the most
common type of join.
How to use SQL join or SQL Inner Join?

• Let an example to deploy SQL JOIN process:


• 1.Staff table

• 2.Payment table
1.SELECT Staff_ID, Staff_NAME, Staff_AGE, AMOUNT
2. FROM STAFF s, PAYMENT p
3. WHERE s.ID =p.STAFF_ID;
• This will produce the result like this:
OUTER JOIN

• In the SQL outer JOIN all the content of the both tables are
integrated together either they are matched or not.
• If you take an example of employee table
Outer join of two types:
1.Left outer join (also known as left join): this join returns all the rows
from left table combine with the matching rows of the right table. If you
get no matching in the right table it returns NULL values.
2.Right outer join (also known as right join): this join returns all the
rows from right table are combined with the matching rows of left table
.If you get no column matching in the left table .it returns null value.
LEFT JOIN

• The SQL left join returns all the values from the left table and it
also includes matching values from right table, if there are no
matching join value it returns NULL.
• BASIC SYNTAX FOR LEFT JOIN:
1.SELECT table1.column1, table2.column2....
2.FROM table1
3.LEFTJOIN table2
4.ON table1.column_field = table2.column_field;
• CUSTOMER TABLE:

• ORDER TABLE:

• join these two tables with LEFT JOIN:


1. SELECT ID, NAME, AMOUNT,DATE
2.FROM CUSTOMER
3.LEFT JOIN ORDER
4.ON CUSTOMER.ID = ORDER.CUSTOMER_ID;
RIGHT JOIN

• The SQL right join returns all the values from the rows of right
table. It also includes the matched values from left table but if
there is no matching in both tables, it returns NULL.
• Basic syntax for right join:
1.SELECT table1.column1, table2.column2.....
2.FROM table1
3.RIGHT JOIN table2
4.ON table1.column_field = table2.column_field;
• Here we will join these two tables with SQL RIGHT JOIN:
1.SQL> SELECT ID,NAME,AMOUNT,DATE
2.FROM CUSTOMER
3.RIGHT JOIN ORDER
4.ON CUSTOMER.ID = ORDER.CUSTOMER_ID;
FULL JOIN

• The SQL full join is the result of combination of both left and right outer join and the join
tables have all the records from both tables. It puts NULL on the place of matches not
found.
• SQL full outer join and SQL join are same. generally it is known as SQL FULL JOIN.
• SQL full outer join:
• What is SQL full outer join?
• SQL full outer join is used to combine the result of both left and right outer join and returns
all rows (don't care its matched or unmatched) from the both participating tables.
• Syntax for full outer join:
1.SELECT *
2.FROM table1
3.FULL OUTER JOIN table2
4.ON table1.column_name = table2.column_name;
• Note:here table1 and table2 are the name of the tables participating in joining and
column_name is the column of the participating tables.
Let us take two tables to demonstrate full
outer join:
• table_A

• table_B

• Resulting table
Cross Join

• When each row of first table is combined with each row from the
second table, known as Cartesian join or cross join. In general words
we can say that SQL CROSS JOIN returns the Cartesian product of
the sets of rows from the joined table.
• We can specify a CROSS JOIN in two ways:
1.Using the JOIN syntax.
2.the table in the FROM clause without using a WHERE clause.
• SYNTAX of SQL Cross Join
1.SELECT * FROM [TABLE1] CROSS JOIN [TABLE2]
2.OR
3.SELECT * FROM [ TABLE1] , [TABLE2]
• Table1 – MatchScore

• Table2 - Departments
SQL Aggregate 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
COUNT FUNCTION

• 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
1.COUNT(*)
2.or
3.COUNT( [ALL|DISTINCT] expression )
Example: COUNT()

Example
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:10
Example: COUNT with WHERE
1.SELECT COUNT(*)
2.FROM PRODUCT_MAST;
3.WHERE RATE>=20;
Output:7
Example: COUNT() with DISTINCT
1.SELECT COUNT(DISTINCT COMPANY)
2.FROM PRODUCT_MAST;
Output:3
Example: COUNT() with GROUP BY
1.SELECT COMPANY, COUNT(*)
2.FROM PRODUCT_MAST
3.GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
SUM Function
• Sum function is used to calculate the sum of • Example: SUM() with GROUP BY
all selected columns. It works on numeric 1.SELECT SUM(COST)
fields only.
• Syntax 2.FROM PRODUCT_MAST
1.SUM() 3.WHERE QTY>3
2.or 4.GROUP BY COMPANY;
3.SUM( [ALL|DISTINCT] expression ) Output:
• Example: SUM() Com1 150
1.SELECT SUM(COST) Com3 170
2.FROM PRODUCT_MAST; • Example: SUM() with HAVING
Output: 1.SELECT COMPANY, SUM(COST)
670 2.FROM PRODUCT_MAST
• Example: SUM() with WHERE 3.GROUP BY COMPANY
1.SELECT SUM(COST) 4.HAVING SUM(COST)>=170;
2.FROM PRODUCT_MAST Output:
3.WHERE QTY>3; Com1 335
Output: Com3 170
320
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:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
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
MAX()
or
MAX( [ALL|DISTINCT] expression )
• Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
30
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:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
SQL - Sub 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.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• There are a few rules that subqueries must follow −
1. Subqueries must be enclosed within parentheses.
2. 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.
3. 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.
4. Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
5. The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
6. A subquery cannot be immediately enclosed in a set function.
7. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Subqueries with the SELECT Statement
• Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −

• Example
• Consider the CUSTOMERS table having the following records −
• This would produce the following result.
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 selected data in the subquery can
be modified with any of the character, date or number functions.
• The basic syntax is as follows.
• 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.
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.
• 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.

• This would impact two rows and finally CUSTOMERS table would have the following records.
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.
• 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.

• This would impact two rows and finally the CUSTOMERS table would have the following records.
Comparison Operators
• Comparison operators are used in the WHERE clause to determine which records to select. Here is
a list of the comparison operators that you can use in SQL:
PL/SQL
• PL/SQL is a combination of SQL along with the procedural
features of programming languages.
• It was developed by Oracle Corporation in the early 90's to
enhance the capabilities of SQL.
• PL/SQL is one of three key programming languages embedded
in the Oracle Database, along with SQL itself and Java. This
tutorial will give you great understanding on PL/SQL to proceed
with Oracle database and other advanced RDBMS concepts.
PL/SQL Procedure

• The PL/SQL stored procedure or simply a procedure is a


PL/SQL block which performs one or more specific tasks. It is
just like procedures in other programming languages.
• The procedure contains a header and a body.
• Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
• Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.
• How to pass parameters in procedure:
• When you want to create a procedure or function, you have to
define parameters .There is three ways to pass parameters in
procedure:
1.IN parameters: The IN parameter can be referenced by the
procedure or function. The value of the parameter cannot be
overwritten by the procedure or the function.
2.OUT parameters: The OUT parameter cannot be referenced
by the procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
3.INOUT parameters: The INOUT parameter can be referenced
by the procedure or function and the value of the parameter can
be overwritten by the procedure or function.
PL/SQL Create Procedure
• Syntax for creating procedure:

• Create procedure example


• In this example, we are going to insert record in user table. So you
need to create user table first.
• Table creation:
1.create table user(id number(10) primary key,name varchar2(100));
• Procedure Code:

create or replace procedure "INSERTUSER"


(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
/
• Output:
Procedure created.
PL/SQL program to call procedure

• Let's see the code to call above created procedure.


BEGIN
insertuser(101,'Rahul');
insertuser(201, ‘Madhav’);
dbms_output.put_line('record inserted successfully');
END;
/
• Now, see the "USER" table, you will see one record is inserted.
PL/SQL Drop Procedure

• Syntax for drop procedure


1.DROP PROCEDURE procedure_name;
• Example of drop procedure
1.DROP PROCEDURE pro1;
PL/SQL Function
• The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and a
function is, a function must always return a value, and on the other hand a procedure may or may not
return a value. Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.
• Syntax to create a function:

• Here:
• Function_name: specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents that value will be passed from outside and OUT represents that this parameter will be
used to return a value outside of the procedure.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
• Function_body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.
PL/SQL Function Example

• Now write another program to call the function


Output:

Addition is: 33
Statement processed.
0.05 seconds
PL/SQL function example using table
Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers table.

• After the execution of


above code, you will get
the following result.

Function created.
• To call a function you have to pass the required parameters along with function name and if function
returns a value then you can store returned value. Following program calls the function totalCustomers
from an anonymous block:

• After the execution of above code in SQL prompt, you will get the following result.
Total no. of Customers: 4
PL/SQL procedure successfully completed.
PL/SQL Drop Function

• Syntax for removing your created function:


If you want to remove your created function from the database,
you should use the following syntax.
1.DROP FUNCTION function_name;
PL/SQL Cursor

• When an SQL statement is processed, Oracle creates a


memory area known as context area. A cursor is a pointer to
this context area. It contains all information needed for
processing the statement. In PL/SQL, the context area is
controlled by Cursor. A cursor contains information on a select
statement and the rows of data accessed by it.
• A cursor is used to referred to a program to fetch and process
the rows returned by the SQL statement, one at a time. There
are two types of cursors:
1. Implicit Cursors
2. Explicit Cursors
PL/SQL Implicit Cursors

• The implicit cursors are automatically generated by Oracle while an


SQL statement is executed, if you don't use an explicit cursor for the
statement.
• These are created by default to process the statements when DML
statements like INSERT, UPDATE, DELETE etc. are executed.
• Orcale provides some attributes known as Implicit cursor's attributes
to check the status of DML operations. Some of them are: %FOUND,
%NOTFOUND, %ROWCOUNT and %ISOPEN.
• For example: When you execute the SQL statements like INSERT,
UPDATE, DELETE then the cursor attributes tell whether any rows
are affected and how many have been affected. If you run a SELECT
INTO statement in PL/SQL block, the implicit cursor attribute can be
used to find out whether any row has been returned by the SELECT
statement. It will return an error if there no data is selected.
Example
Create customers table and have records:

• a
Let's execute the following program to update the table and increase salary of each customer by 5000. Here,
SQL%ROWCOUNT attribute is used to determine the number of rows affected:

Create procedure:
1.DECLARE
2. total_rows number(2);
3.BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12.END;
13./
Output:
6 customers updated PL/SQL procedure successfully completed.
• select * from customers;
PL/SQL Explicit Cursors

• The Explicit cursors are defined by the programmers to gain more control
over the context area. These cursors should be defined in the declaration
section of the PL/SQL block. It is created on a SELECT statement which
returns more than one row.
• Following is the syntax to create an explicit cursor:Syntax of explicit cursor
• Following is the syntax to create an explicit cursor:
1.CURSOR cursor_name IS select_statement;;
• Steps:
• You must follow these steps while working with an explicit cursor.
1.Declare the cursor to initialize in the memory.
2.Open the cursor to allocate memory.
3.Fetch the cursor to retrieve data.
4.Close the cursor to release allocated memory.
1) Declare the cursor:
• It defines the cursor with a name and the associated SELECT statement.
• Syntax for explicit cursor declaration
1. CURSOR cursor_name IS
2. SELECT statement;
2) Open the cursor:
• It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the SQL
statements into it.
• Syntax for cursor open:
1. OPEN cursor_name;
3) Fetch the cursor:
• It is used to access one row at a time. You can fetch rows from the above-opened cursor as follows:
• Syntax for cursor fetch:
1. FETCH cursor_name INTO variable_list;
4) Close the cursor:
• It is used to release the allocated memory. The following syntax is used to close the above-opened
cursors.
• Syntax for cursor close:
1. Close cursor_name;
Example
• Create procedure:
• Execute the following program to retrieve the
customer name and address.
1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers
;
Output:
7. BEGIN
8. OPEN c_customers;
9. LOOP
1 Ramesh Allahabad
10. FETCH c_customers into c_id, c_name, c_a
ddr; 2 Suresh Kanpur
11. EXIT WHEN c_customers%notfound; 3 Mahesh Ghaziabad
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' 4 Chandan Noida
|| c_addr); 5 Alex Paris
13. END LOOP; 6 Sunita Delhi
14. CLOSE c_customers; PL/SQL procedure successfully completed.
15.END;
Trigger

• Trigger is invoked by Oracle engine automatically whenever a


specified event occurs. Trigger is stored into database and invoked
repeatedly, when specific condition match.
• Triggers are stored programs, which are automatically executed or
fired when some event occurs.
• Triggers are written to be executed in response to any of the
following events.
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
• Triggers could be defined on the table, view, schema, or database
with which the event is associated.
Advantages of Triggers

• These are the following advantages of Triggers:


• Trigger generates some derived column values automatically
• Enforces referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
Creating a trigger:

1. CREATE [OR REPLACE ] TRIGGER trigger_n Here,
ame
• CREATE [OR REPLACE] TRIGGER trigger_name: It
2. {BEFORE | AFTER | INSTEAD OF } creates or replaces an existing trigger with the
trigger_name.
3. {INSERT [OR] | UPDATE [OR] | DELETE}
• {BEFORE | AFTER | INSTEAD OF} : This specifies when
4. [OF col_name] the trigger would be executed. The INSTEAD OF clause
5. ON table_name is used for creating trigger on a view.
6. [REFERENCING OLD AS o NEW AS n] • {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies
the DML operation.
7. [FOR EACH ROW]
• [OF col_name]: This specifies the column name that
8. WHEN (condition) would be updated.
9. DECLARE • [ON table_name]: This specifies the name of the table
associated with the trigger.
10. Declaration-statements
• [REFERENCING OLD AS o NEW AS n]: This allows you
11.BEGIN to refer new and old values for various DML statements,
12. Executable-statements like INSERT, UPDATE, and DELETE.
13.EXCEPTION • [FOR EACH ROW]: This specifies a row level trigger,
i.e., the trigger would be executed for each row being
14. Exception-handling-statements affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a
15.END; table level trigger.
• WHEN (condition): This provides a condition for rows for
which the trigger would fire. This clause is valid only for
row level triggers.
Example
• Create trigger:
• Let's take a program to create a row
level trigger for the CUSTOMERS
table that would fire for INSERT or
UPDATE or DELETE operations
performed on the CUSTOMERS
table. This trigger will display the
salary difference between the old
values and new values:
1.CREATE OR REPLACE TRIGGER display_salary_changes
2.BEFORE DELETE OR INSERT OR UPDATE ON customers
3.FOR EACH ROW
4.WHEN (NEW.ID > 0)
5.DECLARE
6. sal_diff number;
7.BEGIN
8. sal_diff := :NEW.salary - :OLD.salary;
9. dbms_output.put_line('Old salary: ' || :OLD.salary);
10. dbms_output.put_line('New salary: ' || :NEW.salary);
11. dbms_output.put_line('Salary difference: ' || sal_diff);
12.END;
13./
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Check the salary
difference by procedure:
Use the following code to get the old salary, new salary and
salary difference after the trigger created.
1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated
');
11. END IF;
12.END;
13./
Assertion
• Assertions - An assertion is a piece of SQL which makes sure a condition is satisfied or it stops
action being taken on a database object. It could mean locking out the whole table or even the
whole database.
• Assertions - Assertions do not modify the data, they only check certain conditions.
• Syntax:
CREATE ASSERTION
CHECK ( );
• Example: Assertion There should not any customer in bank having balance less than 1000.
Create Assertion c1 Check
( NOT EXISTS (
Select *
From customer
Where balance<1000));
Roles & Privileges
Controlling User Access
Privileges
• Database security:
• System security
• Data security
• System privileges: Gaining access to the database
• Object privileges: Manipulating the content of the database objects
• Schemas: Collection of objects such as tables, views, and sequences
System Privileges
• More than 100 privileges are available.
• The database administrator has highlevel system privileges for tasks
such as:
• Creating new users
• Removing users
• Removing tables
• Backing up tables
Creating Users
• The DBA creates users with the CREATE USER statement.
User System Privileges
• After a user is created, the DBA can grant specific system privileges to that
user.

• An application developer, for example, may have the following system


privileges:
• CREATE SESSION
• CREATE TABLE
• CREATE SEQUENCE
• CREATE VIEW
• CREATE PROCEDURE
Granting System Privileges
• The DBA can grant specific system privileges to a user.
Creating and Granting Privileges to a Role
• Create a role

• Grant privileges to a role

• Grant a role to users


Object Privileges
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that owner’s object.
Granting Object Privileges
• Grant query privileges on the EMPLOYEES table.

• Grant privileges to update specific columns to users and roles.


Passing On Your Privileges
• Give a user authority to pass along privileges.

• Allow all users on the system to query data from Alice’s


DEPARTMENTS table.
Revoking Object Privileges
• You use the REVOKE statement to revoke privileges granted to other
users.
• Privileges granted to others through the WITH GRANT OPTION clause
are also revoked.
Revoking Object Privileges
• As user Alice, revoke the SELECT and INSERT privileges given to user
Scott on the DEPARTMENTS table.
Summary

You might also like