0% found this document useful (0 votes)
12 views46 pages

DBMS manualNAAC

Uploaded by

afddfbyof
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views46 pages

DBMS manualNAAC

Uploaded by

afddfbyof
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

M.G.

M’s College Of Engineering, Nanded Database Management System


Department of Computer Science & Engineering.

PRACTICAL No. 1
Study of Codd’s rules.
________________________________________________________
Rule 1: Information Rule
The data stored in a database, may it be user data or metadata, must be a value of some table cell.
Everything in a database must be stored in a table format.

Rule 2: Guaranteed Access Rule


Every single data element (value) is guaranteed to be accessible logically with a combination of
table-name, primary-key (row value), and attribute-name (column value). No other means, such
as pointers, can be used to access data.

Rule 3: Systematic Treatment of NULL Values


The NULL values in a database must be given a systematic and uniform treatment. This is a very
important rule because a NULL can be interpreted as one the following − data is missing, data is
not known, or data is not applicable.

Rule 4: Active Online Catalog


The structure description of the entire database must be stored in an online catalog, known as
data dictionary, which can be accessed by authorized users. Users can use the same query
language to access the catalog which they use to access the database itself.

Rule 5: Comprehensive Data Sub-Language Rule


A database can only be accessed using a language having linear syntax that supports data
definition, data manipulation, and transaction management operations. This language can be used
directly or by means of some application. If the database allows access to data without any help
of this language, then it is considered as a violation.

Rule 6: View Updating Rule


All the views of a database, which can theoretically be updated, must also be updatable by the
system.

Rule 7: High-Level Insert, Update, and Delete Rule


A database must support high-level insertion, updation, and deletion. This must not be limited to
a single row, that is, it must also support union, intersection and minus operations to yield sets of
data records.

Rule 8: Physical Data Independence

1
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

The data stored in a database must be independent of the applications that access the database.
Any change in the physical structure of a database must not have any impact on how the data is
being accessed by external applications.

Rule 9: Logical Data Independence


The logical data in a database must be independent of its user’s view (application). Any change
in logical data must not affect the applications using it. For example, if two tables are merged or
one is split into two different tables, there should be no impact or change on the user application.
This is one of the most difficult rule to apply.

Rule 10: Integrity Independence


A database must be independent of the application that uses it. All its integrity constraints can be
independently modified without the need of any change in the application. This rule makes a
database independent of the front-end application and its interface.

Rule 11: Distribution Independence


The end-user must not be able to see that the data is distributed over various locations. Users
should always get the impression that the data is located at one site only. This rule has been
regarded as the foundation of distributed database systems.

Rule 12: Non-Subversion Rule


If a system has an interface that provides access to low-level records, then the interface must not
be able to subvert the system and bypass security and integrity constraints.

2
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 2
Study and Design of E-R Diagram.
________________________________________________________

Entity-Relationship (E-R) model concepts


– entities
– relationships
– cardinality constraints
– entity type hierarchies
– weak entities

Entity-Relationship model is used in the conceptual design of a database (☞ conceptual level,


conceptual schema)

• Design is independent of all physical considerations (DBMS, OS, . . . ).

Questions that are addressed during conceptual design:

– What are the entities and relationships of interest (miniworld)?


– What information about entities and relationships among entities needs to be stored in the
database?
– What are the constraints (or business rules) that (must) hold for the entities and relationships?
• A database schema in the ER model can be represented pictorially
(Entity-Relationship diagram)

Entity: real-world object or thing with an independent existence and which is distinguishable
from other objects. Examples are a person, car, customer, product, gene, book etc.

• Attributes: an entity is represented by a set of attributes (its descriptive properties), e.g., name,
age, salary, price etc. Attribute values that describe each entity become a major part of the data
eventually stored in a database.

• With each attribute a domain is associated, i.e., a set of permitted values for an attribute.
Possible domains are integer, string, date, etc.

• Entity Type: Collection of entities that all have the same attributes, e.g., persons, cars,
customers etc.

3
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

• Entity Set: Collection of entities of a particular entity type at any point in time; entity set is
typically referred to using the same name as entity type.

Key attributes of an Entity Type

• Entities of an entity type need to be distinguishable.


• A superkey of an entity type is a set of one or more attributes whose values uniquely determine
each entity in an entity set.
• A candidate key of an entity type is a minimal (in terms of number of attributes) superkey.
• For an entity type, several candidate keys may exist. During conceptual design, one of the
candidate keys is selected to be the primary key of the entity type.

4
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

5
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 3
Study and implement the DDL commands.
________________________________________________________

Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:

CREATE - to create objects in the database

CREATE TABLE table_name(

column1 datatype,

column2 datatype,

column3 datatype,

.....

columnN datatype,

PRIMARY KEY( one or more columns )

);

CREATE TABLE Student

(Reg_no varchar2(10),

Name char(30),

DOB date,

Address varchar2(50));

6
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

ALTER - alters the structure of the database

ALTER TABLE table_name ADD column_name datatype;

ALTER TABLE table_name DROP COLUMN column_name;

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

ALTER TABLE table_name RENAME COLUMN old_column_name to new_column_name;

DROP - delete objects from the database

DROP TABLE table_name;

DROP TABLE CUSTOMERS;

TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed

TRUNCATE TABLE table_name;

TRUNCATE TABLE CUSTOMERS;

RENAME - rename an object

RENAME old_table_name to new_table_name;

7
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 4
Study and Implement the DML commands.
________________________________________________________

Data Manipulation Language (DML) statements or commands are used for managing data within
tables. Some commands of DML are:

Some commands of DML are:

SELECT – retrieves data from a database table.

Syntax: SELECT <attribute>, ….., <attribute n> FROM <table name>;

Example: SELECT StudID, Name FROM STUDENT;

INSERT – insert data into a table

Syntax: INSERT INTO <table name> VALUES (<value 1>, ... <value n>);

Example: INSERT INTO STUDENT VALUES (1001,‘Juned’);

UPDATE – updates existing data within a table

Syntax: UPDATE <table name> SET <attribute> = <expression> WHERE <condition>;

Example: UPDATE STUDENT SET Name = ‘Nikita’ WHERE StudID=1001;

DELETE – deletes all records from a table, the space for the records remain

Syntax: DELETE FROM <table name> WHERE <condition>;

Example: DELETE FROM STUDENT WHERE StudID=1001;

8
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 5
Applying integrity constraints on the database
________________________________________________________

SQL Create Constraints

Constraints can be specified when the table is created with the CREATE TABLE statement, or
after the table is created with the ALTER TABLE statement.

Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the data
action, the action is aborted.

Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Use to create and retrieve data from the database very quickly

create table second (id int ,name char(10) not null,pass int unique,primary key(id));
create table second (id int ,name char(10),pass int ,primary key(id),unique(name));

create table third (id int, roll int,foreign key (id) reference second(id));

9
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 6
Implementation of different clauses.

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 SQL statement.

The AND Operator


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 −

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;

10
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

The OR Operator
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 −

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;

The SQL LIKE clause is used to compare a value to similar values using wildcard
operators. There are two wildcards used in conjunction with the LIKE operator.

 The percent sign (%)


 The underscore (_)
The percent sign represents zero, one or multiple characters. The underscore
represents a single number or character. These symbols can be used in
combinations.

Syntax
The basic syntax of % and _ is as follows −

SELECT FROM table_name


WHERE column LIKE 'XXXX%'

or

11
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

SELECT FROM table_name


WHERE column LIKE '%XXXX%'

or

SELECT FROM table_name


WHERE column LIKE 'XXXX_'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX_'

Sr.No. Statement & Description

WHERE SALARY LIKE '200%'


1
Finds any values that start with 200.

WHERE SALARY LIKE '%200%'


2
Finds any values that have 200 in any position.

WHERE SALARY LIKE '_00%'


3
Finds any values that have 00 in the second and third positions.

12
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

WHERE SALARY LIKE '2_%_%'


4
Finds any values that start with 2 and are at least 3 characters in length.

WHERE SALARY LIKE '%2'


5
Finds any values that end with 2.

WHERE SALARY LIKE '_2%3'


6
Finds any values that have a 2 in the second position and end with a 3.

WHERE SALARY LIKE '2___3'


7
Finds any values in a five-digit number that start with 2 and end with 3.

SQL> SELECT * FROM CUSTOMERS


WHERE SALARY LIKE '200%';

The SQL TOP clause is used to fetch a TOP N number or X percent records from
a table.

Note − All the databases do not support the TOP clause. For example MySQL
supports the LIMIT clause to fetch limited number of records while Oracle uses
the ROWNUM command to fetch a limited number of records.

Syntax
The basic syntax of the TOP clause with a SELECT statement would be as
follows.
13
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE [condition]

SQL> SELECT TOP 3* FROM CUSTOMERS;

SQL> SELECT * FROM CUSTOMERS


LIMIT 3;

SQL> SELECT * FROM CUSTOMERS


WHERE ROWNUM <=3;

The SQL ORDER BY clause is used to sort the data in ascending or descending
order, based on one or more 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]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

SQL> SELECT * FROM CUSTOMERS


14
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

ORDER BY NAME, SALARY;


SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

The SQL GROUP BY clause is used in collaboration with the SELECT statement
to arrange identical data into groups. This GROUP BY clause follows the
WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax
The basic syntax of a GROUP BY clause is shown in the following code block.
The GROUP BY clause must follow the conditions in the WHERE clause and
must precede the ORDER BY clause if one is used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME

The SQL DISTINCT keyword is used in conjunction with the SELECT statement
to eliminate all the duplicate 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

15
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

The basic syntax of DISTINCT keyword to eliminate the duplicate records is as


follows −

SELECT DISTINCT column1, column2,.....columnN


FROM table_name
WHERE [condition]

SQL> SELECT SALARY FROM CUSTOMERS


ORDER BY SALARY;

16
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 7
View Data: Write SQL, to view table data. Accept table
attributes for ordering dynamically.
________________________________________________________
A view is nothing more than a SQL statement that is stored in the database with
an associated name. A view is actually a composition of a table in the form of a
predefined SQL query.

A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depends on the written SQL query to
create a view.

Views, which are a type of virtual tables allow users to do the following −

 Structure data in a way that users or classes of users find natural or intuitive.

 Restrict access to the data in such a way that a user can see and (sometimes)
modify exactly what they need and no more.

 Summarize data from various tables which can be used to generate reports.

Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or another view.

To create a view, a user must have the appropriate system privilege according to
the specific implementation.

17
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

The basic CREATE VIEW syntax is as follows −

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE [condition];

SQL > CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS;

SQL > SELECT * FROM CUSTOMERS_VIEW;

The WITH CHECK OPTION


The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose
of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs
satisfy the condition(s) in the view definition.

If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.

The following code block has an example of creating same view


CUSTOMERS_VIEW with the WITH CHECK OPTION.

CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;

18
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

The WITH CHECK OPTION in this case should deny the entry of any NULL
values in the view's AGE column, because the view is defined by data that does
not have a NULL value in the AGE column.

Updating a View
A view can be updated under certain conditions which are given below −

 The SELECT clause may not contain the keyword DISTINCT.

 The SELECT clause may not contain summary functions.

 The SELECT clause may not contain set functions.

 The SELECT clause may not contain set operators.

 The SELECT clause may not contain an ORDER BY clause.

 The FROM clause may not contain multiple tables.

 The WHERE clause may not contain subqueries.

 The query may not contain GROUP BY or HAVING.

 Calculated columns may not be updated.

 All NOT NULL columns from the base table must be included in the view
in order for the INSERT query to function.

So, if a view satisfies all the above-mentioned rules then you can update that
view. The following code block has an example to update the age of Ramesh.

SQL > UPDATE CUSTOMERS_VIEW


SET AGE =35
WHERE name ='Ramesh';

19
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Inserting Rows into a View


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the INSERT command.

Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the
NOT NULL columns in this view, otherwise you can insert rows in a view in a similar way as
you insert them in a table.

Deleting Rows into a View


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands apply to the DELETE command.

Following is an example to delete a record having AGE = 22.

SQL > DELETE FROM CUSTOMERS_VIEW

WHERE age =22;

Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed.
The syntax is very simple and is given below −

DROP VIEW view_name;

Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table.

DROP VIEW CUSTOMERS_VIEW;

PRACTICAL No. 8
Implementation of aggregation and set operations in SQL.

20
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

________________________________________________________
SQL has numerous predefined aggregate functions that can be used to write queries to produce
exactly this kind of information.The GROUP BY clause specifies how to group rows from a
data table when aggregating information, while the HAVING clause filters out rows that do not
belong in specified groups.

Aggregate functions perform a variety of actions such as counting all the rows in a table,
averaging a column's data, and summing numeric data. Aggregates can also search a table to
find the highest "MAX" or lowest "MIN" values in a column. As with other types of queries,
you can restrict, or filter out the rows these functions act on with the WHERE clause. For
example, if a manager needs to know how many employees work in an organization, the
aggregate function named COUNT(*) can be used to produce this information.The COUNT(*)
function shown in the below SELECT statement counts all rows in a table.

SELECT COUNT(*)

FROM employees;

COUNT(*)

----------

24

Some of the commonly used aggregate functions are as below -

SUM([ALL | DISTINCT] expression )

AVG([ALL | DISTINCT] expression )

COUNT([ALL | DISTINCT] expression )

COUNT(*)

21
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

MAX(expression)

MIN(expression)

The ALL and DISTINCT keywords are optional, and perform as they do with the SELECT
clauses that you have learned to write.The ALL keyword is the default where the option is
allowed.The expression listed in the syntax can be a constant,a function, or any combination of
column names, constants, and functions connected by arithmetic operators.However, aggregate
functions are most often used with a column name. Except the COUNT function, all the
aggregate functions do not consider NULL values.

There are two rules that you must understand and follow when using aggregates:

 Aggregate functions can be used in both the SELECT and HAVING clauses (the
HAVING clause is covered later in this chapter).

 Aggregate functions cannot be used in a WHERE clause. Its violation will produce
the Oracle ORA-00934 group function is not allowed here error message.

Illustrations
The below SELECT query counts the number of employees in the organization.

SELECT COUNT(*)Count

FROM employees;
COUNT

-----

24

The below SELECT query returns the average of the salaries of employees in the organization.

SELECT AVG(Salary) average_sal

FROM employees;

22
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

AVERAGE_SAL

-----------

15694

The below SELECT query returns the sum of the salaries of employees in the organization.

SELECT SUM(Salary) total_sal


FROM employees;

TOTAL_SAL

---------

87472

The below SELECT query returns the oldest and latest hired dates of employees in the
organization.

SELECT MIN (hire_date) oldest, MAX (hire_date) latest


FROM employees;

OLDEST LATEST

--------- -----------

16-JAN-83 01-JUL-2012

PRACTICAL No. 9

23
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Design SQL queries using all types of


Joins______________________________________________________
__
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName

1 Alfreds Futterkiste Maria Anders

2 Ana Trujillo Emparedados y helados Ana Trujillo

24
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

3 Antonio Moreno Taquería Antonio Moreno

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

and it will produce something like this:

OrderID CustomerName

10308 Ana Trujillo Emparedados y helados

10365 Antonio Moreno Taquería

10383 Around the Horn

10355 Around the Horn

10278 Berglunds snabbköp

25
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the matched records
from the right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the matched
records from the left table
 FULL (OUTER) JOIN: Return all records when there is a match in either left or right
table

26
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

INNER Join or EQUI Join

This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.

Inner Join Syntax is,

SELECT column-name-list

from table-name1

INNER JOIN

table-name2

WHERE table-name1.column-name = table-name2.column-name;

Natural JOIN

Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.

Natural Join Syntax is,

SELECT *

from table-name1

NATURAL JOIN

table-name2;

Left Outer Join

The left outer join returns a result table with the matched data of two tables then remaining rows
of the left table and null for the right table's column.

Left Outer Join syntax is,

27
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;

Right Outer Join

The right outer join returns a result table with the matched data of two tables then remaining
rows of the right table and null for the left table's columns.

Right Outer Join Syntax is,

select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Right outer Join Syntax for Oracle is,

select column-name-list
from table-name1,
table-name2
on table-name1.column-name(+) = table-name2.column-name;

28
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 10
Design SQL queries using all types Sub-Query
________________________________________________________
A subquery is best defined as a query within a query. Subqueries enable you to write queries
that select data rows for criteria that are actually developed while the query is executing at run
time. More formally, it is the use of a SELECT statement inside one of the clauses of another
SELECT statement. In fact, a subquery can be contained inside another subquery, which is
inside another subquery, and so forth. A subquery can also be nested inside INSERT, UPDATE,
and DELETE statements. Subqueries must be enclosed within parentheses.

A subquery can be used any place where an expression is allowed providing it returns a single
value. This means that a subquery that returns a single value can also be listed as an object in a
FROM clause listing. This is termed an inline view because when a subquery is used as part of a
FROM clause, it is treated like a virtual table or view. Subquery can be placed either in FROM
clause, WHERE clause or HAVING clause of the main query.

Oracle allows a maximum nesting of 255 subquery levels in a WHERE clause. There is no limit
for nesting subqueries expressed in a FROM clause.In practice, the limit of 255 levels is not
really a limit at all because it is rare to encounter subqueries nested beyond three or four levels.

A subquery SELECT statement is very similar to the SELECT statement used to begin a regular
or outer query.The complete syntax of a subquery is:

( SELECT [DISTINCT] subquery_select_parameter


FROM {table_name | view_name}
{table_name | view_name}...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ]...]
[HAVING search_conditions])

29
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. They mark the usage of
single row comparison operators, when used in WHERE conditions.

Multiple row sub query: Sub query returning multiple row output. They make use of multiple
row comparison operators like IN, ANY, ALL. There can be sub queries returning multiple
columns also.

Correlated Sub Query: Correlated subqueries depend on data provided by the outer query.This
type of subquery also includes subqueries that use the EXISTS operator to test the existence of
data rows satisfying specified criteria.

Single Row Sub Query


A single-row subquery is used when the outer query's results are based on a single, unknown
value. Although this query type is formally called "single-row," the name implies that the query
returns multiple columns-but only one row of results. However, a single-row subquery can
return only one row of results consisting of only one column to the outer query.

In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the
company. It in turn uses this value to compare salary of all the employees and displays only
those, whose salary is equal to minimum salary.

SELECT first_name, salary, department_id


FROM employees
WHERE salary =(SELECT MIN (salary)
FROM employees);

A HAVING clause is used when the group results of a query need to be restricted based on
some condition. If a subquery's result must be compared with a group function, you must nest
the inner query in the outer query's HAVING clause.

SELECT department_id, MIN (salary)


FROM employees
GROUP BY department_id
HAVING MIN (salary)<(SELECT AVG (salary)
FROM employees)

30
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Multiple Row Sub Query


Multiple-row subqueries are nested queries that can return more than one row of results to the
parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING
clauses. Since it returns multiple rows,it must be handled by set comparison operators (IN,
ALL, ANY).While IN operator holds the same meaning as discussed in earlier chapter, ANY
operator compares a specified value to each value returned by the sub query while ALL
compares a value to every value returned by a sub query.

Below query shows the error when single row sub query returns multiple rows.

SELECT first_name, department_id


FROM employees
WHERE department_id =(SELECT department_id
FROM employees
WHERE LOCATION_ID =100)
department_id =(select
*
ERROR at line 4:
ORA-01427: single-row subquery returns more than one row

Usage of Multiple Row operators


 [> ALL] More than the highest value returned by the subquery

 [< ALL] Less than the lowest value returned by the subquery

 [< ANY] Less than the highest value returned by the subquery

 [> ANY] More than the lowest value returned by the subquery

 [= ANY] Equal to any value returned by the subquery (same as IN)

31
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Above SQL can be rewritten using IN operator like below.

SELECT first_name, department_id


FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE LOCATION_ID =100)

Note in the above query, IN matches department ids returned from the sub query,compares it
with that in the main query and returns employee's name who satisfy the condition.

A join would be better solution for above query, but for purpose of illustration, sub query has
been used in it.

Correlated Sub Query


As opposed to a regular subquery, where the outer query depends on values provided by the
inner query,a correlated subquery is one where the inner query depends on values provided by
the outer query. This means that in a correlated subquery,the inner query is executed repeatedly,
once for each row that might be selected by the outer query.

Correlated subqueries can produce result tables that answer complex management questions.

Consider the below SELECT query. Unlike the subqueries previously considered, the subquery
in this SELECT statement cannot be resolved independently of the main query. Notice that the
outer query specifies that rows are selected from the employee table with an alias name of e1.
The inner query compares the employee department number column (DepartmentNumber) of
the employee table with alias e2 to the same column for the alias table name e1.

SELECT EMPLOYEE_ID, salary, department_id


FROM employees E
WHERE salary >(SELECT AVG(salary)
FROM EMP T
WHERE E.department_id = T.department_id)

32
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

Multiple Column Sub Query


A multiple-column subquery returns more than one column to the outer query and can be listed
in the outer query's FROM, WHERE, or HAVING clause. For example, the below query shows
the employee's historical details for the ones whose current salary is in range of 1000 and 2000
and working in department 10 or 20.

SELECT first_name, job_id, salary


FROM emp_history
WHERE (salary, department_id)in(SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000and2000
AND department_id BETWEEN 10and20)
ORDER BY first_name;

When a multiple-column subquery is used in the outer query's FROM clause, it creates a
temporary table that can be referenced by other clauses of the outer query. This temporary table
is more formally called an inline view. The subquery's results are treated like any other table in
the FROM clause. If the temporary table contains grouped data, the grouped subsets are treated
as separate rows of data in a table. Consider the FROM clause in the below query. The inline
view formed by the subquery is the data source for the main query.

SELECT *
FROM (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000and2000);

33
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 11
Write SQL queries using Single Row functions.
________________________________________________________

Single row functions


Single row functions can be character functions, numeric functions, date functions, and
conversion functions. Note that these functions are used to manipulate data items. These
functions require one or more input arguments and operate on each row, thereby returning one
output value for each row. Argument can be a column, literal or an expression. Single row
functions can be used in SELECT statement, WHERE and ORDER BY clause. Single row
functions can be -

 General functions - Usually contains NULL handling functions. The functions under
the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE.

 Case Conversion functions - Accepts character input and returns a character value.
Functions under the category are UPPER, LOWER and INITCAP.

o UPPER function converts a string to upper case.

o LOWER function converts a string to lower case.

o INITCAP function converts only the initial alphabets of a string to upper case.

 Character functions - Accepts character input and returns number or character


value. Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR,
LPAD, RPAD, TRIM and REPLACE.

o CONCAT function concatenates two string values.

o LENGTH function returns the length of the input string.

34
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

o SUBSTR function returns a portion of a string from a given start point to an


end point.

o INSTR function returns numeric position of a character or a string in a given


string.

o LPAD and RPAD functions pad the given string upto a specific length with a
given character.

o TRIM function trims the string input from the start or end.

o REPLACE function replaces characters from the input string with a given
character.

 Date functions - Date arithmetic operations return date or numeric values. Functions
under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY,
LAST_DAY, ROUND and TRUNC.

o MONTHS_BETWEEN function returns the count of months between the two


dates.

o ADD_MONTHS function add 'n' number of months to an input date.

o NEXT_DAY function returns the next day of the date specified.

o LAST_DAY function returns last day of the month of the input date.

o ROUND and TRUNC functions are used to round and truncates the date
value.

 Number functions - Accepts numeric input and returns numeric values. Functions
under the category are ROUND, TRUNC, and MOD.

o ROUND and TRUNC functions are used to round and truncate the number
value.

35
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

o MOD is used to return the remainder of the division operation between two
numbers.

Illustrations
General functions
The SELECT query below demonstrates the use of NVL function.

SELECT first_name, last_name, salary, NVL (commission_pct,0)

FROM employees

WHERE rownum <5;

FIRST_NAME LAST_NAME SALARY NVL(COMMISSION_PCT,0)

----------------------------------------------------------------------------

StevenKing240000

NeenaKochhar170000

LexDeHaan170000

AlexanderHunold90000

Case Conversion functions


The SELECT query below demonstrates the use of case conversion functions.

SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)


FROM employees

WHERE rownum <5;

UPPER(FIRST_NAME) INITCAP(LAST_NAME) LOWER(JOB_


-------------------------------------------------------

STEVEN King ad_pres

NEENA Kochhar ad_vp

LEX DeHaan ad_vp

36
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

ALEXANDER Hunold it_prog

Character functions
The SELECT query below demonstrates the use of CONCAT function to concatenate two string
values.

SELECT CONCAT (first_name, last_name)

FROM employees

WHERE rownum <5;

CONCAT(FIRST_NAME,LAST_NAME)

--------------------------------

EllenAbel

SundarAnde

MozheAtkinson

DavidAustin

The SELECT query below demonstrates the use of SUBSTR and INSTR functions. SUBSTR
function returns the portion of input string from 1st position to 5th position. INSTR function
returns the numeric position of character 'a' in the first name.

SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a')


FROM employees

WHERE rownum <5;

SUBST INSTR(FIRST_NAME,'A')

--------------------------

Ellen0
Sunda5

Mozhe0

37
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

David2

The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print the
employee and job information.

SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')


FROM employees

WHERE rownum <5;

RPAD(FIRST_NAME,10,'_')||

-------------------------

Steven____________AD_PRES

Neena_______________AD_VP

Lex_________________AD_VP

Alexander_________IT_PROG

Number functions
The SELECT query below demonstrates the use of ROUND and TRUNC functions.

SELECT ROUND (1372.472,1)

FROM dual;

ROUND(1372.472,1)
-----------------

1372.5

SELECT TRUNC (72183,-2)


FROM dual;

TRUNC(72183,-2)

38
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

---------------

72100

Date arithmetic operations


The SELECT query below shows a date arithmetic function where difference of employee hire
date and sysdate is done.

SELECT employee_id,(sysdate - hire_date)Employment_days

FROM employees

WHERE rownum <5;

EMPLOYEE_ID EMPLOYMENT_DAYS

--------------------------

1003698.61877

1012871.61877

1024583.61877

1032767.61877

Date functions
The SELECT query below demonstrates the use of MONTHS_BETWEEN, ADD_MONTHS,
NEXT_DAY and LAST_DAY functions.

SELECT employee_id, MONTHS_BETWEEN (sysdate, hire_date)Employment_months

FROM employees

WHERE rownum <5;

EMPLOYEE_ID EMPLOYMENT_MONTHS

----------------------------

100121.504216

39
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

10194.3751837

102150.633248

10390.9558289

SELECT ADD_MONTHS (sysdate,5), NEXT_DAY (sysdate), LAST_DAY (sysdate)

FROM dual;

ADD_MONTH NEXT_DAY( LAST_DAY(

---------------------------

01-JAN-1405-AUG-1331-AUG-13

40
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

PRACTICAL No. 12
Write program to implement Embedded SQL.
________________________________________________________
Aim: Write program to implement Embedded SQL

This experiment provides an example of how to create a simple JDBC application. This will
show you how to open a database connection, execute a SQL query, and display the results.

Creating JDBC Application

Java Database Connectivity (JDBC) is a standard Application Programming Interface (API) that
is used to access databases, irrespective of the application driver and database product. In other
words, JDBC presents a uniform interface to databases, however, if you change the database
management system and your applications, you only need to change their driver. JDBC provides
cross-DBMS connectivity to a wide range of SQL databases, and other tabular data sources, such
as spreadsheets or flat files.

There are plenty of drivers now for JDBC that support popular databases. In case you do not find
a driver for the database management system you are using you may use a JDBC driver from
Sun Microsystems, that is compatible with ODBC, therefore enabling you to connect to any
ODBC (Open Database Connectivity) compliant database. JDBC drivers are available for most
of the major database management system — such as for Oracle, DB2, Access, Informix,
Sybase etc. — as well as for any data source that uses Microsoft's ODBC driver.

This programming interface allows Java programmers to request a connection with a database,
then sends query statements using SQL and receive the results for processing. JDBC handles the
actual connection, sending queries and data to and from the database. Programmers using JDBC
typically create their own SQL queries, which requires more work than using visual-oriented
tools for building the queries. You need to write the SQL statements manually, and you have to
make sure they're well formed, valid and correct. Since the queries are executed on the server
side, therefore, any syntactical error is send to the database and you will get an error back.
41
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

JDBC also allows programmers to update multiple fields with a single command, or even access
multiple database servers with a single transaction. In addition, it allows programmers
reusedatabase connections, known as connection pooling, so a new connection doesn't need to
be made to a database for each new JDBC command.

Since Java runs on many different hardware platforms and operating systems, developers can use
JDBC to write applications that access data across incompatible database management systems
running on different platforms. This feature is a great asset, as the whole software is not to be
redone.

The use of an application server, a software that sits between the client and the database server
accepting and directing the data requests, have made the life easier for programmer. Application
servers have JDBC support built into them, reducing the amount of code the programmer needs
to write.

The use of application server increases productivity and may be a dominant means of building
new applications, thus, reducing the requirements of JDBC drivers.

The advantages of using JDBC

The basic three advantages of JDBC may be:

 When there's a need to disseminate information internally in a large company where


departments have standardized on different platforms.
 If a corporation has undergone a merger and finds itself with different operating systems
and databases.
 For e-commerce applications that run over the Internet, where the company has no
control over the software its customers use. The customers only need the appropriate Java
technology, which can be downloaded on the fly to their computers.

There are following six steps involved in building a JDBC application

 Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.

42
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

 Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
 Open a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
 Execute a query: Requires using an object of type Statement for building and submitting
an SQL statement to the database.
 Extract data from result set: Requires that you use the appropriate ResultSet.getXXX()
method to retrieve the data from the result set.
 Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.

The following are steps should be written in programs

We begin by importing the sql package this is the package that has built in methods to
interact with a database.

 The main() method throws an exception of SQL type which is used to catch any
errors during execution of SQL commands.
 Class.forName() this is the class which tells which JDBC driver to use currently we
use the driver given to us by JAVA i.e. Sun’s own JDBC, ODBC bridge driver.
 Next we see three new type of variables:
 Connection: As the name suggests this will establish a connection with the database.
The DriverManager class’ getConnection() method opens a new connection with the
specified url, which may a web address or a DSN name as we have used. We also
have to specify User name, Password in this method.
 Statement: This is synonymous with a SQL statement. The executeQuery() method of
this class executes a SELECT query.execueUpdate() method executes an update
query like INSERT.
 ResultSet: As we can clearly see tis holds the result of a Query and we can move
through it to read data in it.

43
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

A Simple Program with connectivity:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class Form extends JFrame implements ActionListener{
JButton SUBMIT;
JPanel panel;
JLabel label1,label2;
final JTextField text1;
final JPasswordField text2;

Form(){
label1 = new JLabel();
label1.setText("UserName:");
text1 = new JTextField(15);

label2 = new JLabel();


label2.setText("Password:");
text2 = new JPasswordField(15);
SUBMIT=new JButton("Login");
panel=new JPanel(new GridLayout(3,1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel,BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("FORM");
}
public void actionPerformed(ActionEvent ae){

44
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

String value1=text1.getText();
String value2=text2.getText();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:dbdsn");
Statement stmt =(Statement) con.createStatement();

String q;
q=" select * from admin where username='"+text1.getText()+"' and password='"+text2.getText()+"'";
ResultSet res=stmt.executeQuery(q);
if (res.next()) {
JOptionPane.showMessageDialog(this,"Login Success:");
}
else
{
JOptionPane.showMessageDialog(this,"Login Incorrect:");
}

}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}

45
M.G.M’s College Of Engineering, Nanded Database Management System
Department of Computer Science & Engineering.

class LoginDemo{
public static void main(String arg[]) {
try {
Form frame=new Form();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}

46

You might also like