SQL - Unit III
SQL - Unit III
SQL
Topics Covered
• SQL commands,
• Constraints,
• Joins,
• set operations,
• Sub queries,
• Views,
• PL – SQL,
• Triggers, and Cursors.
Basics of SQL-DDL,DML,DCL,TCL Nested Queries, Views and its
Structure Creation, alternation Types
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
• The output of the DDL is placed in the data dictionary which contains metadata - that is, data about data.
• SQL provides a rich DDL that allows one to define tables, integrity constraints, assertions, etc.
create table department (dept name char (20), building char (15), budget numeric (12,2));
• Execution of the above DDL statement creates the department table with three columns: dept name,
building, and budget, each of which has a specific data type associated with it.
CREATING DATABASE TABLE
• Used to create a table by defining its structure, the data type and name of the various
columns, the relationships with columns of other tables etc.
• E.g.:
CREATE TABLE Employee(Name varchar2(20), DOB date, Salary number(6));
ALTER - Add a new attribute or Modify the characteristics of some existing attribute.
• ALTER TABLE table_name ADD (column_name1 data_type (size), column_name2 data_type (size),
….., column_nameN data_type (size));
E.g.:
ALTER TABLE Employee ADD (Address varchar2(20));
ALTER TABLE Employee ADD (Designation varchar2(20), Dept varchar2(3));
ALTER TABLE table_name MODIFY (column_name data_type(new_size));
E.g.:
E.g.:
E.g.:
TRUNCATE TABLE Employee_details;
Data Manipulation Language
E.g.:
• INSERT INTO Employee VALUES (‘ashok’, ‘16-mar-1998’, 30000);
• E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10)
NOT NULL, ADDRESS varchar(20) );
UNIQUE
• This constraint helps to uniquely identify each row in the table. i.e. for a
particular column, all the rows should have unique values. We can have
more than one UNIQUE columns in a table.
• E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME
varchar(10), ADDRESS varchar(20) );
PRIMARY KEY
• Primary Key is a field which uniquely identifies each row in the table.
• If a field in a table as primary key, then the field will not be able to
contain NULL values as well as all the rows should have unique values
for this field.
• In other words we can say that this is combination of NOT NULL and
UNIQUE constraints.
• A table can have only one field as primary key.
• E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME
varchar(10), ADDRESS varchar(20), PRIMARY KEY(ID) );
FOREIGN KEY
• Foreign Key is a field in a table which uniquely identifies each row of a
another table.
• That is, this field points to primary key of another table. This usually
creates a kind of link between the tables.
• Foreign Key is used to relate two tables. The relationship between the
two tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
• This is also called a referencing key.
• We use ALTER statement and ADD statement to specify this constraint.
• In Customer_Detail table, c_id is the primary key which is set as foreign key
in Order_Detail table.
• The value that is entered in c_id which is set as foreign key in Order_Detail table
must be present in Customer_Detail table where it is set as primary key.
• This prevents invalid data to be inserted into c_id column of Order_Detail table.
• E.g.
• CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10)
NOT NULL, AGE int DEFAULT 18 );
Primary Key Vs Foreign Key
Primary Key Vs Unique Key
Basics of SQL-DDL,DML,DCL,TCL Views and its Types
Structure Creation, alternation
• Count(Distinct Salary): Return number of distinct Non Null values over the
column salary .i.e 4
• Sum()
• sum(salary): Sum all Non Null values of
Column salary i.e., 310
• sum(Distinct salary): Sum of all distinct
Non-Null values i.e., 250.
• Avg()
• Avg(salary) = Sum(salary) / count(salary) = 310/5
• Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
• Min(), Max()
• Min(salary): Minimum value in the salary column except NULL i.e., 40.
• Max(salary): Maximum value in the salary i.e., 80.
Built in Functions - Numeric Functions in
SQL
• ABS(): It returns the absolute value of a number.
Syntax: SELECT ABS(-243.5);
Output: 243.5
• ACOS(): It returns the arc cosine of a number.
Syntax: SELECT ACOS(0.25);
Output: 1.318116071652818
• ASIN(): It returns the arc sine of a number.
Syntax: SELECT ASIN(0.25);
Output: 0.25268025514207865
• ATAN(): It returns the arc tangent of a number.
Syntax: SELECT ATAN(2.5);
Output: 1.1902899496825317
• CEILING(): It returns the smallest integer value that is greater than or equal to a number.
Syntax: SELECT CEILING(25.75);
Output: 26
• COS(): It returns the cosine of a number.
Syntax: SELECT COS(30);
Built in Functions - Numeric Functions in SQL
• COT(): It returns the cotangent of a number.
Syntax: SELECT COT(6);
Output: -3.436353004180128
• DEGREES(): It converts a radian value into degrees.
Syntax: SELECT DEGREES(1.5);
Output: 85.94366926962348
• DIV(): It is used for integer division.
Syntax: SELECT 10 DIV 5;
Output: 2
• EXP(): It returns the value of e to the power of number.
Syntax: SELECT EXP(1);
Output: 2.718281828459045
• FLOOR(): It returns the largest integer value that is less than or equal to a number.
Syntax: SELECT FLOOR(25.75);
Output: 25
• GREATEST(): It returns the greatest value in a list of expressions.
Syntax: SELECT GREATEST(30, 2, 36, 81, 125);
Output: 125
• LEAST(): It returns the smallest value in a list of expressions.
Syntax: SELECT LEAST(30, 2, 36, 81, 125);
Output: 2
• LN(): It returns the natural logarithm of a number.
Syntax: SELECT LN(2);
Output: 0.6931471805599453
• LOG10(): It returns the base-10 logarithm of a number.
Syntax: SELECT LOG(2);
Output: 0.6931471805599453
Built in Functions - Numeric Functions in
SQL
• LOG2(): It returns the base-2 logarithm of a number.
Syntax: SELECT LOG2(6);
Output: 2.584962500721156
• MOD(): It returns the remainder of n divided by m.
Syntax: SELECT MOD(18, 4);
Output: 2
• PI(): It returns the value of PI displayed with 6 decimal places.
Syntax: SELECT PI();
Output: 3.141593
• POW(): It returns m raised to the nth power.
Syntax: SELECT POW(4, 2);
Output: 16
• RADIANS(): It converts a value in degrees to radians.
Syntax: SELECT RADIANS(180);
• RAND(): It returns a random number.
Syntax: SELECT RAND();
Output: 0.33623238684258644
• ROUND(): It returns a number rounded to a certain number of decimal places.
Syntax: SELECT ROUND(5.553);
Output: 6
• SIGN(): It returns a value indicating the sign of a number.
Syntax: SELECT SIGN(255.5);
Output: 1
• SIN(): It returns the sine of a number.
Syntax: SELECT SIN(2);
Output: 0.9092974268256817
Built in Functions - Numeric Functions in
SQL
• SQRT(): It returns the square root of a number.
Syntax: SELECT SQRT(25);
Output: 5
• ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and expressed in radians.
Syntax: SELECT ATAN2(7);
Output: 1.42889927219073
• 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.
• To update name of the students to geeks in Student2 table whose location is same as Raju,Ravi in Student1 table
• UPDATE Student2 SET NAME=’geeks’ WHERE LOCATION IN ( SELECT LOCATION FROM Student1 WHERE NAME IN
(‘Raju’,’Ravi’));
Subqueries with the DELETE Statement
• The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
• To delete students from Student2 table whose rollno is same as that in Student1 table and having location as Chennai.
• DELETE FROM Student2 WHERE ROLL_NO IN ( SELECT ROLL_NO FROM Student1 WHERE LOCATION = ’chennai’);
Basics of SQL-DDL,DML,DCL,TCL Views and its Types
Structure Creation, alternation
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
• We can create a view by selecting fields from one or more tables present
in the database.
• A View can either have all the rows of a table or specific rows based on
certain condition.
Student Marks
Student Details
Creating a View
View can be created using CREATE VIEW statement. A View can be created from a
single table or multiple tables.
Syntax
CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name
Student Details
WHERE condition;
To see the data in the View, we can query the view in the same manner as we query a
table.
SELECT * FROM DetailsView;
Student Details • Creating View from multiple tables
• In this example we will create a View named MarksView from two tables
StudentDetails and StudentMarks.
• To create a View from multiple tables we can simply include multiple tables in
the SELECT statement.
• CREATE VIEW MarksView AS SELECT StudentDetails.NAME,
StudentDetails.ADDRESS, StudentMarks.MARKS FROM StudentDetails,
Student Marks StudentMarks WHERE StudentDetails.NAME = StudentMarks.NAME;
Output
DELETING VIEWS
• SQL allows us to delete an existing View. We can delete or drop a View using the DROP statement.
Syntax
1.The SELECT statement which is used to create the view should not
include GROUP BY clause or ORDER BY clause.
2.The SELECT statement should not have the DISTINCT keyword.
3.The View should have all NOT NULL values.
4.The view should not be created using nested queries or complex queries.
5.The view should be created from a single table. If the view is created
using multiple tables then we will not be allowed to update the view.
CREATE OR REPLACE VIEW
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
Syntax
CREATE OR REPLACE VIEW view_name AS SELECT column1,coulmn2,.. FROM table_name WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
Syntax:
INSERT INTO view_name(column1, column2 , column3,..) VALUES(value1, value2, value3..);
Example:
In the below example we will insert a new row in the View DetailsView which we have created above in the example of “creating
views from a single table”.
• Also deleting a row from a view first delete the row from the actual table and the change is then reflected in the view.
• Syntax
• DELETE FROM view_name WHERE condition;
• view_name:Name of view from where we want to delete rows
• condition: Condition to select rows
In this example we will delete the last row from the view DetailsView which we just added in the above example of inserting rows.
DELETE FROM DetailsView WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output
Basics of SQL-DDL,DML,DCL,TCL Nested Queries, Views and its
Structure Creation, alternation Types
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
TCL Commands
Transaction Control Language (TCL) Commands are:
Commit − It is used to save the transactions in the database.
Savepoint − The changes done till savpoint will be unchanged and all the
transactions after savepoint will be rolled back.
Example
• Given below is an example of the usage of the TCL commands
in the database management system (DBMS)
COMMIT
Transactional control commands are only used with the DML
Commands such as - INSERT, UPDATE and DELETE only.
Thus, two rows from the table would be deleted and the SELECT statement would
produce the following result.
ROLLBACK Command
Following is an example, which would delete those records from the table which
have the age = 25 and then ROLLBACK the changes in the database.
Thus, the delete operation would not impact the table and the
SELECT statement would produce the following result.
select * from customers;
SAVEPOINT
• A SAVEPOINT is a point in a transaction when you can roll the
transaction back to a certain point without rolling back the entire
transaction.
The syntax for a SAVEPOINT command is as shown below.
Now that the three deletions have taken place, let us assume that you have changed
your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2.
Because SP2 was created after the first deletion, the last two deletions are undone −
Notice that only the first deletion took place since you rolled back
to SP2.
RELEASE SAVEPOINT Command:
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that
you have created.
The syntax for a RELEASE SAVEPOINT command is as follows:
Once a SAVEPOINT has been released, you can no longer use the
ROLLBACK command to undo transactions performed since the last
SAVEPOINT.
Basics of SQL-DDL,DML,DCL,TCL Nested Queries, Views and its
Structure Creation, alternation Types
Defining Constraints-Primary Key, Foreign Key, Transaction Control Commands
Unique, not null, check, IN operator Commit, Rollback, Savepoint
Variable_name Table_name.Column_name%type;
This syntax defines a variable of the type of the referenced column on the
referenced table
PL/SQL Control Structure
• PL/SQL has a number of control structures which includes:
• Conditional controls
• Iterative or loop controls.
• Exception or error controls
• These control structure, can be used singly or together, that allow the
PL/SQL developer to direct the flow of execution through the
program.
PL/SQL Control Structure
• Conditional Controls
IF....THEN....END IF;
IF....THEN...ELSE....END IF;
IF....THEN...ELSIF....THEN....ELSE....END IF;
PL/SQL Control Structure
• LOOP
• Sequence of statements;
• END LOOP;
• WHILE loops
• WHILE <condition>
• LOOP statements;
• END LOOP;
Example:
SET SERVEROUTPUT ON;
• DECLARE
• i INTEGER := 1;
• BEGIN
• WHILE i <= 10 LOOP
• DBMS_OUTPUT.PUT_LINE(i);
• i := i+1;
• END LOOP;
• FOR loops
• FOR counter IN initial_value .. final_value LOOP
• LOOP statements;
• END LOOP;
Cursor
• Whenever DML statements are executed, a temporary
work area is created in the system memory and it is
called a cursor. A cursor holds the rows (one or more)
returned by a SQL statement. The set of rows the
cursor holds is referred to as the active set.
• There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
• Implicit cursors are automatically created by Oracle
whenever an SQL statement is executed, when there
is no explicit cursor for the statement.
• Programmers cannot control the implicit cursors and
the information in it.
• In PL/SQL, the most recent implicit cursor is the SQL
cursor, which has the following attributes.
Implicit Cursors
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
2
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after
3 executing its associated SQL statement.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by
4 a SELECT INTO statement.
Example
The following program will update the employee table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
Output:
6 customers selected
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor 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.
LANGUAGE value of SQL and the BEGIN...END block, which forms the procedure body, are particular to an SQL
procedure
∙ CASE statement
∙ FOR statement
∙ GOTO statement
∙ IF statement
∙ ITERATE statement
∙ RETURN statement
∙ WHILE statement
• Invoking Procedures
Can invoke Stored procedure stored at the location of the database by using the
SQL CALL statement
IF <condition> THEN
<statement(s)>
ELSE
<statement(s)>
END IF;
Loops
LOOP
……
EXIT WHEN <condition>
……
END LOOP;
• CREATE TABLE employee (
• empno CHAR(6) PRIMARY KEY, -- Employee Number (Unique
Identifier)
• name VARCHAR(50) NOT NULL, -- Employee Name
• department VARCHAR(50), -- Department Name
• salary DECIMAL(10,2), -- Employee Salary
• bonus DECIMAL(10,2), -- Bonus Amount
• rating SMALLINT CHECK (rating BETWEEN 1 AND 5) -- Performance
Rating (1 to 5)
• );
• INSERT INTO employee (empno, name, department, salary, bonus,
rating) VALUES
• ('E1001', 'Alice Johnson', 'HR', 5000.00, 0.00, 1),
• ('E1002', 'Bob Smith', 'Finance', 6000.00, 0.00, 2),
• ('E1003', 'Charlie Brown', 'IT', 7000.00, 0.00, 3),
• ('E1004', 'David Lee', 'Sales', 5500.00, 0.00, 1),
• ('E1005', 'Emma Watson', 'Marketing', 5800.00, 0.00, 2);
EXAMPLE :
CREATE OR REPLACE PROCEDURE UPDATE_SALARY_IF3 (
employee_number IN CHAR,
rating IN SMALLINT
)
AS
counter NUMBER := 10;
BEGIN
WHILE counter > 0 LOOP
IF rating = 1 THEN
UPDATE employee
SET salary = salary * 1.10, bonus = 1000
WHERE empno = employee_number;
ELSIF rating = 2 THEN
UPDATE employee
SET salary = salary * 1.05, bonus = 500
WHERE empno = employee_number;
ELSE
UPDATE employee
SET salary = salary * 1.03, bonus = 0
WHERE empno = employee_number;
END IF;
counter := counter - 1;
END LOOP;
END UPDATE_SALARY_IF3; -- ✅ The name must exactly match the procedure name above
/
• Check for errors using:
• SHOW ERRORS PROCEDURE UPDATE_SALARY_IF3;
• If there are no errors, execute the procedure using:
• EXEC UPDATE_SALARY_IF3('E1001', 1);
• Verify updates in the employee table:
• SELECT * FROM employee WHERE empno = 'E1001';
Triggers
• 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.
∙
A database definition (DDL) statement (CREATE, ALTER, or DROP).
∙
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
The syntax of Triggers in SQL–
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
/
• CREATE TABLE Student_Trigger
• (
• Student_RollNo INT NOT NULL PRIMARY KEY,
• Student_FirstName Varchar (100),
• Student_EnglishMarks INT,
• Student_PhysicsMarks INT,
• Student_ChemistryMarks INT,
• Student_MathsMarks INT,
• Student_TotalMarks INT,
• Student_Percentage int));
• CREATE OR REPLACE TRIGGER Student_Table_Marks
• BEFORE INSERT
• ON Student_Trigger
• FOR EACH ROW
• BEGIN
• :NEW.Student_TotalMarks :=
• :NEW.Student_EnglishMarks +
• :NEW.Student_PhysicsMarks +
• :NEW.Student_ChemistryMarks +
• :NEW.Student_MathsMarks;
•Auditing
• Step-2
Optimizer
• During optimization stage, database must perform a hard parse at least for one unique DML statement and perform optimization
during this parse. This database never optimizes DDL unless it includes a DML component such as subquery that require
optimization.
• It is a process in which multiple query execution plan for satisfying a query are examined and most efficient query plan is satisfied
for execution.
•
Database catalog stores the execution plans and then optimizer passes the lowest cost plan for execution.
• Row Source Generation
• The Row Source Generation is a software that receives a optimal execution
plan from the optimizer and produces an iterative execution plan that is
usable by the rest of the database.
• The iterative plan is the binary program that when executes by the sql
engine produces the result set.
• Step-3
Execution Engine
• Finally runs the query and display the required result.