Unit 2
Unit 2
Unit 2
o SQL stands for Structured Query Language. It is used for storing and managing data
in relational database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create,
read, update and delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL
as their standard database language.
o SQL allows users to query the database in a number of ways, using English-like
statements.
o
Rules:
SQL follows the following rules:
o Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
o Statements of SQL are dependent on text lines. We can use a single SQL statement on
one or multiple text line.
o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.
SQL process:
o When an SQL command is executing for any RDBMS, then the system figure out the
best way to carry out the request and the SQL engine determines that how to interpret
the task.
o In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query
engine won't handle logical files.
Characteristics of SQL
o SQL is easy to learn.
o SQL is used to access data from relational database management systems.
o SQL can execute queries against the database.
o SQL is used to describe the data.
o SQL is used to define the data in the database and manipulate it when needed.
o SQL is used to create and drop the database and table.
o SQL is used to create a view, stored procedure, function in a database.
o SQL allows users to set permissions on tables, procedures, and views.
Advantages of SQL
There are the following advantages of SQL:
High speed
Using the SQL queries, the user can quickly and efficiently retrieve a large amount of records
from a database.
No coding needed
In the standard SQL, it is very easy to manage the database system. It doesn't require a
substantial amount of code to manage the database system.
Portability
SQL can be used in laptop, PCs, server and even some mobile phones.
Interactive language
SQL is a domain language used to communicate with the database. It is also used to receive
answers to the complex questions in seconds.
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
Datatype of SQL:
1. Binary Datatypes
There are Three types of binary Datatypes which are given below:
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.
float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.
Data Description
type
Datatype Description
date It is used to store the year, month, and days value.
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also used
to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify
the table, set permission for users.
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
15.2M
343
Example:
1.
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Example
c. 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.
Syntax:
To add a new column in the table
EXAMPLE
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.
Syntax:
Example:
o DML commands are used to modify the database. It is responsible for all form of changes in
the database.
o 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.
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
Syntax:
Or
For example:
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
1.
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
Syntax:
For example:
Example
1.
Example
These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause.
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
SQL Operator
There are various types of SQL operator:
- It is used to subtract the right-hand operand from the left-hand a-b will give 10
operand.
* It is used to multiply the value of both operands. a*b will give 200
/ It is used to divide the left-hand operand by the right-hand a/b will give 2
operand.
% It is used to divide the left-hand operand by the right-hand a%b will give 0
operand and returns reminder.
!= It checks if two operands values are equal or not, if values are not equal, (a!=b) is true
then condition becomes true.
<> It checks if two operands values are equal or not, if values are not equal (a<>b) is true
then condition becomes true.
> It checks if the left operand value is greater than right operand value, if yes (a>b) is not
then condition becomes true. true
< It checks if the left operand value is less than right operand value, if yes (a<b) is true
then condition becomes true.
>= It checks if the left operand value is greater than or equal to the right (a>=b) is not
operand value, if yes then condition becomes true. true
<= It checks if the left operand value is less than or equal to the right operand (a<=b) is true
value, if yes then condition becomes true.
!< It checks if the left operand value is not less than the right operand value, (a!=b) is not
if yes then condition becomes true. true
!> It checks if the left operand value is not greater than the right operand (a!>b) is true
value, if yes then condition becomes true.
Operator Description
BETWEEN It is used to search for values that are within a set of values.
IN It compares a value to that specified list value.
SQL Table
o SQL Table is a collection of data which is organized in terms of rows and columns. In
DBMS, the table is known as relation and row as a tuple.
o Table is a simple form of data storage. A table is also considered as a convenient
representation of relations.
In the above table, "EMPLOYEE" is the table name, "EMP_ID", "EMP_NAME", "CITY",
"PHONE_NO" are the column names. The combination of data of multiple columns forms a
row, e.g., 1, "Kristen", "Washington" and 7289201223 are the data of one row.
Operation on Table
1. Create table
2. Drop table
3. Delete table
4. Rename table
Syntax
Example
If you create the table successfully, you can verify the table by looking at the message by the
SQL server. Else you can use DESC command as follows:
Now you have an EMPLOYEE table in the database, and you can use the stored information
related to the employees.
Drop table
A SQL drop table is used to delete a table definition and all the data from a table. When this
command is executed, all the information available in the table is lost forever, so you have to
very careful while using this command.
Syntax
Firstly, you need to verify the EMPLOYEE table using the following command:
This table shows that EMPLOYEE table is available in the database, so we can drop it as
follows:
Now, we can check whether the table exists or not using the following command:
Syntax
Example
If you don't specify the WHERE condition, it will remove all the rows from the table.
Syntax
Here, the expression is the field name of the table that you want to select data from.
Use the following syntax to select all the fields available in the table:
Example:
EMPLOYEE
To fetch the EMP_ID of all the employees, use the following query:
Output
EMP_ID
EMP_NAME SALARY
Kristen 150000
Russell 200000
Angelina 600000
Robert 350000
Christian 260000
To fetch all the fields from the EMPLOYEE table, use the following query:
Output
Sample Table
EMPLOYEE
Syntax
History of Java
Query
1. INSERT INTO EMPLOYEE VALUES (6, 'Marry', 'Canada', 600000, 48);
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
Query
1.
INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40)
;
Output: After executing this query, the table will look like:
Syntax
1. UPDATE table_name
2. SET column1 = value1, column2 = value2, ...
3. WHERE condition;
Sample Table
EMPLOYEE
HTML Tutorial
Syntax
1. UPDATE table_name
2. SET column_name = value
3. WHERE condition;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Emma'
3. WHERE SALARY = 500000;
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
1. UPDATE table_name
2. SET column_name = value1, column_name2 = value2
3. WHERE condition;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Kevin', City = 'Boston'
3. WHERE EMP_ID = 5;
Output
Syntax
1. UPDATE table_name
2. SET column_name = value1;
Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Harry';
Output
Syntax
Sample Table
EMPLOYEE
Query
Output: After executing this query, the EMPLOYEE table will look like:
Query
Output: After executing this query, the EMPLOYEE table will look like:
Syntax
Query
Output: After executing this query, the EMPLOYEE table will look like:
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
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:
Query:
Just like table query, we can query the view to view the data.
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
Example:
SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database very fast.
o An Index is used to speed up select queries and where clauses. But it shows down the data
input with insert and update statements. Indexes can be created or dropped without affecting
the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain topic, you first
have to refer to the index, which alphabetically lists all the topics and then referred to one or
more specific page numbers.
Syntax
Example
Syntax
1. CREATE UNIQUE INDEX index_name
2. ON table_name (column1, column2, ...);
Example
Syntax
Example
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause,
HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and
the inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be
used to perform the same function as ORDER BY command.
Syntax
2
1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
Syntax:
Example
Now use the following syntax to copy the complete EMPLOYEE table into the
EMPLOYEE_BKP table.
Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
Example
1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
Syntax
Example
This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
1 John 20 US 2000.00
SQL Clauses
The following are the various SQL clauses:
1. GROUP BY
o SQL GROUP BY statement is used to arrange identical data into groups. The GROUP BY
statement is used with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes
the ORDER BY clause.
o The GROUP BY statement is used with aggregation function.
Syntax
1. SELECT column
2. FROM table_name
3. WHERE conditions
4. GROUP BY column
5. ORDER BY column
Sample table:
PRODUCT_MAST
18.2M
299
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example:
Output:
Com1 5
Com2 3
Com3 2
2. HAVING
o HAVING clause is used to specify a search condition for a group or an aggregate.
o Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you can
use HAVING function like a WHERE clause.
Syntax:
Example:
Output:
Com1 5
Com2 3
3. ORDER BY
o The ORDER BY clause sorts the result-set in ascending or descending order.
o It sorts the records in ascending order by default. DESC keyword is used to sort the records in
descending order.
Syntax:
Where
CUSTOMER
12 Kathrin US
23 David Bangkok
34 Alina Dubai
45 John UK
56 Harry US
1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME;
Output:
34 Alina Dubai
23 David Bangkok
56 Harry US
45 John UK
12 Kathrin US
Output:
12 Kathrin US
45 John UK
56 Harry US
23 David Bangkok
34 Alina Dubai
o COUNT function is used to Count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
Sample Table
EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE
PROJECT
10 Sec
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and
the matched values from the left table. If there is no matching in both tables, it will return
NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
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:
o Implicit Cursors
o Explicit Cursors
These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.
10 Sec
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.
The following table soecifies the status of the cursor with each of its attribute.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect at least one row or more rows or a SELECT INTO statement
returned one or more rows. Otherwise it returns FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect no row, or a SELECT INTO statement return no rows. Otherwise
it returns FALSE. It is a just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is
automatically closed after executing its associated SQL statements.
%ROWCOUNT It returns the number of rows affected by DML statements like INSERT,
DELETE, and UPDATE or returned by a SELECT INTO statement.
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.
Now, if you check the records in customer table, you will find that the rows are updated.
1. 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.
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:
1. Close cursor_name;
PL/SQL Explicit Cursor Example
Explicit cursors are defined by programmers to gain more control over the context area. It is
defined in the declaration section of the PL/SQL block. It is created on a SELECT statement
which returns more than one row.
Let's take an example to demonstrate the use of explicit cursor. In this example, we are using
the already created CUSTOMERS table.
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;
7. BEGIN
8. OPEN c_customers;
9. LOOP
10. FETCH c_customers into c_id, c_name, c_addr;
11. EXIT WHEN c_customers%notfound;
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
13. END LOOP;
14. CLOSE c_customers;
15. END;
16. /
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
o System-defined Exceptions
o User-defined Exceptions
Nested Structure in C
Keep Watching
1. DECLARE
2. <declarations section>
3. BEGIN
4. <executable command(s)>
5. EXCEPTION
6. <exception handling goes here >
7. WHEN exception1 THEN
8. exception1-handling-statements
9. WHEN exception2 THEN
10. exception2-handling-statements
11. WHEN exception3 THEN
12. exception3-handling-statements
13. ........
14. WHEN others THEN
15. exception3-handling-statements
16. END;
1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /
After the execution of above code at SQL Prompt, it produces the following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.
Note: You get the result "No such customer" because the customer_id used in the above
example is 8 and there is no cutomer having id value 8 in that table.
If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For a
demo example: here, we are using the id 5.
1. DECLARE
2. c_id customers.id%type := 5;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /
After the execution of above code at SQL prompt, you will get the following result:
Name: alex
Address: paris
PL/SQL procedure successfully completed.
Raising Exceptions
In the case of any internal database error, exceptions are raised by the database server
automatically. But it can also be raised explicitly by programmer by using command RAISE.
1. DECLARE
2. exception_name EXCEPTION;
3. BEGIN
4. IF condition THEN
5. RAISE exception_name;
6. END IF;
7. EXCEPTION
8. WHEN exception_name THEN
9. statement;
10. END;
1. DECLARE
2. my-exception EXCEPTION;
CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in the "WHEN"
clauses of a CASE statement is selected, and there is
no else clause.
INVALID_CURSOR 01001 -1001 It is raised when attempts are made to make a cursor
operation that is not allowed, such as closing an
unopened cursor.
PL/SQL 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 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:
Creating a trigger:
Syntax for creating trigger:
1. CREATE [OR REPLACE ] TRIGGER trigger_name
2. {BEFORE | AFTER | INSTEAD OF }
3. {INSERT [OR] | UPDATE [OR] | DELETE}
4. [OF col_name]
5. ON table_name
6. [REFERENCING OLD AS o NEW AS n]
7. [FOR EACH ROW]
8. WHEN (condition)
9. DECLARE
10. Declaration-statements
11. BEGIN
12. Executable-statements
13. EXCEPTION
14. Exception-handling-statements
15. END;
Here,
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:
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. /
Output:
Note: As many times you executed this code, the old and new both salary is incremented by
5000 and hence the salary difference is always 5000.
After the execution of above code again, you will get the following result.
Important Points
Following are the two very important point and should be noted carefully.
o OLD and NEW references are used for record level triggers these are not avialable for table
level triggers.
o If you want to query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial changes are
applied and the table is back in a consistent state.
that emphasizes on the concept of what to for the data management rather how
notations. It is an integral part of the relational data model. The relational calculus
in DBMS uses specific terms such as tuple and domain to describe the queries.
Some of the other related common terminologies for relational calculus are
variables.
Tuple and domain are the major components of relational calculus. A result tuple
Variables that make the formula evaluate to be true. There are two types of
Both the types of relational calculus are semantically similar for operating in
DBMS data retrieval definitions. We will discuss each type of relational calculus
with some database table examples to represent the syntax and its uses.
TRC
Tuple relational calculus works on filtering the tuples based on the specified
conditions.TRC is the variable range over the tuples and is a type of simple subset
of the first-order logic.TRC considers tuples as equal status as variables, and field
referencing can be used to select the tuple parts. It is represented using letter ‘T’
and conditions with the pipe symbol and enclosing curly braces.
Syntax of TRC:
{T | Conditions)
The TRC syntax supports to denote the Table names or relation names, defining
the tuple variables, and the column names. It uses the ‘.’ operator symbol to
TRC specifies the relation names with the Tuple variable name such as ’T’. Syntax
Relation(T)
For example, if the Product is the relation name, it can be denoted as Product(T).
Similarly, TRC has the provision to specify the conditions. The condition is
For instance, if the data need to be represented for the particular product id of
value 10, it can be denoted as T.product_id=10, where T is the tuple variable that
Now to represent the relational calculus to return the product name that has the
product id value as 10 from the product table, it can be denoted as with the tuple
variable T.
This relational calculus predicate describes what to do for getting the resultant
tuple from the database. The result of the tuple relational calculus for the Product
10 TV Unit 2
DRC
The domain regional calculus works based on the filtering of the domain and the
related attributes.DRC is the variable range over the domain elements or the filed
compared to TRC is tuple dependent. In DRC the formal variables are explicit for
represented as C1, C2,…, Cn and the condition related to the attributes can be
denoted as the formula defining the condition for fetching the F(C1, C2, …Cn )
DRC for the product name attribute from the Product table needs where the
The result of the domain relational calculus for the Product table will be
10 TV Unit 2
Some of the commonly used logical operator notations for DRC are ∧ for AND,∨
for OR, and ┓ for NOT. imilarly, the mathematical symbol ∈ refers to the relation