CS8481 DBMS RECORD FINAL Modfied
CS8481 DBMS RECORD FINAL Modfied
AIM:
To execute and verify Data Definition Language commands in DBMS.
PROGRAM:
SQL:
Structured query language pronounced as (SEQUEL). This language is used to communicate to oracle
database.
DBMS is software it helps to manage the database. It performs the following activities very easily.
Inserting the new data.
Examples of RDBMS:
ORACLE
SQL SERVER
DB2
MYSQL
SYBASE
TERA DATA
MS ACCESS
Structured Query Language (SQL)
Language
1
TCL Transaction Control
Data Definition Language (DDL) or Schema Definition Language, statements are used to
define thedatabase structure or schema.
the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
Transaction Control (TCL) statements are used to manage the changes made by DML
statements.It allows statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use
Data Types
SQL data type is an attribute that specifies type of data of any object. Each column, variable and
expression hasrelated data type in SQL.
You would use these data types while creating your tables. You would choose a particular data
type for atable column based on your requirement.
SQL Server offers six categories of data types for your use.
2
Exact Numeric Data Types
tinyint 0 255
bit 0 1
3
Date and Time Data Types
Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.
4
Unicode Character Strings Data Types
Maximum length
image 2,147,483,647 bytes. ( Variable
oflength Binary
Data)
5
Misc Data Types
Operators
An operator is a reserved word or a character used primarily in an SQL statement's WHERE
clause toperform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multipleconditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions.
6
SQL Arithmetic Operators:
b%a
Modulus - Divides left hand operand by right handoperand
% willgive0
and returns remainder
(a = b)is
Checks if the values of two operands are equal ornot, if yes
= not true.
then condition becomes true.
Checks if the value of left operand is greater thanthe value (a > b)is
> of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is greater thanor equal (a >= b)is
>= to the value of right operand, if yes thencondition becomes not true.
true.
7
Checks if the value of left operand is less than orequal to
(a <= b)is
<= the value of right operand, if yes then condition
true.
becomes true.
Operator Description
The ALL operator is used to compare a value to all values inanother value
ALL
set.
The AND operator allows the existence of multiple conditions inan SQL
AND
statement's WHERE clause.
The NOT operator reverses the meaning of the logical operator with which
NOT it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN,etc. This is a negate
operator.
8
SQL - CREATE Table
Creating a basic table involves naming the table and defining its columns and each column's data
Syntax:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
CONSTRAINT CONSTRAINTNAME CONSTRAINTKEYWORD1( one or more columns ),
CONSTRAINT CONSTRAINTNAME CONSTRAINTKEYWORD2( one or more columns ),
.
.
.);
CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want
tocreate 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 an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE statement and
theSELECT statement.
9
SQL> CREATE TABLE
CUSTOMERS( ID INT NOT
NULL,
NAME VARCHAR (20) NOT
NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
CONSTRAINT PK1 PRIMARY KEY
Example:
(ID)
Following is an example, which creates a CUSTOMERS table with ID as primary key and NOT NULL
arethe constraints showing that these fields can not be NULL while creating records in this table:
You can verify if your table has been created successfully by looking at the message displayed by the
SQLserver, otherwise you can use DESC command as follows:
| NO|| ||
| YES | | NULL|
| ADDRESS | char(25) |
| NULL|
|
| SALARY | decimal(18,2) | YES |
+++++++
5 rows in set (0.00 sec)
Now, you have CUSTOMERS table available in your database which you can use to store
requiredinformation related to customers.
10
The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:
The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows:
The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as follows:
The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as follows:
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows:
The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows:
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as follows:
The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows:
11
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as follows:
Example:
Consider the CUSTOMERS table having the following records:
++++++
| ID | NAME| AGE | ADDRESS| SALARY|
++++++
++++++
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
12
+++++++
| ID | NAME| AGE | ADDRESS| SALARY| SEX |
+++++++
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
++++++
| ID | NAME| AGE | ADDRESS| SALARY|
++++++
++++++
You can also use DROP TABLE command to delete complete table but it would remove complete table
structure form the database and you would need to re-create this table once again if you wish you
store somedata.
Syntax:
The basic syntax of TRUNCATE TABLE is as follows:
13
TRUNCATE TABLE table_name;
Example:
Consider the CUSTOMERS table having the following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
++++++
Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:
The SQL DROP TABLE statement is used to remove a table definition and all data, indexes, triggers,
constraints, and permission specifications for that table.
NOTE: You have to be careful while using this command because once a table is deleted then all
theinformation available in the table would also be lost forever.
14
Syntax:
Basic syntax of DROP TABLE statement is as follows:
Example:
Let us first verify CUSTOMERS table and then we would delete it from the database:
| NO|| ||
| YES | | NULL|
| ADDRESS | char(25) |
| NULL|
|
| SALARY | decimal(18,2) | YES |
+ + + + + + +
5 rows in set (0.00 sec)
This means CUSTOMERS table is available in the database, so let us drop it as follows:
Now, if you would try DESC command, then you would get error as follows:
Here, TEST is database name which we are using for our examples.
SQL – Constraints
Constraints are the rules enforced on data columns on table. These are used to limit the type of data that
can gointo a table. This ensures the accuracy and reliability of the data in the database. Constraints could
be column level or table level. Column level constraints are applied only to one column, whereas table
level
15
constraints are applied to the whole table.
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
CHECK Constraint : The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE statement or you can use
ALTER TABLE statement to create constraints even after the table is created.
Dropping Constraints:
Any constraint that you have defined can be dropped using the ALTER TABLE command with the
DROPCONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following
command:
Some implementations may provide shortcuts for dropping certain constraints. For example, to
drop theprimary key constraint for a table in Oracle, you can use the following command:
16
Integrity Constraints:
Integrity constraints are used to ensure accuracy and consistency of data in a relational database.
Dataintegrity is handled in a relational database through the concept of referential integrity.
There are many types of integrity constraints that play a role in referential integrity (RI). These
constraintsinclude Primary Key, Foreign Key, Unique Constraints and other constraints mentioned above.
SQL RENAME Statement
Some of the relational database management system (RDBMS) does not support this command,
because thisis not standardizing statement.
For example renaming a table through MS SQL Server you must use storage procedure
SP_RENAME.Syntax for SQL RENAME is:
As for Oracle may also be use the following option: ALTER TABLE
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
Here, column1, column2,...columnN are the names of the columns in the table into which you want to
insertdata.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the
columnsof the table. But make sure the order of the values is in the same order as the columns in the
table.
17
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:
You can create a record in CUSTOMERS table using second syntax as follows:
All the above statements would produce the following records in CUSTOMERS table:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
18
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
19
Populate one table using another table:
You can populate data into a table through select statement over another table provided another
ehas a set of fields, which are required to populate first table. Here is the syntax:
RESULT:
Thus DDL commands has been written, executed and the output was verified.
20
Ex . No 1 (b) DATA MANIPULATION LANGUAGEAND TCL
AIM:
To execute and verify DML Commands and various Transaction Control statements in DBMS.
PROGRAM:
SQL is equipped with data manipulation language (DML). DML modifies the database instance by
inserting, updating and deleting its data. DML is responsible for all forms data modification in a
database. SQL contains the following set of commands in its DML section −
SELECT/FROM/WHERE
INSERT INTO/VALUES
UPDATE/SET/WHERE
DELETE FROM/WHERE
These basic constructs allow database programmers and users to enter data and information into
the database and retrieve efficiently using a number of filter options.
SQL-SELECTQuery
SQL SELECT statement is used to fetch the data from a database table which returns data in the form
of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:
Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to
fetch allthe fields available in the field, then you can use the following syntax:
Example:
Consider the CUSTOMERS table having the following records:
21
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Following is an example, which would fetch ID, Name and Salary fields of the customers available in
CUSTOMERS table:
+ + + +
| ID | NAME | SALARY |
+ + + +
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
|6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+ + + +
If you want to fetch all the fields of CUSTOMERS table, then use the following query:
22
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
SQL-INSERTQuery
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
Here, column1, column2,...columnN are the names of the columns in the table into which you want to
insert data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the
columns of the table. But make sure the order of the values is in the same order as the columns in the
table.The SQL INSERT INTO syntax would be as follows:
23
Example:
Following statements would create six records in CUSTOMERS table:
You can create a record in CUSTOMERS table using second syntax as follows:
All the above statements would produce the following records in CUSTOMERS table:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
24
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Populateonetableusinganothertable:
You can populate data into a table through select statement over another table provided another
table has aset of fields, which are required to populate first table. Here is the syntax:
Syntax:
SQL-UPDATEQuery
The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows
would beaffected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2... , columnN = valueN
WHERE [condition];
Example:
Consider the CUSTOMERS table having the following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
25
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Following is an example, which would update ADDRESS for a customer whose ID is 6:
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi
| 3 | kaushik | 23 | Kota
| 4 | Chaitali | 25 | Mumbai| 1500.00 |
| 2000.00 |
| 6500.00 |
| 8500.00 |
| 4500.00 |
| 5 | Hardik | 27 | Bhopal | 10000.00 |
| 6 | Komal| 22 | Pune
| 7 | Muffy| 24 | Indore
++++++
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do notneed
to use WHERE clause and UPDATE query would be as follows:
+ + + + + +
26
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Pune
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal| 22 | Pune | 1000.00 |
| 1000.00 |
| 1000.00 |
| 7 | Muffy| 24 | Pune
++++++
SQL-DELETEQuery
The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records
wouldbe deleted.
Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:
Example:
Consider the CUSTOMERS table having the following records:
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi| 1500.00 |
| 3 | kaushik | 23 | Kota| 2000.00 |
| 4 | Chaitali | 25 | Mumbai| 6500.00 |
| 5 | Hardik | 27 | Bhopal| 8500.00 |
| 6 | Komal| 22 | MP | 4500.00 |
27
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE
clauseand DELETE query would be as follows:
You can also use DROP TABLE command to delete complete table but it would remove complete
table structure form the database and you would need to re-create this table once again if you wish
you store some data.
Syntax:
The basic syntax of TRUNCATE TABLE is as follows:
28
Example:
Consider the CUSTOMERS table having the following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:
SQL-Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you are
creating a record or updating a record or deleting a record from the table, then you are performing
transaction on the table. It is important to control transactions to ensure data integrity and to handle
database errors.
Practically, you will club many SQL queries into a group and you will execute all of them together as
a part of a transaction.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:
29
Atomicity: ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure, and previous operations are rolled
back to their former state.
Consistency: ensures that the database properly changes states upon a successfully
committed transaction.
Durability: ensures that the result or effect of a committed transaction persists in case of a
system failure.
Transaction Control:
There are following commands used to control transactions:
Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only. They cannot be used while creating tables or dropping them because these operations
are automatically commited in the database.
The COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK
command.
COMMIT;
Example:
Consider the CUSTOMERS table having the following records:
30
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
Following is the example which would delete records from the table having age = 25 and then
COMMITthe changes in the database.
As a result, two rows from the table would be deleted and SELECT statement would produce the
following result:
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota
| 2000.00 |
| 8500.00 |
| 5 | Hardik | 27 | Bhopal
| 4500.00 |
| 6 | Komal| 22 | MP
| 10000.00 |
| 7 | Muffy| 24 | Indore
++++++
TheROLLBACKCommand:
The ROLLBACK command is the transactional command used to undo transactions that have not
alreadybeen saved to the database.
31
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
ROLLBACK;
Example:
Consider the CUSTOMERS table having the following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Following is the example, which would delete records from the table having age = 25 and then
ROLLBACK the changes in the database.
As a result, delete operation would not impact the table and SELECT statement would
produce thefollowing result:
32
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the CUSTOMERS
table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any
SAVEPOINT at any time to return the appropriate data to its original state:
Example:
Consider the CUSTOMERS table having the following records:
33
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now that the three deletions have taken place, say 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:
34
SQL> SELECT * FROM CUSTOMERS;
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
6 rows selected.
TheRELEASESAVEPOINTCommand:
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undotransactions performed since the SAVEPOINT.
TheSETTRANSACTIONCommand:
The SET TRANSACTION command can be used to initiate a database transaction. This command is
usedto specify characteristics for the transaction that follows.
For example, you can specify a transaction to be read only, or read write.
RESULT:
Thus DML and TCL commands has been written, executed and output was verified.
35
Ex.No: 2(a) Database Querying – Simple queries, Nested queries, Sub queries and Joins
AIM :
To execute and verify the SQL commands for Simple queries, Nested queries, Sub queries.
SQL-ANDand OR ConjunctiveOperators
The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL
statement. These two operators are called as the conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the
same SQLstatement.
TheANDOperator
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
Syntax
The basic syntax of the AND operator with a WHERE clause is as follows −
Example
Consider the CUSTOMERS table having the following records −
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi
| 3 | kaushik | 23 | Kota | 1500.00 |
| 4 | Chaitali | 25 | Mumbai| 2000.00 |
| 6500.00 |
| 8500.00 |
| 5 | Hardik | 27 | Bhopal | 4500.00 |
| 6 | Komal| 22 | MP | 10000.00 |
| 7 | Muffy| 24 | Indore
++++++
Following is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS
table,where the salary is greater than 2000 and the age is less than 25 years −
36
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
+ + + +
| ID | NAME | SALARY |
+ + + +
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+ + + +
TheOROperator
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
Syntax
The basic syntax of the OR operator with a WHERE clause is as follows −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
37
The following code block hasa query, which would fetch the ID, Name and Salary fields from
theCUSTOMERS table, where the salary is greater than 2000 and the age is less than 25 years.
+ + + +
| ID | NAME | SALARY |
+ + + +
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+ + + +
TheSQLLIKEOperator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.There are two wildcards used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
combinations!LIKE Syntax
SELECT column1,column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR
operators. Here are some examples showing different LIKE operators with '%'
38
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName
Finds any values that have "or" in any position
LIKE'%or%'
WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' charactersin length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
DemoDatabase
Below is a selection from the "Customers" table in the Northwind sample database:
Alfreds
1 Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkist
e
Ana Trujillo Avda. de la
México
2 Emparedados Ana Trujillo Constituci 05021 Mexico
D.F.
yhelados ó n2222
39
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName starting with "a":
Example
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
The following SQL statement selects all customers with a CustomerName that have "or" in any position:
Example
The following SQL statement selects all customers with a CustomerName that have "r" in the
secondposition:
Example
The following SQL statement selects all customers with a CustomerName that starts with "a" and
are atleast 3 characters in length:
Example
The following SQL statement selects all customers with a ContactName that starts with "a" and
ends with"o":
Example
40
SELECT * FROM Customers
WHERE ContactName LIKE 'a
%o';
41
The following SQL statement selects all customers with a CustomerName that NOT starts with "a":
Example
Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE
clauseto search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
42
WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' charactersin length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement selects all customers with a City starting with "ber":
Example
The following SQL statement selects all customers with a City containing the pattern "es":
Example
43
44
The percent sign (%)
The underscore (_)
The percent sign represents zero, one or multiple characters. The underscore represents a single
number orcharacter. These symbols can be used in combinations.
Syntax
or
or
or
You can combine N number of conditions using AND or OR operators. Here, XXXX could be
anynumeric or string value.
Example
The following table has a few examples showing the WHERE part having different LIKE clause with
'%'and '_' operators –
45
Sr.No. Statement & Description
46
This would produce the following result −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+ + + + + +
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
47
Thoma WA1
4 Around the Horn 120 Hanover Sq. London UK
s Hardy 1DP
Berglund Christin S-
5 Berguvsvä gen 8 Luleå Sweden
s a 958
snabbkö Berglun 22
p d
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" and "UK":
Example
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
Example
The following SQL statement selects all customers that are from the same countries as the suppliers:
Example
The BETWEEN operator selects values within a given range. The values can be numbers, text, or
dates.The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
48
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
To display the products outside the range of the previous example, use NOT BETWEEN:
Example
The following SQL statement selects all products with a price BETWEEN 10 and 20. In addition; do
notshow products with a CategoryID of 1,2, or 3:
Example
49
The following SQL statement selects all products with a ProductName BETWEEN 'Carnarvon Tigers'
and'Mozzarella di Giovanni':
Example
The following SQL statement selects all products with a ProductName NOT BETWEEN 'Carnarvon
Tigers' and 'Mozzarella di Giovanni':
Example
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 7/4/1996 3
10249 81 6 7/5/1996 1
10250 34 4 7/8/1996 2
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
The following SQL statement selects all orders with an OrderDate BETWEEN '04-July-1996' and '09-
July-1996':
Example
50
SQL TOP, LIMIT or ROWNUM Clause
SQL-ORDERBYClause
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one ormore columns. Some databases sort the query results in an ascending order by default.
Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
Example
Consider the CUSTOMERS table having the following records –
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi
| 3 | kaushik | 23 | Kota | 1500.00 |
| 4 | Chaitali | 25 | Mumbai| 2000.00 |
| 6500.00 |
| 8500.00 |
| 5 | Hardik | 27 | Bhopal | 4500.00 |
| 6 | Komal| 22 | MP | 10000.00 |
| 7 | Muffy| 24 | Indore
++++++
The following code block has an example, which would sort the result in an ascending order by the
NAMEand the SALARY −
51
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 4 | Chaitali | 25 | Mumbai| 6500.00 |
| 5 | Hardik | 27 | Bhopal
| 3 | kaushik | 23 | Kota | 8500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 6 | Komal| 22 | MP | 1500.00 |
| 4500.00 |
| 10000.00 |
| 7 | Muffy| 24 | Indore
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
++++++
The following code block has an example, which would sort the result in the descending order by NAME.
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy| 24 | Indore
| 6 | Komal| 22 | MP | 10000.00 |
| 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
++++++
SQL-DistinctKeyword
The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all
theduplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such
records,it makes more sense to fetch only those unique records instead of fetching duplicate records.
Syntax
The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows −
52
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Example
Consider the CUSTOMERS table having the following records −
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi
| 3 | kaushik | 23 | Kota | 1500.00 |
| 4 | Chaitali | 25 | Mumbai| 2000.00 |
| 6500.00 |
| 8500.00 |
| 5 | Hardik | 27 | Bhopal | 4500.00 |
| 6 | Komal| 22 | MP | 10000.00 |
| 7 | Muffy| 24 | Indore
+ + + + + +
First, let us see how the following SELECT query returns the duplicate salary records.
This would produce the following result, where the salary (2000) is coming twice which is a
duplicaterecord from the original table.
++
| SALARY |
++
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
++
Now, let us use the DISTINCT keyword with the above SELECT query and then see the result.
53
This would produce the following result where we do not have any duplicate entry.
+ +
| SALARY |
+ +
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+ +
SQL-SORTING Results
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one ormore columns. Some databases sort the query results in an ascending order by default.
Syntax
The basic syntax of the ORDER BY clause which would be used to sort the result in an
ascending ordescending order is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure that whatever column you
areusing to sort, that column should be in the column-list.
Example
Consider the CUSTOMERS table having the following records −
54
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Following is an example, which would sort the result in an ascending order by NAME and SALARY.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
55
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal| 22 | MP | 4500.00 |
| 10000.00 |
| 7 | Muffy| 24 | Indore
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
++++++
The following code block has an example, which would sort the result in a descending order by NAME.
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy| 24 | Indore
| 6 | Komal| 22 | MP
| 10000.00 |
| 4500.00 |
| 1500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 8500.00 |
| 5 | Hardik | 27 | Bhopal | 6500.00 |
| 4 | Chaitali | 25 | Mumbai
++++++
To fetch the rows with their own preferred order, the SELECT query used would be as follows −
56
This would produce the following result −
++++++
| ID | NAME| AGE | ADDRESS | SALARY |
++++++
| 2 | Khilan | 25 | Delhi
| 5 | Hardik | 27 | Bhopal | 1500.00 |
| 3 | kaushik | 23 | Kota | 8500.00 |
| 6 | Komal| 22 | MP | 2000.00 |
| 4500.00 |
| 6500.00 |
| 4 | Chaitali | 25 | Mumbai
| 7 | Muffy| 24 | Indore| 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
++++++
This will sort the customers by ADDRESS in your ownoOrder of preference first and in a natural
orderfor the remaining addresses. Also, the remaining Addresses will be sorted in the reverse
alphabetical order.
The MIN() function returns the smallest value of the selected column.
column.MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
57
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
10 boxes
1 Chais 1 1 18
x 20bags
2 Chang 1 1 24 - 12 oz bottles 19
12 - 550 ml
3 Aniseed Syrup 1 2 10
bottles
Chef Anton's
4 2 2 48 - 6 oz jars 22
CajunSeasoning
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
The following SQL statement finds the price of the most expensive product:
Example
The COUNT() function returns the number of rows that matches a specified
column.COUNT() Syntax
58
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
10 boxes
1 Chais 1 1 18
x 20bags
2 Chang 1 1 24 - 12 oz bottles 19
12 - 550 ml
3 Aniseed Syrup 1 2 10
bottles
Chef Anton's
4 2 2 48 - 6 oz jars 22
CajunSeasoning
Example
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
59
Example
SELECT AVG(Price)
FROM Products;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
RESULT:
Thus the SQL commands for Simple queries, Nested queries, Sub queries has been written , executed and
output was verified.
60
EX.NO 2 (b) NESTED QUERIES AND QUERIES USING GROUP BY AND HAVING
CLAUSE AIM :
To execute and verify Nested Queries and Queries Using Group By and Having Clause.
PROGRAM:
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregatefunctions.
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
And a selection from the "Employees" table:
EmployeeID LastName FirstName BirthDate Photo Notes
61
SQL HAVING Example
Now we want to find if any of the employees has registered more than 10
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
OrdersINNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
Now we want to find if the employees "Davolio" or "Fuller" have registered more than 25
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
OrdersINNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR
LastName='Fuller'GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
1. SELECT column-names
2. FROM table-name
3. WHERE condition
4. GROUP BY column-names
5. HAVING condition
62
The general syntax with ORDER BY is:
1. SELECT column-names
2. FROM table-name
3. WHERE condition
4. GROUP BY column-names
5. HAVING condition
6. ORDER BY column-names
CUSTOMER
Id
FirstName
LastName
City
Country
Phone
Problem: List the number of customers in each country. Only include countries with more than 10
customers.
Country
Count
11 France
11 Germany
13 USA
CUSTOMER
Id
FirstName
LastName
63
City
Country
Phone
Problem: List the number of customers in each country, except the USA, sorted high to
low.Only include countries with 9 or more customers.
1. FROM Customer
2. WHERE Country <> 'USA'
3. GROUP BY Country
4. HAVING COUNT(Id) >= 9
5. ORDER BY COUNT(Id) DESC
Count Country
11 France
11 Germany
9 Brazil
ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount
Problem: List all customer with average orders between $1000 and $1200.
64
Average FirstName LastName
1081.215000 Miguel Angel Paolino
1063.420000 Isabel de Castro
1008.440000 Alexander Feuer
1062.038461 Thomas Hardy
1107.806666 Pirkko Koskitalo
1174.945454 Janete Limeira
1073.621428 Antonio Moreno
1065.385000 Rita Mü ller
1183.010000 José Pedro Freyre
1057.386666 Carine Schmitt
SQL-GroupBy
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical
datainto groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY
clause.
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
Example:
Consider the CUSTOMERS table is having the following records:
65
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
If you want to know the total amount of salary on each customer, then GROUP BY query would
be as follows:
+++
| NAME| SUM(SALARY) |
+++
| Chaitali |6500.00 |
| Hardik |8500.00 |
| kaushik |2000.00 |
| Khilan1500.00 |
| Komal4500.00 |
| Muffy10000.00 |
| Ramesh |2000.00 |
+++
Now, let us have following table where CUSTOMERS table has the following records with
duplicatenames:
66
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now again, if you want to know the total amount of salary on each customer, then GROUP BY
querywould be as follows:
+++
| NAME| SUM(SALARY) |
+++
| Hardik |8500.00 |
| kaushik |8500.00 |
| Komal |4500.00 |
| Muffy |10000.00 |
| Ramesh |3500.00 |
+++
67
NESTED QUERIES & QUERIES USING GROUP BY AND OTHER CLAUSES
SAMPLES QUERIES
PROBLEM STATEMENTS:
1. Find the name of the institute in which the person studied and developed the costliest package.
INPUT: SQL> SELECT SPLACE, PNAME FROM STUDY WHERE PNAME = (SELECT PNAMEFROM
SOFTWARE
WHERE SCOST = (SELECT MAX (SCOST) FROM SOFTWARE);
OUTPUT:
SPLACE PNAME
SAHBHARI MARY
2. Find the salary and institute of a person who developed the highest selling package.
INPUT: SQL> SELECT STUDY.PNAME, SAL, SPLACE FROM STUDY, PROGRAMMER WHERE
OUTPUT:
3. How many packages were developed by the person who developed the cheapest package.
INPUT: SQL> SELECT PNAME, COUNT (TITLE) FROM SOFTWARE WHERE DCOST = (SELECT
68
MIN(DCOST) FROM SOFTWARE) GROUP BY PNAME;
RESULT
PNAME COUNT(TITLE)
VIJAY 1
4. Calculate the amount to be recovered for those packages whose development cost has not
yet recovered.
INPUT: SQL>SELECT TITLE, (DCOST-SCOST) FROM SOFTWARE WHERE DCOST > SCOST;
5. Display the title, scost, dcost, difference of scost and dcost in the descending order of difference.
INPUT: SQL> SELECT TITLE, SCOST, DCOST, (SCOST - DCOST) FROM SOFTWARE
DESCENDING ORDER BY (SCOST-DCOST);
ANALYST 6000
CLERK 23050
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
assistant 2200
clerk 2003
7 rows selected.
INPUT: SQL>SELECT ENAME, SAL FROM EMP WHERE SAL IN (SELECT MIN(SAL) FROM EMPGROUP
BY MGR);
OUTPUT:
ENAME SAL
CHAI 3
JAMES 950
MILLER 1000
69
ADAMS 1100
russel 2200
5 rows selected.
9. Display number of employees working in each department and their department name.
INPUT: SQL> SELECT DNAME, COUNT (ENAME) FROM EMP, DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO
GROUP BY DNAME;
OUTPUT:
DNAME COUNT(ENAME)
ACCOUNTING 3
RESEARCH 5
SALES 9
OUTPUT:
PNAME SUM(SCOST)
john 12000
kamala 12000
raju 12333
3 rows
selected.
OUTPUT:
PNAME COUNT(TITLE)
john 1
kamala 1
raju 1
ramana 1
rani 1
5 rows
selected.
70
12. Display the number of packages in each language for which the development cost is less
than thousand.
INPUT: SQL>SELECT DEVIN, COUNT(TITLE) FROM SOFTWARE WHERE DCOST < 1000 GROUPBY
DEVIN;
OUTPUT:
DEVIN COUNT(TITLE)
cobol 1
BDPS 2
BITS 1
BNRILLIANI 1
COIT 1
HYD 1
5 rows
selected.
13. How many copies of package have the least difference between development and selling cost,
weresold?
INPUT: SQL>select SOLD FROM SOFTWARE WHERE SCOST – DCOST=(SELECT MIN(SCOST –DCOST)
FROM SOFTWARE);
OUTPUT:
SOLD
11
INPUT: SQL>SELECT TITLE FROM SOFTWARE WHERE DEVIN = ‘PASCAL’ AND DCOST =(SELECT
MAX(DCOST) FROM SOFTWARE WHERE DEVIN = ‘PASCAL’);
OUTPUT:
no rows selected
INPUT: SQL>SELECT DEVIN, COUNT (*) FROM SOFTWARE GROUP BY DEVIN HAVING
COUNT(*)
= (SELECT MAX(COUNT(*) ) FROM SOFTWARE GROUP BY DEVIN);
71
OUTPUT:
DEVIN COUNT(*)
jsp 2
16. Who are the male programmers earning below the average salary of female programmers?
INPUT: SQL>SELECT PNAME FROM PROGRAMMER WHERE SAL < (SELECT AVG(SAL) FROM
PROGRAMMER WHERE SEX = ‘F’) AND SEX = ‘M’;
OUTPUT:
PNAME
vijay
17. Display the details of software developed by the male programmers earning more than 3000/-.
OUTPUT:
no rows selected
18. Display the details of software developed in c language by female programmers of Pragathi.
INPUT: SQL>SELECT SOFTWARE.PNAME, TITLE, DEVIN, SCOST, DCOST, SOLD FROM PROGRAMMER,
SOFTWARE, STUDY WHERE DEVIN = ‘C’ AND SEX =’F’ AND SPLACE = ‘PRAGATHI’ AND
PROGRAMMER.PNAME = SOFTWARE.PNAME AND SOFTWARE.PNAME = STUDY.PNAME;
RESULT:
Thus the Nested Queries and Queries Using Group By and Having Clause has been executed and output
was verified.
72
Ex.No:3 VIEWS, SEQUENCES, SYNONYMS
AIM:
To create view, execute and verify the various operations on views.
PROGRAM:
SQL CREATE VIEW Statement
A view contains rows and columns, just like a real table. The fields in a view are fields from one or
morereal tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data
were coming from one single table.
VIEW view_name AS
SELECT column1,column2, ...
FROM table_name
WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
SQLstatement, every time a user queries a view.
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued)
from the"Products" table. The view is created with the following SQL:
73
Another view in the Northwind sample database selects every product in the "Products" table with
a unitprice higher than the average unit price:
Another view in the Northwind database calculates the total sale for each category in 1997. Note that
thisview selects its data from another view called "Product Sales for 1997":
We can also add a condition to the query. Let's see the total sale only for the category
AS
SELECT column1,column2, ...
FROM table_name
WHERE condition;
Now we want to add the "Category" column to the "Current Product List" view. We will update the
viewwith the following SQL:
74
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;
SQL Dropping a View
Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are
justused to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So, only create indexes on columns that will be frequently searched against.
Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax
forcreating indexes in your database.
The SQL statement below creates an index named "idx_lastname" on the "LastName" column
in the"Persons" table:
75
CREATE INDEX idx_lastname
ON Persons (LastName);
If you want to create an index on a combination of columns, you can list the column names
within theparentheses, separated by commas:
MS Access:
SQL Server:
DB2/Oracle:
MySQL:
CREATE SYNONYM
Purpose
Use the CREATE SYNONYM statement to create a synonym, which is an alternative name for a table,
view, sequence, procedure, stored function, package, materialized view, Java class schema object,
user- defined object type, or another synonym.
Synonyms provide both data independence and location transparency. Synonyms permit
applications to function without modification regardless of which user owns the table or view and
regardless of which database holds the table or view. However, synonyms are not a substitute for
privileges on database objects. Appropriate privileges must be granted to a user before the user can
use the synonym.
76
You can refer to synonyms in the following DML statements:
SELECT, INSERT, UPDATE, DELETE, FLASHBACK TABLE, EXPLAIN PLAN, and LOCK TABLE.
You can refer to synonyms in the following DDL statements: AUDIT, NOAUDIT, GRANT, REVOKE,
and COMMENT.
Prerequisites
To create a private synonym in your own schema, you must have the CREATE SYNONYM system
privilege.
To create a PUBLIC synonym, you must have the CREATE PUBLIC SYNONYM system privilege.
Examples
CREATE SYNONYM: Examples To define the synonym offices for the table locations in the schema hr,
issue the following statement:
CREATE SYNONYM
To create a PUBLIC synonym for the employees table in the schema hr on the remote database, you
couldissue the following statement:
FOR [email protected];
A synonym may have the same name as the underlying object, provided the underlying object is
contained in another schema.
If the user sh then issues the following statement, then the database returns the count of
rowsfrom sh.customers:
77
SELECT COUNT(*) FROM customers;
To retrieve the count of rows from oe.customers, the user sh must preface customers with the
schemaname. (The user sh must have select permission on oe.customers as well.)
If the user hr's schema does not contain an object named customers, and if hr has select
permission on oe.customers, then hr can access thecustomers table in oe's schema by using the
public synonym customers:
CREATE SEQUENCE
Purpose
Use the CREATE SEQUENCE statement to create a sequence, which is a database object from which
multiple users may generate unique integers. You can use sequences to automatically generate
primary key values.
When a sequence number is generated, the sequence is incremented, independent of the transaction
committing or rolling back. If two users concurrently increment the same sequence, then the
sequence numbers each user acquires may have gaps, because sequence numbers are being
generated by the other user. One user can never acquire the sequence number generated by another
user. After a sequence value is generated by one user, that user can continue to access that value
regardless of whether the sequence is incremented by another user.
Sequence numbers are generated independently of tables, so the same sequence can be used for one
or for multiple tables. It is possible that individual sequence numbers will appear to be skipped,
because theywere generated and used in a transaction that ultimately rolled back. Additionally, a
single user may not realize that other users are drawing from the same sequence.
After a sequence is created, you can access its values in SQL statements with
the CURRVAL pseudocolumn, which returns the current value of the sequence, or
the NEXTVAL pseudocolumn, which increments the sequence and returns the new value.
Semantics
schema
Specify the schema to contain the sequence. If you omit schema, then Oracle Database creates the
sequencein your own schema.
78
sequence
To create a sequence that increments without bound, for ascending sequences, omit
the MAXVALUE parameter or specify NOMAXVALUE. For descending sequences, omit the
MINVALUE parameter or specify the NOMINVALUE.
To create a sequence that stops at a predefined limit, for an ascending sequence, specify a value
for the MAXVALUE parameter. For a descending sequence, specify a value for the MINVALUE
parameter. Also specify NOCYCLE. Any attempt to generate a sequence number once the sequence
has reached its limit results in an error.
To create a sequence that restarts after reaching a predefined limit, specify values for both
the MAXVALUE and MINVALUE parameters. Also specify CYCLE. If you do not specify MINVALUE,
then it defaults to NOMINVALUE, which is the value 1.
INCREMENT BY Specify the interval between sequence numbers. This integer value can be any
positive or negative integer, but it cannot be 0. This value can have 28 or fewer digits. The absolute of
this value must be less than the difference of MAXVALUE and MINVALUE. If this value is negative,
then the sequence descends. If the value is positive, then the sequence ascends. If you omit this
clause, then the interval defaults to 1.
START WITH Specify the first sequence number to be generated. Use this clause to start an
ascending sequence at a value greater than its minimum or to start a descending sequence at a value
less than its maximum. For ascending sequences, the default value is the minimum value of the
sequence. For descending sequences, the default value is the maximum value of the sequence. This
integer value can have28 or fewer digits.
Note:
This value is not necessarily the value to which an ascending cycling sequence cycles after reaching its
maximum or minimum value.
MAXVALUE Specify the maximum value the sequence can generate. This integer value can have 28
or fewer digits. MAXVALUE must be equal to or greater thanSTART WITH and must be greater
than MINVALUE.
MINVALUE Specify the minimum value of the sequence. This integer value can have 28 or fewer
digits. MINVALUE must be less than or equal to START WITH and must be less than MAXVALUE.
CYCLE Specify CYCLE to indicate that the sequence continues to generate values after reaching
79
eitherits maximum or minimum value. After an ascending sequence reaches its maximum value, it
generates its minimum value. After a descending sequence reaches its minimum, it generates its
maximum value.
NOCYCLE Specify NOCYCLE to indicate that the sequence cannot generate more values after reaching
its maximum or minimum value. This is the default.
CACHE Specify how many values of the sequence the database preallocates and keeps in memory for
faster access. This integer value can have 28 or fewer digits. The minimum value for this parameter
is 2.For sequences that cycle, this value must be less than the number of values in the cycle. You
cannot cache more values than will fit in a given cycle of sequence numbers. Therefore, the maximum
value allowed for CACHE must be less than the value determined by the following formula:
If a system failure occurs, then all cached sequence values that have not been used in committed
DMLstatements are lost. The potential number of lost values is equal to the value of the CACHE
parameter.
Note:
Oracle recommends using the CACHE setting to enhance performance if you are using sequences in an
Oracle Real Application Clusters environment.
NOCACHE Specify NOCACHE to indicate that values of the sequence are not preallocated. If you omit
both CACHE and NOCACHE, then the database caches 20 sequence numbers by default.
ORDER Specify ORDER to guarantee that sequence numbers are generated in order of request. This
clause is useful if you are using the sequence numbers as timestamps. Guaranteeing order is usually
not important for sequences used to generate primary keys.
ORDER is necessary only to guarantee ordered generation if you are using Oracle Real Application
Clusters. If you are using exclusive mode, then sequence numbers are always generated in order.
NOORDER Specify NOORDER if you do not want to guarantee sequence numbers are generated in
orderof request. This is the default.
Example
Creating a Sequence: Example The following statement creates the sequence customers_seq in the
sample schema oe. This sequence could be used to provide customer ID numbers when rows are
added to the customers table.
80
CREATE SEQUENCE
1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
The first reference to customers_seq.nextval returns 1000. The second returns 1001. Each subsequent
reference will return a value 1 greater than the previous reference.
DROP SEQUENCE
Purpose
Use the DROP SEQUENCE statement to remove a sequence from the database.
You can also use this statement to restart a sequence by dropping and then re-creating it. For
example, if you have a sequence with a current value of 150 and you would like to restart the
sequence with a value of 27, then you can drop the sequence and then re-create it with the same
name and aSTART WITH value of 27.
Example
Dropping a Sequence: Example The following statement drops the sequence customers_seq
owned bythe user oe, which was created in "Creating a Sequence: Example". To issue this statement,
you must eitherbe connected as user oe or have the DROP ANY SEQUENCE system privilege:
ALTER SEQUENCE
Purpose
Use the ALTER SEQUENCE statement to change the increment, minimum and maximum values,
cachednumbers, and behavior of an existing sequence. This statement affects only future sequence
numbers.
Examples
ALTER SEQUENCE
customers_seq MAXVALUE
1500;
81
This statement turns on CYCLE and CACHE for the customers_seq sequence:
ALTER SEQUENCE
customers_seq CYCLE
CACHE 5;
Finding the next value of a sequence: Example This example selects the next value of the
employeesequence in the sample schema hr:
SELECT employees_seq.nextval
FROM DUAL;
Inserting sequence values into a table: Example This example increments the employee sequence
anduses its value for a new employee inserted into the sample table hr.employees:
30);
Example This example adds a new order with the next order number to the master order table. It
then addssuborders with this number to the detail order table:
82
INSERT INTO orders (order_id, order_date, customer_id)
106);
RESULT:
Thus the Queries for Views, Synonyms and Sequences has been written,executed and output was
verified.
83
Ex. No: 4 Oracle PL/SQL Cursor: Implicit, Explicit, Cursor FOR Loop
AIM:
To execute and verify cursors in DBMS to retrieve data from a result set, one row at a time.
PROGRAM:
A Cursor is a pointer to this context area. Oracle creates context area for processing an SQL
statement which contains all information about the statement.
PL/SQL allows the programmer to control the context area through the cursor. A cursor holds the
rows returned by the SQL statement. The set of rows the cursor holds is referred as active set.
These cursors can also be named so that they can be referred from another place of the code.
Implicit Cursor
Explicit Cursor
Cursor Attributes
Implicit Cursor
Explicit Cursor
Implicit Cursor
Whenever any DML operations occur in the database, an implicit cursor is created that holds the
rows affected, in that particular operation. These cursors cannot be named and, hence they cannot
be controlled or referred from another place of the code. We can refer only to the most recent
cursor through the cursor attributes.
Explicit Cursor
Programmers are allowed to create named context area to execute their DML operations to get
more control over it. The explicit cursor should be defined in the declaration section of the PL/SQL
block, and it is created for the 'SELECT' statement that needs to be used in the code.
84
Declaring the cursor
Declaring the cursor simply means to create one named context area for the 'SELECT' statement
that is defined in the declaration part. The name of this context area is same as the cursor name.
Opening Cursor
Opening the cursor will instruct the PL/SQL to allocate the memory for this cursor. It will make
The cursor ready to fetch the records.
In this process, the 'SELECT' statement is executed and the rows fetched is stored in the allocated
memory. These are now called as active sets. Fetching data from the cursor is a record-level activity
that means we can access the data in a record-by-record way.
Each fetch statement will fetch one active set and holds the information of that particular record.
This statement is same as 'SELECT' statement that fetches the record and assigns to the variable in
the 'INTO' clause, but it will not throw any exceptions.
Once all the record is fetched now, we need to close the cursor so that the memory allocated to this
context area will be released.
Syntax:
DECLARE
<cursor_variable
declaration>BEGIN
OPEN <cursor_name>;
CLOSE <cursor_name>;
END;
In the above syntax, the declaration part contains the declaration of the cursor and the cursor
variable inwhich the fetched data will be assigned.
The cursor is created for the 'SELECT' statement that is given in the cursor declaration.
85
In execution part, the declared cursor is opened, fetched and closed.
Cursor Attributes
Both Implicit cursor and the explicit cursor has certain attributes that can be accessed. These
attributes give more information about the cursor operations. Below are the different cursor
attributes and their usage.
Cursor Description
Attribut
e
%FOUND It returns the Boolean result 'TRUE' if the most recent fetch
operation fetched a record successfully, else it will return FALSE.
We will project all the employee's name from emp table using a cursor. We will also use cursor attribute
to set the loop to fetch all the record from the cursor.
86
DECLARE
lv_emp_name emp.emp_name%type;
BEGIN
OPEN guru99_det;
LOOP
IF guru99_det%NOTFOUND
THEN
EXIT;
END IF;
Dbms_output.put_line(‘Employee
Fetched:‘||lv_emp_name);END LOOP;
is‘||guru99_det%R0WCOUNT);CLOSE guru99_det;
END:
Output
Employee Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY
Code Explanation:
Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM emp'.
87
Code line 6: Setting the Basic loop statement to fetch all the records in the 'emp' table.
Code line 7: Fetches the guru99_det data and assign the value to lv_emp_name.
Code line 9: Using the cursor attribute '%NOTFOUND' to find whether all the record in the
cursor is fetched. If fetched then it will return 'TRUE' and control will exit from the loop, else
the control will keep on fetching the data from the cursor and print the data.
Code line 14: Using the cursor attribute '%ROWCOUNT' to find the total number of records
that gotaffected/fetched in the cursor.
Code line 15: After exiting from the loop the cursor is closed and the memory allocated is set free.
"FOR LOOP" statement can be used for working with cursors. We can give the cursor name instead
of range limit in the FOR loop statement so that the loop will work from the first record of the
cursor to the last record of the cursor. The cursor variable, opening of cursor, fetching and closing
of the cursor will bedone implicitly by the FOR loop.
Syntax:
DECLARE
BEGIN
FOR I IN
<cursor_name> LOOP
END LOOP;
END;
In the above syntax, the declaration part contains the declaration of the cursor.
The cursor is created for the 'SELECT' statement that is given in the cursor declaration.
In execution part, the declared cursor is setup in the FOR loop and the loop variable 'I' will
behave ascursor variable in this case.
88
Example 1: In this example, we will project all the employee name from emp table using a
cursor-FORloop.
DECLARE
BEGIN
LOOP
Dbms_output.put_line(‘Employee
Fetched:‘||lv_emp_name);END LOOP;
END;
Output
Employee
Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY
Code Explanation:
Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM emp'.
Code line 4: Constructing the 'FOR' loop for the cursor with the loop variable lv_emp_name.
Code line 5: Printing the employee name in each iteration of the loop.
Note: In Cursor-FOR loop, cursor attributes cannot be used since opening, fetching and closing
of the cursor is done implicitly by FOR loop.
RESULT:
Thus cursors in DBMS to retrieve data from a result set has been written, executed and the output was verified.
89
Ex.No:5 PROCEDURES AND
FUNCTIONS AIM:
An Oracle stored procedure is a program stored in an Oracle database. The following are the
advantages of using procedures.
Better performance: Oracle stored procedures load once into the shared pool and remain
there unless they become paged out. Subsequent executions of the Oracle stored procedure are far
faster than executions of external code.
Coupling of data with behaviour: DBAs can use naming conventions to couple relational tables
with the behaviors associated with a table by using Oracle stored procedures as "methods". If all
behaviors associated with the employee table are prefixed with the table name--employee.hire,
employee.give_raise, for example--the data dictionary can be queries to list all behaviors associated
witha table (select * from dba_objects where owner = 'EMPLOYEE'), and it's easy to identify and
reuse code via stored procedures.
Isolation of code: Since all SQL is moved out of the external programs and into the Oracle
stored procedures, the application programs become nothing more than calls to Oracle stored
procedures. As such, it becomes very simple to swap out one database and swap in another one.
SYNTAX:
CREATE [OR REPLACE] PROCEDURE
procedure_name [(parameter_name [IN | OUT | IN
OUT] type [, ...])]
{IS | AS}
BEGIN
procedure_body
EXCEPTION
Exception
handlingEND
procedure_name
IN - The parameter can be referenced by the procedure or function. The value of the parameter
cannot beoverwritten by the procedure or function.
OUT - The parameter cannot be referenced by the procedure or function, but the value of the
90
parameter canbe overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter canbe overwritten by the procedure or function.
Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.
Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so
that thePL/SQL Blocks terminates gracefully.
If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with
errors.
REFERRED TABLES:
Borrow(acc_no , rollno, date_issue);
1. Write a procedure to insert a record in borrower relation. Before inserting check whether the
book is available or not.
Procedure
CREATE OR REPLACE PROCEDURE PROC_BORROW(ACCNO NUMBER, ROLL VARCHAR,DOI
DATE)
IS
CNT NUMBER(5);
BEGIN
SELECT COUNT(*) INTO CNT FROM BORROW WHERE ACC_NO=ACCNO ;
IF(CNT=0)
THEN
INSERT INTO BORROW VALUES (ACCNO,ROLL,DOI); ELSE
END;
OUTPUT:
SQL> @
e:\proc.sql;
Procedure Created.
SQL> exec pro1(‘123’,’CS01’,’27-OCT-2013’);
Procedure successfully completed.
SQL> SELECT * FROM BORROW;
91
ACC_NO ROLLNO DOI
2. Write a procedure to insert a record in borrower relation with the above constraints and also
ensure that the member has not borrowed more than three books.
Procedure
CREATE OR REPLACE PROCEDURE PROC_BORROW(ACCNO NUMBER, ROLL VARCHAR,DOI
DATE)
IS
CNT NUMBER(5);
BEGIN
SELECT COUNT(*) INTO CNT FROM BORROW WHERE ACC_NO=ACCNO;
IF(CNT=0)
THEN
SELECT COUNT(*) INTO CNT1 FROM BORROW WHERE ROLLNO=ROLL;
IF(CNT1<4)
THEN
INSERT INTO BORROW VALUES (ACCNO,ROLL,DOI);END
IF;
ELSE
DBMS_OUTPUT.PUT_LINE(‘BOOK NOT AVAILABLE’);END
IF;
END;
OUTPUT:
SQL> @ e:\proc.sql;
Procedure Created.
92
FUNCTIONS
PL/SQL FUNCTION:
A PL/SQL function is same as a procedure except that it returns a value. A standalone function is
createdusing the CREATE FUNCTION statement.
SYNTAX
CREATE [OR REPLACE] FUNCTION function_name (parameter_name [IN | OUT | IN OUT] type [,
...])
RETURN return_datatype
{IS | AS}
BEGIN
< function_body
>
return_variable;
EXCEPTION
exception
sectionEND;
93
Return Type: The header section defines the return type of the function. The return datatype can be
any ofthe oracle datatype like varchar, number etc. The execution and exception section both
should return a value which is of the datatype defined in the header section.
IN - The parameter can be referenced by the procedure or function. The value of the parameter
cannot beoverwritten by the procedure or function.
OUT - The parameter cannot be referenced by the procedure or function, but the value of the
parameter canbe overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter
canbe overwritten by the procedure or function.
Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.
Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so
that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that
cannot be handled, the Block terminates abruptly with errors
The major difference between a procedure and a function is, a function must always return a
value, but aprocedure may or may not return a value.
RESULT:
Thus the program for Procedures and Functions has been written and executed successfully.
94
Ex.No:6 TRIGGERS
AIM:
To execute and verify triggers for the purpose of monitoring the database objects.
PROGRAM:
PL/SQL TRIGGERS:
Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggersare, in fact, 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).
SYNTAX:
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
95
>BEGIN
< Executable-statements
>EXCEPTION
< Exception-handling-
statements >END;
A typical trigger has 3 main components
1.Triggering SQL Statement: - This is the DML statement which causes the triggers to be invoked.
Thatis it tells when to call the trigger – before or after, on which DML statement of the table –
INSERT/ UPDATE/ DELETE and whether to call trigger when whole table is processed or only few
columns are processed. BEFORE and AFTER is used on tables and INSTEAD OF is used on views to
create triggers.
2.Trigger Restriction: - This is the part of trigger which tells how many times the trigger needs to be
executed. It informs, if the trigger has to be called for each row insert /update/delete, or only once
for the transaction.
3.Trigger Action: - This part will actually perform set of transaction as result of original DML statement.
SAMPLE EXERCISE
REFERRED TABLES:
Account (
accnt_no,cst_id,acnt_type,last_trans_date,balance )
Account_bckup(accnt_no,last_trans_date,balance)
Loan (ln_id,cst_id,ln_amount,ln_date);
1. Create a trigger for Account relation such that whenever a record is inserted in the Account
tablethe same record also gets inserted in the backup table.
CREATE OR REPLACE TRIGGER TRIG_ACNT_BCKUP AFTER INSERT ON ACCOUNTFOR
EACH ROW
DECLARE
BEGIN
INSERT INTO ACCOUNT_BCKUP VALUES (:NEW.ACCNT_NO, :NEW.LAST_TRANS_DATE,
:NEW.BALANCE);
END;
OUTPUT:
SQL>
96
@e:/plsql/accnt_trig.sql
Trigger Created.
2.Create a trigger for account relation such that whenever account record is inserted in account
relation with negative relation then that record should also be inserted in the loan relation with
positive balance.
CREATE OR REPLACE TRIGGER TRIG_LOAN AFTER INSERT ON ACCOUNTFOR
EACH ROW
DECLARE
BEGIN
IF(:NEW.BALANCE<0)
THEN
INSERT INTO LOAN VALUES (:NEW.ACCNT_NO, :NEW.CST_ID, -(:NEW.BALANCE),
SYSDATE);
END IF;
END;
OUTPUT:
SQL>
@e:/plsql/loan_trig.sql
Trigger Created.
SQL> INSERT INTO ACCOUNT VALUES (‘AC011’,’CST011’,’SVNG’,’27-DEC-2013’,-8000);
1 Row inserted.
SQL> SELECT * FROM LOAN;
LN_ID CST_ID LN_AMOUNT LN_DATE
97
RESULT:
Thus the Triggers for the purpose of monitoring the database objects has been written and executed
successfully.
98
Ex.No:7 EXCEPTION HANDLING
AIM:
PROGRAM:
END;
99
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer by using the command RAISE.
Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
definedexception must be declared and then raised explicitly, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is
−DECLARE
my-exception EXCEPTION;
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by aprogram. For example, the predefined exception NO_DATA_FOUND is raised when a
SELECT INTO statement returns no rows. The following table lists few of the important pre-defined
exceptions.
100
Exception Description
101
1. For the customer relation Customers(ID, Name, Age Address, Salary). Write a PL/SQL block to input
customerid and display address and salary. Use exception to display “ No such customer” when
data not found.
DECLARE
c_id customers.ID%type
:= &c_id;c_name
customers.Name%type;
c_addr customers.Address
%type;BEGIN
SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' ||
c_addr); EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such
customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
OUTPUT:
Enter the value of c_id:100
No such customer
2. For the customer relation Customers(ID, Name, Age Address, Salary). Write a PL/SQL block to
input customerid and display address and salary. Use exception to display “ No such customer”
when data not found.
DECLARE
c_id customers.id%type :=
&cc_id;c_name
customerS.Name%type; c_addr
customers.address%type;
-- user defined exception
102
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' ||
c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such
customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
OUTPUT
Enter the value of c_id:-50
ID must be greater than zero
RESULT:
Thus the Exception handling program has been written, executed and output was verified.
103
Ex. No: 8. DATABASE DESIGN USING ER MODELING, NORMALIZATION
AND IMPLEMENTATION FOR ANY APPLICATION
AIM:
To design Database using ER Modeling in DBMS.
PROGRAM:
NORMALIZATION
Normalization is the analysis of functional dependencies between attributes/data items of
user views. It reduces a complex user view to a set of small and stable subgroups of the fields and
relations. This process helps to design a logical data model known as conceptual data model.
There are different normal forms
1. First Normal Form(1NF)
2. Second Normal Form(2NF)
3. Third Normal Form(3NF)
FIRST NORMAL FORM (1NF)
1NF states that the domain of an attribute must include only atomic values and that value of
any attribute in a tuple must be a single value from the domain of that attribute. Hence 1NF
disallows multivalued attributes, composite attributes. It disallows “relations within relations”.
SECOND NORMAL FORM (2NF)
A relation is said to be in 2NF if it is already in 1NF and it has no partial dependency. 2NF is
basedon the concept of full functional dependency.
A functional dependency(FD) x y is fully functional dependency is (x-(A)) y does not
holddependency any more if A x.
A functional dependency x y is partial dependency if A can be removed which does not affect
thedependency ie (x-(A)) y holds.
A relation is in 2NF if it is in 1NF and every non-primary key attribute is fully and
functionallydependent on primary key.
A relation is in 1NF will be in the 2NF if one of the following conditions is satisfied:
1. The primary key consist of only one attribute.
2. No non-key attribute exist in relation ie all the attributes in the relation are components of
the primarykey.
Every non-key attribute is functionally dependent on full set of primary key attributes.
104
THIRD NORMAL FORM (3NF)
A relation is said to be in 3NF if it is already in 2NF and it has no transitive dependency.
A FD x y in a relation schema R is a transitive dependency if there is a set of attributes z that is
neither a candidate key nor a subset of any key of the relation and both x z and z y hold.
105
Database design for property database.
E-R DIAGRAMS
1. First Normal Form
Propnorm
propnorm
Propi cnam
106
3. Third Normal Form
propnorm
107
2. Insert values in the property table.
SQL> insert into prop values('34','india','ganthi nagar,Coimbatore,
india','500','500000','2');1 row created.
SQL> insert into prop values('45','united states','first street southeast, Washington,
Unitedstates','400','2550000','5');
1 row created.
SQL> insert into prop values('39','scotland','capelrig road, Glasgow, scotland','600','2500000','4');
1 row created.
Before Normalization
prop
Propid Cname Padd Area Price Tax_rate
1. Creating the prop11 tabale with propid, cname, area,price, tax_rate from
prop.SQL> create table prop11 as select , cname, area,price, tax_rate from
prop;
2. Creating the table prop12 with propid, sname,city,country
from propSQL> create table prop12 as select propid,padd from
emp;
3. Altering the table prop11 with primary key on prop.
SQL> alter table prop12 add constraint c1 foreign key(propid) references prop11(propid);
4. Altering the table prop12 with foreign key on propid with reference from
prop11. SQL> alter table prop12 add constraint c1 foreign key(propid)
references prop11(propid);
After
Normalization
Prop11
Propid Cname Area Price Tax_rate
Prop12
Propid sname City country
108
SECOND NORMAL FORM
Normalization to Second Normal Form
1. Create the table prop21 with propid, cname, area, price from the
table prop.SQL> create table prop21 as select propid,cname,area, price
from prop;
2. Create the table prop22 with cname, tax_rate from the
table prop.SQL> create table prop22 as select cname,tax_rate
from prop;
3. Alter table prop21 with a primary key constraint on propid.
SQL> alter table prop21 add constraint prop21 primary
key(propid);
109
3. Alter table prop31 with the constraint primary key on
propid. SQL> alter table prop31 add constraint prop31 primary
key(propid);
4. Alter table prop32 with the constraint primary key on
area. SQL> alter table prop32 add constraint prop32
primary key(area);
5. Alter table prop31 with the constraint foreign key on area with refernce from area
in prop32.SQL> alter table prop31 add constraint prop311 foreign key(area)
references prop32(area); After Normalization
Prop31 prop32
Propid Cname Area Area Price
RESULT:
Thus the Database Design Using ER Modeling, Normalization has been written, executed
successfully.
110
Ex . No: 9 GENERATION OF FORMS USING ORACLE FORM BUILDER
AIM:
To generate forms using Oracle form builder.
PROCEDURE:
Use Form Builder to simplify for the creation of data-entry screens, also known as Forms. Forms are
the applications that connect to a database, retrieve information requested by the user, present it in a
layout specified by Form designer, and allow the user to modify or add information. Form Builder
allows you to build forms quickly and easily.
Welcome window
You will get the ‘Welcome to the Form Builder’ window. If you don’t want to get this window anymore
uncheck the ‘Display at startup’ box. You can start your work with any of the following options:
The default is ‘Use the data Block Wizard.’ If you want to build a new form manually, click on
"Cancel”or check ‘Build a new form manually’ and click ‘OK.’
Connect to database
In the ‘Object Navigator’ window, highlight "Database Objects." Go to the Main menu and choose
In the ‘Connect’ window, login in as “scott” password “tiger,” then click “CONNECT.”
Notice that the box next to ‘Database Objects’ is not empty anymore and it has a ‘+’ sign in
it.That will indicate that this item is expandable and you are able to see its entire objects.
Click on the ‘+’ sign next to the ‘Database Objects’ to expand all database schemas.
111
Create a Module
In the ‘Object Navigator’ window, highlight module1. This is a default name. Go to the Main menu
and choose “File,” select “Save as” to store the new object in the “iself” folder and save it as
customer data entry. "c:_de." In this example the ‘DE’ abbreviation stands for Data Entry.
In the ‘Object Navigator’ window, highlight "Data Blocks,” and click on the "create” icon. The
‘Create’ icon is in the vertical tool bar in the ‘Object Navigator’ window. It is a green ‘+’ sign. If you
drag your cursor on the icon a tooltip will show ‘Create.’
In the ‘New Data Block’ window, choose the default option “Data Block Wizard” and click "OK."
In the ‘Welcome Data Block Wizard’ window click on the “NEXT” icon.
Select the type of data block you would like to create by clicking on a radio button. Select the default
option ‘Table or View’ and then click “NEXT” again.
Selecting Tables
Click on “browse.” In the ‘Tables’ window, highlight the "cust11” table; then click "OK."
To choose all columns, click on the two arrow signs in the ‘Data Block Wizard’ window. To choose
selected columns, click on the one arrow sign. And then select all columns, and click “next.”
Layout Wizard
End of the Data Block Wizard and beginning of the Layout Wizard In the ‘Congratulations’ screen,
use the default checkmark radio button (Create the data block, then call the Layout Wizard), and
click "Finish." You can also use the Data Block Wizard to modify your existing data block. Simply
select the data block in the Object Navigator and click the Data Block Wizard toolbar button, or
choose ‘Data Block wizard’ from the ‘Tools’ menu.
Welcome screen
112
Selecting canvas
In the ‘Layout Wizard’ window, select the "new canvas" option. Canvas is a place that you will have
your objects such as columns, titles, pictures, etc. If you have already had your canvas, select the
canvas and then click on the next. The following are different types of canvases: Content, Stacked,
Vertical Toolbar, Horizontal Toolbar, and Tab.
Think of the ‘Content’ canvas as one flat place to have all your objects. In the stacked canvas, you
can have multiple layers of objects and it is the same as the tab canvas. You use the vertical or
horizontal toolbar canvases for your push buttons. Check the different types of canvases by clicking
on the ‘down arrow’ box next to the ‘Type’ field. Select "content," then click “Next.”
In the ‘Layout Wizard’ window, select all the columns. These are the columns that you want to be
displayed on the canvas. Then click “Next.”
Change size or prompt if needed. In this window, you can enter a prompt, width, and height for
each itemon the canvas. You can change the measurement units. As a default the default units for
item width and height are points. You can change it to inch or centimeter. When you change size,
click “Next.”
Select a layout style for your frame by clicking a radio button. Select "Form," if you want one record
at a time to be displayed. Select “Tabular,” if you want more than one record at a time to be
displayed. Select "Forms," and then click “next.”
Record layout
Type the "Frame Title" and click "next." Checkmark the ‘Display Scrollbar’ box when you use
multiple records or the ‘Tabular’ option.
Congratulation Screen
Make some window adjustments and then run the form. To run the form, click on the ‘Run’
The object module should be compiled successfully before executing the Form.
113
Execute Query
Click on the "Execute Query" icon below the main menu. If you drag the cursor on the toolbar in the
‘Forms Runtime’ window, a tooltip will be displayed and you see ‘Execute Query. So to know all
your option, drag your cursor to view all the icon descriptions.
Next Record
Previous Record
Click on the "Previous Record" icon to navigate to the previous record.This is an easy way to
Enter Query
Insert Record
Click "Insert Record" to add new customer. All items on the forms will be blanked. You can either
Duplicate Record
To duplicate the previous record, go to the main menu and select the ‘Record’ sub-menu. A drop
down menu will be displayed. Select the ‘Duplicate’ option in the sub-menu.
Apply the changes. Remember in this stage, your record was inserted but not committed yet.
Click "next record" and "previous record" to navigate through the records and the one was added.
Save transactions
Delete Record
114
Lock a Record
Exit the FORM Runtime. If you have not committed any transaction, you will be prompted to
savechanges. Click “YES” to save changes.
Sample Exercise:
RABAD
115
Selecting the type of form to create
116
Selecting the canvas on which data block can be displayed
RESULT:
Thus the Generation of Forms Using Oracle Form Builder has been designed and executed successfully.
117
Ex. No: 10 DATABASE DESIGN AND IMPLEMENTATION
AIM:
To design database and Implementation using Form Builder.
PROGRAM:
Sample Exercise:
SQL> desc
trans;Name Null? Type
ACCNO NUMBER(10)
AMOUNT NUMBER(10)
TRDATE DATE
commit;
clear_form
;
118
commit;
debit
declare
wdamount number;
begin
select balance into wdamount from cust where
accno=:trans.accno;if wdamount>=:amount then
update cust set balance = balance-:trans.amount
where cust.accno=:trans.accn
o;execute_query;
commit;
message('money withdraw succesfully');
else
message('you have low balance');
end if;
en
d
;
119
After write all codings Run the
Form:The Form will like this,
120
Then press the Create Button.
MOVE TO SQL PLUS AND ENTER THE QUERY:
A ERODE 101 0
121
MOVE TO SQL PLUS AND ENTER THE QUERY:
122
ACCNO AMOUNT TRDATE
RESULT:
Thus the database has been designed using Oracle Form Builder and executed successfully.
123