You are on page 1of 49

Experiment 1

Relational and Object Relational Database Management Systems


Objectives :
After completing this lesson, you should be able to know the following:

• Oracle Database 11g extends:

– the benefits of infrastructure grids

– the existing information management capabilities

– the capabilities to use the major application development environments


such as PL/SQL, Java/JDBC, .NET, XML, and so on

• The database is based on ORDBMS.

• Relational databases are composed of relations, managed by relational operations,


and governed by data integrity constraints.

• With the Oracle server, you can store and manage information by using SQL.

Introduction :

The Oracle server supports both the relational and the object relational database models.

The Oracle server extends the data-modeling capabilities to support an object relational database
model that provides object-oriented programming, complex data types, complex business objects,
and full compatibility with the relational world.

It includes several features for improved performance and functionality of the OLTP applications,
such as better sharing of run-time data structures, larger buffer caches, and deferrable constraints.
Data warehouse applications benefit from enhancements such as parallel execution of insert,
update, and delete operations; partitioning; and parallel-aware query optimization. Operating
within the Network Computing Architecture (NCA) framework, the Oracle model supports
client/server and Web-based applications that are distributed and multitiered.

Every organization has some information needs. A library keeps a list of members, books, due
dates, and fines. A company needs to save information about its employees, departments, and
salaries. These pieces of information are called data.

Organizations can store data in various media and in different formats, such as a hard copy
document in a filing cabinet, or data stored in electronic spreadsheets, or in databases.

A database is an organized collection of information.

To manage databases, you need a database management system (DBMS). A DBMS is a program
that stores, retrieves, and modifies data in databases on request.
Q1: What is the meaning of Database ?

Q2: Organizations can store data in various media and in different formats, List some of them ?

Q3: What is the need for using Database Management Systems ?

Q4: What is the name of the software you will use it to establish and manage Database ?
Experiment 2
Retrieving Data Using the SQL SELECT Statement
Objectives :
After completing this lesson, you should be able to do the following:

• List the capabilities of SQL SELECT statements

• Execute a basic SELECT statement

Lesson Agenda:
• Basic SELECT statement

• Arithmetic expressions and NULL values in the SELECT statement

• Column aliases

• Use of concatenation operator, literal character strings, alternative quote operator,


and the DISTINCT keyword

• DESCRIBE command

Introduction :
A SELECT statement retrieves information from the database. With a SELECT statement, you can
use the following capabilities:

Projection: Select the columns in a table that are returned by a query. Select as few or as many of
the columns as required.

Selection: Select the rows in a table that are returned by a query. Various criteria can be used to
restrict the rows that are retrieved.

Joining: Bring together data that is stored in different tables by specifying the link between them.
SQL joins are covered in more detail in the lesson titled “Displaying Data from Multiple Tables.”

Question: What is the rules and guidelines, that you can use to construct valid statements that
are both easy to read and edit?

Assignment 2:
• Write SQL statement to perform the following :

A)Display these three columns ( FIRST_NAME , LAST_NAME , HIRE_DATE ) .

B) Describe EMPLOYEES Table.

C) List all customers from CUSTOMERS table .

• For table EMPLOYEES write SQL statement to perform the following :

A)Multiplies any two numbers .

B)Display the addition of 1500$ to salaries of all employees .

C) Display the addition of commission would be calculated on the salary and then added to the
salary .
Experiment 3
Restricting and Sorting Data
Objectives :

After completing this lesson, you should be able to do the following:

• Limit the rows that are retrieved by a query

• Sort the rows that are retrieved by a query

• Use ampersand substitution to restrict and sort output at run time

Lesson Agenda:

• Limiting rows with:

-The WHERE clause

-The comparison conditions using =, <=, BETWEEN, IN, LIKE, and NULL conditions

-Logical conditions using AND, OR, and NOT operators

• Rules of precedence for operators in an expression

• Sorting rows using the ORDER BY clause

• Substitution variables

• DEFINE and VERIFY commands

Introduction :

When retrieving data from the database, you may need to do the following:

• Restrict the rows of data that are displayed

• Specify the order in which the rows are displayed

You can restrict the rows that are returned from the query by using the WHERE clause. A WHERE
clause contains a condition that must be met and it directly follows the FROM clause. If the
condition is true, the row meeting the condition is returned .

Question : Assume that you want to display all the employees in department 90 , what will be the
SQL statement to do this ?

Assignement3:

1.Write SQL statement to get all the columns from the Customers table.
2.Write SQL starement to select all different values from the Country column in the
Customers table.

3. The clause that used to filter the records and choose records where City is NOT (Berlin)
is /are :

a.Where city <> ‘Berlin’

b.where city != ‘ Berlin’

c.where city not like ‘Berlin’

d. all of the above

4. Select all records from the Customers table, sort the result reversed alphabetically by the
column City.

5. Select all records from the Customers where the PostalCode column is NOT empty.

Below is a selection from the "Customers" table :


Below is a selection from the "Products" table :
Experiment 4
Using Single-Row Functions to Customize Output
Objectives

After completing this lesson, you should be able to do the following:

• Describe various types of functions available in SQL


• Use character, number, and date functions in SELECT statements

Lesson Agenda

• Single-row SQL functions

• Character functions

• Number functions

• Working with dates

• Date functions
Introduction :

Functions make the basic query block more powerful, and they are used to manipulate data
values. This is the first of two lessons that explore functions. It focuses on single-row character,
number, and date functions.

Functions are a very powerful feature of SQL. They can be used to do the following:

• Perform calculations on data

• Modify individual data items

• Manipulate output for groups of rows

• Format dates and numbers for display

• Convert column data types

SQL functions sometimes take arguments and always return a value.

Question :There are two types of functions, List them then explain the difference between
these two types?
Assignment Sheet Lab 4
1.Get first_name and last_name as single column from employees table separated by ‘_’ .

2. Write SQL statement to select all the records where the value of the Price column is
NOT between 10 and 20.

3.Give the result of the following SQL statement :

Do it manually ( Don’t apply the statement on the Software )

Select round (65.923,2 ) ,round(65.923,0) , round (65.923,-1 ) , trunc(65.923,-1 ), mod(9,4)

From DUAL ;

4.Write SQL statement to display the first 3 characters of first_name from employees table.

5. When displaying the Customers table, make an ALIAS of the PostalCode column, the
column should be called Pno instead.
6. Write SQL statement to select all the records where Country is NOT "Norway" and
NOT "France".(use customers table )

7. Write SQL statement to selects all customers with a ContactName that starts with "a"
and ends with "o" .

8. Select all records from the Customers where the PostalCode column is NOT empty.

Get the result of the following queries :

9.Select INSTR ( ‘Mississippi‘ , ‘issi’ ,1,2 )

From dual ;

10.Select last_name , INSTR ( last_name , ‘ton‘ ) ton_position , SUBSTR ( last_name


,INSTR ( last_name , ‘ton‘ )) substring_ton

From employees ; (Apply this statement )


Below is a selection from the "Customers" table :

Below is a selection from the "Products" table :


Experiment 5
Using Conversion Functions and Conditional Expressions
Objectives:

After completing this lesson, you should be able to do the following:

• Describe various types of conversion functions that are available in SQL

• Use the TO_CHAR, TO_NUMBER, and TO_DATE conversion functions

• Apply conditional expressions in a SELECT statement

Lesson Agenda:

• Implicit and explicit data type conversion

• TO_CHAR, TO_DATE, TO_NUMBER functions

• Nesting functions

• General functions:

– NVL

– NVL2

– NULLIF

– COALESCE

• Conditional expressions:

– CASE

– DECODE

Assignment5
Q1) write down the results of the following queries :

a_ select employee_id , last_name ,first_name ,nvl( manager_id ,0 ) manager


from employees ;

b_ select employee_id , last_name, first_name , nvl( manager_id , ‘ has no manager ‘ )


manager

from employees ;

if it doesn’t work >>>>> think of a solution ??? and find the answer .

c_ select employee_id , first_name ,last_name , manager_id ,

decode( manager_id ,100,’ King ’ ,103 , ‘ Ernst ‘) , decode ( employee_id , 100 , ‘ is King ‘ ,
103 , ‘ is Ernst ‘ , ‘ neither King nor Ernst ‘ ) manager

from employees ;

d_ select employee_id , first_name , last_name , salary ,

case when manager_id = 100 then ‘ Emily is the manager …. No bonus this year ’

when salary < 80000 then ‘ bonus this year ‘


end “ Bonus? “

from employees ;

e_ select employee_id , first_name , last_name , salary

From employees

Where salary + case

When round (( salary /52) + (salary *.03 /52 )) > 1500 then 0

When round (( salary /52 ) + ( salary *.03/52 )) < 1300 then 500

Else 200

End >10000;

f_ select first_name , last_name ,

to_char ( hire_date , ‘DD-MON-YYYY HH:MI:SS ‘ ) hire_date

From employees ;
g_ select SYSDATE ,to_char( SYSDATE , ‘DD-MON-YYYY HH24:MI:SS’)
sysdate_with_time

From dual ;

h_ Add 12 months to date 15-dec-2000 and subtract 1 day


Experiment 6
Reporting Aggregated DataUsing the Group Functions
Objectives:
After completing this lesson, you should be able to do the following:

• Identify the available group functions

• Describe the use of group functions

• Group data by using the GROUP BY clause

• Include or exclude grouped rows by using the HAVING clause

Lesson Agenda:

• Group functions:

– Types and syntax

– Use AVG, SUM, MIN, MAX, COUNT

– Use DISTINCT keyword within group functions

– NULL values in a group function

• Grouping rows:

– GROUP BY clause

– HAVING clause

• Nesting group functions

Introduction :

Unlike single-row functions, group functions operate on sets of rows to give one result per
group. These sets may comprise the entire table or the table split into groups.
Each of the functions accepts an argument. The following table identifies the options that you
can use in the syntax:

Function Description
AVG([DISTINCT|ALL]n) Average value of n, ignoring null values
COUNT({*|[DISTINCT|ALL]expr Number of rows, where expr evaluates to
}) something other than null (count all selected
rows using *, including duplicates and rows
with nulls)
MAX([DISTINCT|ALL]expr) Maximum value of expr, ignoring null values
MIN([DISTINCT|ALL]expr) Minimum value of expr, ignoring null values
STDDEV([DISTINCT|ALL]x) Standard deviation of n, ignoring null values
SUM([DISTINCT|ALL]n) Sum values of n, ignoring null values
VARIANCE([DISTINCT|ALL]x) Variance of n, ignoring null values

Question :
Write SQL Statement to display the average, highest, lowest, and sum of monthly salaries for
all sales representatives.

Assignment 6:
Determine the validity of the following three statements. Circle either True or False.

1. Group functions work across many rows to produce one result. True / False

2. Group functions include nulls in calculations. True / False

3. The WHERE clause restricts rows prior to inclusion in a group calculation. True/False

4. Display the highest, lowest, sum, and average salary of all employees. Label the

columns Maximum , Minimum , Sum , and Average , respectively. Round your results to

the nearest whole number.


5. Modify the previous query to display the minimum, maximum, sum, and average salary

for each job type.

6. Write a query to display the number of people with the same job .

7.determine the number of managers without listing them . Label the column number of

managers .

8.Find the difference between the highest and lowest salaries. Label the column

DIFFERENCE .
9.Create a report to display the manager number and the salary of the lowest-paid

employee for that manager. Exclude anyone whose manager is not known. Exclude any

groups where the minimum salary is $6,000 or less. Sort the output in descending order of

salary.
Experiment 7
Using Subqueries to Solve Queries
Objectives:
After completing this lesson, you should be able to do the following:

• Define subqueries

• Describe the types of problems that the subqueries can solve

• List the types of subqueries

• Write single-row and multiple-row subqueries


Lesson Agenda:
Subquery: Types, syntax, and guidelines

• Single-row subqueries:

– Group functions in a subquery

– HAVING clause with subqueries

• Multiple-row subqueries

– Use ALL or ANY operator

• Null values in a subquery

Introduction :
In this lesson, you learn about the more advanced features of the SELECT statement. You can
write subqueries in the WHERE clause of another SQL statement to obtain values based on an
unknown conditional value. This lesson also covers single-row subqueries and multiple-row
subqueries.

Suppose you want to write a query to find out who earns a salary greater than Abel’s salary.

To solve this problem, you need two queries: one to find how much Abel earns, and a second
query to find who earns more than that amount.

You can solve this problem by combining the two queries, placing one query inside the other
query.

The inner query (or sub query) returns a value that is used by the outer query (or main query).
Using a sub query is equivalent to performing two sequential queries and using the result of the
first query as the search value in the second query.
Question :

Try to write SQL query to display the above task ?

Assignment 7 :
1. The HR department needs a query that prompts the user for an employee last name. The query
then displays the last name and hire date of any employee in the same department as the employee
whose name they supply (excluding that employee). For example, if the user enters Zlotkey, find
all employees who work with Zlotkey (excluding Zlotkey).

2. Create a report that displays the employee number, last name, and salary of all employees who
earn more than the average salary. Sort the results in order of ascending salary.
3. Write a query that displays the employee number and last name of all employees who work in a
department with any employee whose last name contains a u.

4. The HR department needs a report that displays the last name, department number, and job ID of
all employees whose department location ID is 1700.

5. Create a report for HR that displays the last name and salary of every employee who reports to
King.

6. Create a report for HR that displays the department number, last name, and job ID for every
employee in the Executive department.
Experiment 8
Using DDL Statements to Create and Manage Tables
Objectives:
After completing this lesson, you should be able to do the following:

• Categorize the main database objects

• Review the table structure

• List the data types that are available for columns

• Create a simple table

• Explain how constraints are created at the time of table creation

• Describe how schema objects work

Lesson Agenda:

• Database objects

– Naming rules

• CREATE TABLE statement:

– Access another user’s tables

– DEFAULT option

• Data types

• Overview of constraints: NOT NULL, PRIMARY KEY, FOREIGN KEY, CHECK

constraints

• Creating a table using a subquery

• ALTER TABLE

– Read-only tables

• DROP TABLE statement


Introduction :

In this lesson, you are introduced to the data definition language (DDL) statements. You are

taught the basics of how to create simple tables, alter them, and remove them. The data types

available in DDL are shown and schema concepts are introduced. Constraints are discussed in

this lesson. Exception messages that are generated from violating constraints during DML

operations are shown and explained.

Database Objects

The Oracle database can contain multiple data structures. Each structure should be outlined in

the database design so that it can be created during the build stage of database development.

• Table: Stores data

• View: Subset of data from one or more tables

• Sequence: Generates numeric values

• Index: Improves the performance of some queries

• Synonym: Gives alternative name to an object

Oracle Table Structures

• Tables can be created at any time, even when users are using the database.

• You do not need to specify the size of a table. The size is ultimately

defined by the amount of space allocated to the database as a whole. It is

important, however, to estimate how much space a table will use over

time.

• Table structure can be modified online.

Question : Mention the database objects you can create on oracle database System ?
Assignment 8 :

Create STUDENTS / COLLEGES tables using DDL statements which must contains the
following columns

STUDENTS (STD_NO , STD_NAME , STD_SSN , STD_COLL_NO, STD_AVG,


ENROLLMENT_DATE)

COLLEGES ( COLL_NAME,COLL_NO, COLL_LOCATION )

Choose the suitable constraints if necessary , don’t forget to make reference between these two
tables .
Experiment 9
Creating Other Schema Objects
Objectives:
After completing this lesson, you should be able to do the following:

• Create simple and complex views

• Retrieve data from views

• Create, maintain, and use sequences

• Create and maintain indexes

• Create private and public synonyms

Lesson Agenda:
• Overview of views:

– Creating, modifying, and retrieving data from a view

– Data manipulation language (DML) operations on a view

– Dropping a view

• Overview of sequences:

– Creating, using, and modifying a sequence

– Cache sequence values

– NEXTVAL and CURRVAL pseudocolumns

• Overview of indexes

– Creating, dropping indexes

• Overview of synonyms

– Creating, dropping synonyms


Introduction :

There are several other objects in a database in addition to tables. In this lesson, you learn about

the views, sequences, indexes, and synonyms.

With views, you can present and hide data from the tables.

Many applications require the use of unique numbers as primary key values. You can either build

code into the application to handle this requirement or use a sequence to generate unique

numbers.

If you want to improve the performance of data retrieval queries, you should consider creating an

index. You can also use indexes to enforce uniqueness on a column or a collection of columns.

You can provide alternative names for objects by using synonyms.

Question : There are several other objects in a database in addition to tables, mention them ?
Assignment 9:

1.Write SQL Statement to create a view that contains the employee number, last name, and

salary , hire_date , commission_pct for each employees who works as Representatives.

Name the view as empv_rep .

2. Describe the structure of empv_rep , created in the previous part .

3. Write SQL statement to create a sequence named EMP_EMPID_SEQ to be used for the

EMPLOYEE_ID column of the EMPLOYEES table.


Experiment 10
Displaying Data from Multiple Tables
Objectives:
After completing this lesson, you should be able to do the following:

• Write SELECT statements to access data from more than one table using
equijoins and nonequijoins

• Join a table to itself by using a self-join

• View data that generally does not meet a join condition by using outer joins

• Generate a Cartesian product of all rows from two or more tables

Lesson Agenda:
• Types of JOINS and its syntax

• Natural join:

– USING clause

– ON clause

• Self-join

• No equijoins

• OUTER join:

– LEFT OUTER join

– RIGHT OUTER join

– FULL OUTER join

• Cartesian product

– Cross join
Introduction :
This lesson explains how to obtain data from more than one table. A join is used to view
information from multiple tables. Therefore, you can join tables together to view information
from more than one table.

Question :

How many types of joins you can use to obtain data from more than one table ?
Assignment 10 :

Imagine you’re running a store and would like to record information about your customers and
their orders. By using a relational database, you can save this information as two tables that
represent two distinct entities: customers and orders.

Customers
customer
first_name last_name email address city state zip
_id
1 George Washington gwashington@usa.gov 3200 Mt Mount Vernon VA 22121
Vernon Hwy
2 John Adams jadams@usa.gov 1250 Hancock Quincy MA 02169
St
3 Thomas Jefferson tjefferson@usa.gov 931 Thomas Charlottesville VA 22902
Jefferson
Pkwy
4 James Madison jmadison@usa.gov 11350 Orange VA 22960
Constitution
Hwy
5 James Monroe jmonroe@usa.gov 2050 James Charlottesville VA 22902
Monroe Pkwy

Here, information about each customer is stored in its own row, with columns specifying different
bits of information, including their first name, last name, and email address. Additionally, we
associate a unique customer number, or primary key, with each customer record.

Orders
order_id order_date amount customer_id
1 07/04/1776 $234.56 1
2 03/14/1760 $78.50 3
3 05/23/1784 $124.00 2
4 09/03/1790 $65.50 3
5 07/21/1795 $25.50 10
6 11/27/1787 $14.40 9

Again, each row contains information about a specific order. Each order has its own unique
identification key – order_id for this table – assigned to it as well.

1. Let’s say we want to find all orders placed by a particular customer. We can do this by
joining the customers and orders tables together using the relationship established by the
customer_id key, Write down SQL statement to perform this ?
2. Write SQL statement to list all records from both tables.

3. Write SQL statement to join the LOCATIONS with the DEPARTMENT table to those with
a department ID equal to 20 or 50 by the LOCATION_ID column, which is the only column
of the same name in both tables. If other common columns were present, the join would have
used them all.
Experiment 11
Using the Set Operators
Objectives:
After completing this lesson, you should be able to do the following:

• Describe set operators

• Use a set operator to combine multiple queries into a single query

Control the order of rows returned

Lesson Agenda:

• Set Operators: Types and guidelines

• Tables used in this lesson

• UNION and UNION ALL operator

• INTERSECT operator

• MINUS operator

• Matching the SELECT statements

• Using the ORDER BY clause in set operations

Introduction :

Set operators combine the results of two or more component queries into one result. Queries
containing set operators are called compound queries.

Operator Returns
UNION Rows from both queries after eliminating duplications
UNION ALL Rows from both queries, including all duplications
INTERSECT Rows that are common to both queries
MINUS Rows in the first query that are not present in the second query

All set operators have equal precedence. If a SQL statement contains multiple set operators, the
Oracle server evaluates them from left (top) to right (bottom)—if no parentheses explicitly specify
another order. You should use parentheses to specify the order of evaluation explicitly in queries
that use the INTERSECT operator with other set operators.

Question :

What is the function of set operators ?

Assignment 11 ;
1.Write SQL statement to return the cities (only distinct values) from both the "Customers" and
the "Suppliers" table .

2. Write SQL statement to return the cities (duplicate values also) from both the "Customers" and
the "Suppliers" table .

3.Write SQL statement to return the German cities (only distinct values) from both the
"Customers" and the "Suppliers" table .

4. Write SQL statement to list all customers and suppliers .


Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City PostalCode Country

1 Exotic Liquid Charlotte 49 Gilbert London EC1 4SD UK


Cooper St.

2 New Orleans Shelley Burke P.O. Box New 70117 USA


Cajun Delights 78934 Orleans

3 Grandma Kelly's Regina 707 Ann 48104 USA


Homestead Murphy Oxford Arbor
Rd.
Experiment 12
Manipulating Data
Objectives:
After completing this lesson, you should be able to do the following:

• Describe each data manipulation language (DML) statement

• Insert rows into a table

• Update rows in a table

• Delete rows from a table

• Control transactions

Lesson Agenda:
• Adding new rows in a table

– INSERT statement

• Changing data in a table

– UPDATE statement

• Removing rows from a table:

– DELETE statement

– TRUNCATE statement

• Database transactions control using COMMIT, ROLLBACK, and SAVEPOINT

• Read consistency

• FOR UPDATE clause in a SELECT statement

Introduction :

In this lesson, you learn how to use the data manipulation language (DML) statements to insert
rows into a table, update existing rows in a table, and delete existing rows from a table. You also
learn how to control transactions with the COMMIT, SAVEPOINT, and ROLLBACK
statements.

Data manipulation language (DML) is a core part of SQL. When you want to add, update, or
delete data in the database, you execute a DML statement. A collection of DML statements that
form a logical unit of work is called a transaction.
Consider a banking database. When a bank customer transfers money from a savings account to
a checking account, the transaction might consist of three separate operations: decreasing the
savings account, increasing the checking account, and recording the transaction in the transaction
journal. The Oracle server must guarantee that all the three SQL statements are performed to
maintain the accounts in proper balance. When something prevents one of the statements in the
transaction from executing, the other statements of the transaction must be undone.

Question :

What is the meaning of transactions ?

Assignment 12 ;
1.Insert a new row to EMPLOYEES table containing values for each column.

You can insert any suitable value .

2. An employee who was a SA_REP has now changed his job to an IT_PROG.
make the required modifications , what should be change in the commission_pct field ?

3. Update the COPY_EMP table based on the values from the EMPLOYEES table , change the
department number of all employees with employee 20’s job ID to employee 90’s current
department number.

You might also like