Вы находитесь на странице: 1из 27

Please check all the commands/Text by yourself, Author will not be responsible for any

error or any mismatch. This is just to help for students.

Oracle Lab Notes

SQL> CLEAR SCREEN;

This command will clear the screen

How to create a table

SQL> CREATE TABLE EMPLOYEE1 (


2 EMP_NAME VARCHAR2(25),
3 CITY VARCHAR2(20),
4 SALARY NUMBER(6));

Table created.

1
Display Table structure

SQL> Desc Table_Name;

Example:
SQL> DESC EMPLOYEE1
Name Null? Type
----------------------------------------------------- -------- --------------------
EMP_NAME VARCHAR2(25)
CITY VARCHAR2(20)
SALARY NUMBER(6)

INSERT DATA INTO TABLE

insert into table_name


values
data;

SQL> insert into employee1


2 values
3 ('ali','ankara', 2400);

1 row created.

How to display Data

SQL> select * from employee1;

EMP_NAME CITY SALARY


------------------------- -------------------- ---------
ali ankara 2400

SQL> insert into employee1


values
('ali','ankara', 2400);

1 row created.

Enter More data


SQL> insert into employee1
values

2
('ahmet','ankara', 2000);

1 row created.
SQL> insert into employee1
values
('Can','izmir', 2400);

1 row created.

SQL> insert into employee1


values
('hakan','izmir', 2000);

1 row created.

SQL> insert into employee1


values
('kasim','ankara', 2400);

1 row created.

Display All Data

SQL> select * from employee1


2 ;

EMP_NAME CITY SALARY


------------------------- -------------------- ---------
ali ankara 2400
ali ankara 2400
ahmet ankara 2000
kasim ankara 2400
hakan izmir 2000
Can izmir 2400

6 rows selected.

Display Data on specific columns.

SQL> select emp_name , salary from employee1;

EMP_NAME SALARY
------------------------- ---------
ali 2400
ali 2400
ahmet 2000
kasim 2400
hakan 2000

3
Can 2400

6 rows selected.
SQL> Select emp_name, city from employee1;

EMP_NAME CITY
------------------------- --------------------
ali ankara
ali ankara
ahmet ankara
kasim ankara
hakan izmir
Can izmir

6 rows selected.

4
Lab# 3

How to use Primary Key in the Tables

SQL> CREATE TABLE STUDENT1 (


STUDENT_ID VARCHAR2(15) PRIMARY KEY,
NAME VARCHAR2(20),
ADDRESS VARCHAR2(20),
CITY VARCHAR2(20));

Table created.

SQL> INSERT INTO STUDENT1


VALUES
('INDS01', 'MUSTAFA', 'ATILIM', 'ANKARA');

1 row created.

SQL> INSERT INTO STUDENT1


VALUES
('INDS02', 'MUSTAFA CAN ', 'ATILIM', 'ANKARA');

1 row created.

SQL> INSERT INTO STUDENT1


VALUES
('INDS03', 'CANTURK', 'GOP', 'ANKARA');

1 row created.

SQL> INSERT INTO STUDENT1


VALUES
('INDS04', 'MEHMET ALI', 'ATILIM', 'ANKARA');

1 row created.

SQL> INSERT INTO STUDENT1


VALUES
('INDS05', 'KEREM PASHA', 'ATILIM', 'ANKARA');

1 row created.

SQL> INSERT INTO STUDENT1


VALUES
('INDS06', 'IBRAHIM', 'ATILIM', 'ANKARA');

1 row created.

Dısplay all data by

5
SQL> SELECT * FROM STUDENT1;
SQL> INSERT INTO STUDENT1
VALUES
('INDS01', 'MUSTAFA', 'ATILIM', 'ANKARA');
INSERT INTO STUDENT1
*
ERROR at line 1:
ORA-00001: unique constraint (REHAN.SYS_C0010350) violated

IF WE INPUT SAME DATA IN PRIMARY KEY TABLE, ERROR WILL GENERATE

SQL> INSERT INTO STUDENT1


2 VALUES
3 ('INDS06','EMRAN','ATILIM', 'ANKARA');
INSERT INTO STUDENT1
*
ERROR at line 1:
ORA-00001: unique constraint (REHAN.SYS_C0010350) violated

SQL> SELECT * FROM STUDENT1;

STUDENT_ID NAME ADDRESS CITY


--------------- -------------------- -------------------- -------------------
INDS01 MUSTAFA ATILIM ANKARA
INDS06 IBRAHIM ATILIM ANKARA
INDS05 KEREM PASHA ATILIM ANKARA
INDS04 MEHMET ALI ATILIM ANKARA
INDS03 CANTURK GOP ANKARA
INDS02 MUSTAFA CAN ATILIM ANKARA

6 rows selected.

SQL> COMMIT;

Commit complete.

SQL> CREATE TABLE S_GRADE (


2 STUDENT_ID VARCHAR2(15),
3 COURSE_NAME VARCHAR2(10),
4 EXAM_NAME VARCHAR2(10),
5 OBT_MARKS NUMBER(6,2),
6 CONSTRAINT FK_STUDENT FOREIGN KEY(STUDENT_ID) REFERENCES
STUDENT1);

Table created.

6
Insert Data

SQL> INSERT INTO S_GRADE


VALUES
('INDS01', 'COMPE343','MIDTERM I', 88);

1 row created.

SQL> INSERT INTO S_GRADE


2 VALUES
3 ('INDS11', 'COMPE343','MIDTERM I', 88);
INSERT INTO S_GRADE
*
ERROR at line 1:
ORA-02291: integrity constraint (REHAN.FK_STUDENT) violated - parent key not found

*Error will genearted Because, INDS11 IS NOT IN THE PRIMARY KEY TABLE.

SQL> INSERT INTO S_GRADE


2 VALUES
3 ('INDS01', 'COMPE343','MIDTERM II', 99);

1 row created.

SQL> SELECT * FROM S_GRADE;

STUDENT_ID CIURSE_NAM EXAM_NAME OBT_MARKS


--------------- ---------- ---------- ---------
INDS01 COMPE343 MID TERM I 88
INDS01 COMPE343 MIDTERM II 99

7
Lab #4

How to add a PRIMARY KEY to the table after creating a table without PRIMARY KEY.

SQL> CREATE TABLE EXAM1 (


2 S_ID VARCHAR2(20),
3 NAME VARCHAR2(20),
4 EAXM_NAME VARCHAR2(20),
5 SCORE NUMBER(5));

Table created.

SQL> Alter table exam1 add constraint exam_pk PRIMARY KEY(S_ID);

SQL> insert into exam1


2 values
3 ('ınds01','can','quiz',96);

1 row created.

SQL> insert into exam1


2 values
3 ('inds02','mert','quiz',78)
4 ;

1 row created.

SQL> insert into exam1


2 values
3 ('inds02','ali','quiz',77);
insert into exam1
*
ERROR at line 1:
ORA-00001: unique constraint (REHAN.SYS_C0010451) violated

DROP PRIMARY KEY

SQL> Alter table exam1 drop constraint exam_pk;

Table altered.

Disable a Primary Key


The syntax for disabling a primary key is:

ALTER TABLE table_name disable CONSTRAINT constraint_name;

For example:

ALTER TABLE exam1 disable CONSTRAINT exam_pk;


In this example, we're disabling a primary key on the exam1 table called exam_pk.

8
Enable a Primary Key
The syntax for enabling a primary key is:

ALTER TABLE table_name


enable CONSTRAINT constraint_name;

For example:

ALTER TABLE exam1


enable CONSTRAINT exam_pk;

Create Table form Other Table

SQL> SELECT * FROM EXAM1;

S_ID NAME EAXM_NAME SCORE


-------------------- -------------------- -------------------- ---------
inds01 can quiz 96
inds02 mert quiz 78

SQL> create table abc


2 as
3 (select * from exam1);

Table created.

SQL> SELECT * FROM ABC;

S_ID NAME EAXM_NAME SCORE


-------------------- -------------------- -------------------- --------
inds01 can quiz 96
inds02 mert quiz 78

9
DATE DATATYPE- DATE DATATYPE IS USED TO STORE DATE IN THE TABLE.

SQL> CREATE TABLE DOB (


2 NAME VARCHAR2(20),
3 DATE_OF_BIRTH DATE );

Table created.

SQL> INSERT INTO DOB


2 VALUES
3 ('ALI', '26-AUG-2006');

1 row created.

SQL> INSERT INTO DOB


2 VALUES
3 ('MEHMET', '24-JUL-2006');

1 row created.

SQL> INSERT INTO DOB


2 VALUES
3 ('JOHN','28-AUG-2006');

1 row created.

SQL> INSERT INTO DOB


2 VALUES
3 ('AHMET','10-SEP-2006');

1 row created.

SQL> SELECT * FROM DOB;

NAME DATE_OF_B
-------------------- ---------
ALI 26-AUG-06
MEHMET 24-JUL-06
JOHN 28-AUG-06
AHMET 10-SEP-06

Now Create A Table with Following Data


* Table: Customers

FirstName LastName Email DOB Phone


John Smith John.Smith@yahoo.com 2/4/1968 626 222-2222
Steven Goldfish goldfish@fishhere.net 4/4/1974 323 455-4545
Paula Brown pb@herowndomain.org 5/24/1978 416 323-3232
James Smith jim@supergig.co.uk 20/10/1980 416 323-8888

* Put your Table Name

Then Display Data by Following Command


SQL> SELECT * FROM Customer ;

Distinct Command

10
The SQL DISTINCT clause is used together with the SQL SELECT keyword, to return a dataset with
unique entries for certain database table column.

SQL> SELECT DISTINCT LastName FROM Customers;

The result of the SQL DISTINCT expression above will look like this:

LastName

Smith
Goldfish
Brown

where Command

SELECT * FROM Customers


WHERE LastName like 'Smith'

The result of the SQL expression above will be the following:

FirstName LastName Email DOB Phone


John Smith John.Smith@yahoo.com 2/4/1968 626 222-2222
James Smith jim@supergig.co.uk 20/10/1980 416 323-8888

SQL> select * from dob


2 where
3 name = 'ALI';

NAME DATE_OF_B
-------------------- ---------
ALI 26-AUG-06

But we can use any of the following comparison operators in conjunction with the SQL WHERE
clause:

<> (Not Equal) OR !=

SQL> SELECT * FROM Customers


WHERE LastName <> 'Smith';
Check output

SQL> select * from dob


2 where
3 name <> 'ALI';
NAME DATE_OF_B
-------------------- ---------
MEHMET 24-JUL-06
JOHN 28-AUG-06
AHMET 10-SEP-06
SQL> select * from dob
2 where

11
3 name != 'ALI';
NAME DATE_OF_B
-------------------- ---------
MEHMET 24-JUL-06
JOHN 28-AUG-06
AHMET 10-SEP-06

> (Greater than)

SELECT *
FROM Customers
WHERE DOB > '1/1/1970';

>= (Greater or Equal)

SELECT *
FROM Customers
WHERE DOB >= '1/1/1970';

< (Less than)

SELECT *
FROM Customers
WHERE DOB < '1/1/1970';

<= (Less or Equal)

SELECT * FROM Customers


WHERE DOB <= '1/1/1970';

LIKE (similar to)

SELECT * FROM Customers


WHERE Phone LIKE '626%'

Note the LIKE syntax is different with the different RDBMS (SQL Server syntax used above). Check
the SQL LIKE article for more details.

Between (Defines a range)

SELECT *
FROM Customers
WHERE DOB BETWEEN '1/1/1970' AND '1/1/1975';
Lab#5

Some more queries.

12
DISPLAY Columns
The columns to be selected from a table are specified after the keyword SELECT.

SELECT * FROM EMP;


SELECT * FROM DEPT;

SELECT LOC, DEPTNO from DEPT;

SELECT ENAME, DEPTNO, SAL ∗ 36 from EMP;

For the order by clause is used and which has one or more attributes
listed in the select clause as parameter. desc command specifies a
descending order and asc specifies an ascending order (this is also the
default order). For example, the query

SELECT ENAME, DEPTNO, HIREDATE from EMP;


from EMP
order by DEPTNO [asc], HIREDATE desc;

Next
Set Conditions: <column> [not] in (<list of values>)
Exampl1e:
SELECT ∗ from DEPT where DEPTNO in (10,30);

• Null value: <column> is [not] null,

Example2 : Test by yourself, if any error, then make correction.

SELECT ∗ from EMP


where MGR is not null;

SELECT ∗ from EMP


where MGR is null;

Example3 : •
SELECT EMPNO, ENAME, SAL from EMP
where SAL between 1000 and 3500;

SELECT ENAME from EMP


where HIREDATE between ’02-APR-81’ and ’08-SEP-81’;

Aggregate Functions
Aggregate functions are statistical functions such as count, min, max etc.
They are used to compute a single value from a set of attribute values of a
column:

count command is used to counting Rows in the table.

13
SELECT count(∗) from EMP;

Ex1: How many different type of job are save in the EMP table.
SELECT count(distinct JOB) from EMP;

max and min (value for a column)

Ex2: Display the minimum and maximum salary.


SELECT min(SAL), max(SAL) from EMP;

Ex3: Find out the difference between the minimum and maximum salary.
SELECT max(SAL) - min(SAL) from EMP;

Ex4: Sum of all salaries of employees working in the department 30.


SELECT sum(SAL) from EMP
where DEPTNO = 20;

Unique Key Command

Create Table abc123456 (


P_NO number(4) unique,
P_NAME varchar2(20) ,
P_PERSONS number(6),
BUDGET number(12,2),
P_START date,
P_END date);

SQL> insert into abc123456


2 values
3 (313, 'DBS', 10, 15000.42, '10-OCT-94', '10-OCT-99');

1 row created.

SQL> insert into abc123456


2 values
3 (314, 'DBS2', 10, 16000.42, '15-OCT-94', '20-OCT-99');

1 row created.

SQL> insert into abc123456


2 values
3 (314, 'DBS2', 10, 16000.42, '15-OCT-94', '20-OCT-99');
insert into abc123456
*
ERROR at line 1:
ORA-00001: unique constraint (REHAN.SYS_C0010564) violated

14
Lab#6
Student Should create followin tables.

Example Table STUDENTS students must put other name of same table

CREATE TABLE students (studentid NUMBER(5,0), name VARCHAR2(25),


major VARCHAR2(15), gpa NUMBER(6,3),
tutorid NUMBER(5,0));

INSERT INTO students VALUES (101, 'Bill', 'CIS', 3.45, 102);


INSERT INTO students VALUES (102, 'Mary', 'CIS', 3.10, NULL);
INSERT INTO students VALUES (103, 'Sue', 'Marketing', 2.95, 102);
INSERT INTO students VALUES (104, 'Tom', 'Finance', 3.5, 106);
INSERT INTO students VALUES (105, 'Alex', 'CIS', 2.75, 106);
INSERT INTO students VALUES (106, 'Sam', 'Marketing', 3.25, 103);
INSERT INTO students VALUES (107, 'Jane', 'Finance', 2.90, 102);

Example table COURSES:

Create table courses(studentid NUMBER(5,0) NOT NULL,


coursenumber VARCHAR2(15) NOT NULL,
coursename VARCHAR2(25), semester VARCHAR2(10),
year NUMBER(4,0), grade VARCHAR2(2));

INSERT INTO courses VALUES (101, 'CIS3400', 'DBMS I', 'FALL', 1997, 'B+');
INSERT INTO courses VALUES (101, 'CIS3100', 'OOP I', 'SPRING', 1999, 'A-');
INSERT INTO courses VALUES (101, 'MKT3000', 'Marketing', 'FALL', 1997,
'A');
INSERT INTO courses VALUES (102, 'CIS3400', 'DBMS I', 'SPRING', 1997,
'A-');
INSERT INTO courses VALUES (102, 'CIS3500', 'Network I', 'SUMMER', 1997,
'B');
INSERT INTO courses VALUES (102, 'CIS4500', 'Network II', 'FALL', 1997,
'B+');
INSERT INTO courses VALUES (103, 'MKT3100', 'Advertizing', 'SPRING', 1998,
'A');
INSERT INTO courses VALUES (103, 'MKT3000', 'Marketing', 'FALL', 1997,
'A');
INSERT INTO courses VALUES (103, 'MKT4100', 'Marketing II', 'SUMMER', 1998,
'A-');

SQL> SELECT * FROM STUDENTS;

StudentID Name Major GPA TutorId


101 Bill CIS 3.45 102
102 Mary CIS 3.1
103 Sue Marketing 2.95 102
104 Tom Finance 3.5 106
105 Alex CIS 2.75 106
106 Sam Marketing 3.25 103
107 Jane Finance 2.9 102

15
 Average GPA of all students:

SELECT AVG(gpa)
FROM students;

AVG(GPA)
----------
3.12857143
 Average GPA of Finance and CIS students:

SELECT AVG(gpa)
FROM students
WHERE major = 'CIS' OR major = 'Finance';

AVG(GPA)
----------
3.14

Give the name of the student with the highest GPA:


This is an example of a subquery

SQL> SELECT name, gpa


2 FROM students
3 WHERE gpa =
4 ( SELECT MAX(gpa) FROM students );

NAME GPA
------------------------- ---------
Tom 3.5

Another option is to enclose some text in quotes and concatenate that text with the output
of the SQL statement:

SQL> SELECT 'The student with the highest GPA is ' || name
2 FROM students
3 WHERE gpa =
4 ( SELECT MAX(gpa) FROM students );

'THESTUDENTWITHTHEHIGHESTGPAIS'||NAME
-------------------------------------------------------------
The student with the highest GPA is Tom

Show the students with the GPA grades in each major:

SELECT name, major, gpa


FROM students s1
WHERE gpa =
(
SELECT max(gpa)
FROM students s2
WHERE s1.major = s2.major
);

NAME MAJOR GPA


-------- ---------- ----------
Bill CIS 3.45

16
Tom Finance 3.5
Sam Marketing 3.25

Note the two aliases given to the students table: s1 and s2. These allow us to refer to
different views of the same table.

You may wish to sort the output based on the GPA. In this case, the output is ordered by GPA
in decending order (highest GPA will come first, etc.):

SELECT name, major, gpa


FROM students s1
WHERE gpa =
(
SELECT max(gpa)
FROM students s2
WHERE s1.major = s2.major
)
ORDER BY gpa DESC;

NAME MAJOR GPA


-------- ---------- ----------
Tom Finance 3.5
Bill CIS 3.45
Sam Marketing 3.25

Selecting from 2 or More Tables


 In the FROM portion, list all tables separated by commas. Called a Join.
 The WHERE part becomes the Join Condition

Studen should create following tables.

Table 1

Example table EMPLOYEE:

FNAME Varchar2
MI Varchar2
LNAME Varchar2
SSN Number
BDATE date
ADDRESS Varchar2
Sex Varchar2
SALARY NUMBER
SUPERSSN NUMBER
DNO NUMBER

Insert following data


FNAME MI LNAME SSN BDATE ADDRESS Sex SALARY
SUPERSSN DNO
-------- -- ------- --------- --------- ------------------------- - ------ ---------
---
JOHN B SMITH 123456789 09-JAN-55 731 FONDREN, HOUSTON, TX M 30000 333445555
5
FRANKLIN T WONG 333445555 08-DEC-45 638 VOSS,HOUSTON TX M 40000 888665555
5
ALICIA J ZELAYA 999887777 19-JUL-58 3321 CASTLE, SPRING, TX F 25000 987654321
4
JENNIFER S WALLACE 987654321 20-JUN-31 291 BERRY, BELLAIRE, TX F 43000 888665555
4
RAMESH K NARAYAN 666884444 15-SEP-52 975 FIRE OAK, HUMBLE, TX M 38000 333445555
5

17
JOYCE A ENGLISH 453453453 31-JUL-62 5631 RICE, HOUSTON, TX F 25000 333445555
5
AHMAD V JABBAR 987987987 29-MAR-59 980 DALLAS, HOUSTON, TX M 25000 987654321
4
JAMES E BORG 888665555 10-NOV-27 450 STONE, HOUSTON, TX M 55000
1

Table 2

Example table DEPARTMENT:


DNAME varchar2(20)
DNUMBER number(4)
MGRSSN number(15)
MGRSTARTD Date

Insert following data

DNAME DNUMBER MGRSSN MGRSTARTD


--------------- --------- --------- ---------
RESEARCH 5 333445555 22-MAY-78
ADMINISTRATION 4 987654321 01-JAN-85
HEADQUARTERS 1 888665555 19-JUN-71

Example Table DEPT_LOCATIONS:

Table 3

DNUMBER NUMBER
DLOCATION VARCHAR2

Insert following data

DNUMBER DLOCATION
------- ---------------
1 HOUSTON
4 STAFFORD
5 BELLAIRE
5 SUGARLAND
5 HOUSTON

Table 4

Example table DEPENDENT:

ESSN NUMBER(10)
DEPENDENT_NAME VARCHAR2(20)
SEX VARCHAR2(5)
BDATE DATE
RELATIONSHIP VARCHAR2(20)

Insert following data

ESSN DEPENDENT_NAME SEX BDATE RELATIONSHIP


--------- --------------- --- --------- ------------
333445555 ALICE F 05-APR-76 DAUGHTER
333445555 THEODORE M 25-OCT-73 SON
333445555 JOY F 03-MAY-48 SPOUSE
123456789 MICHAEL M 01-JAN-78 SON
123456789 ALICE F 31-DEC-78 DAUGHTER
123456789 ELIZABETH F 05-MAY-57 SPOUSE
987654321 ABNER M 26-FEB-32 SPOUSE

18
Now we will do some queries.

List all of the employees working in Houston:

SELECT employee.fname, employee.lname


FROM employee, dept_locations
WHERE employee.dno = dept_locations.dnumber
AND dept_locations.dlocation = 'HOUSTON' ;

FNAME LNAME
-------- --------
JOHN SMITH
FRANKLIN WONG
RAMESH NARAYAN
JOYCE ENGLISH
JAMES BORG

List each employee name and the location they work in. List them in order of location and
name:

SELECT dept_locations.dlocation, department.dname,


employee.fname, employee.lname
FROM employee, department, dept_locations
WHERE employee.dno = department.dnumber
AND department.dnumber = dept_locations.dnumber
AND employee.dno = dept_locations.dnumber
ORDER BY dept_locations.dlocation, employee.lname;

Results:
DLOCATION DNAME FNAME LNAME
--------------- --------------- -------- --------
BELLAIRE RESEARCH JOYCE ENGLISH
BELLAIRE RESEARCH RAMESH NARAYAN
BELLAIRE RESEARCH JOHN SMITH
BELLAIRE RESEARCH FRANKLIN WONG
HOUSTON HEADQUARTERS JAMES BORG
HOUSTON RESEARCH JOYCE ENGLISH
HOUSTON RESEARCH RAMESH NARAYAN
HOUSTON RESEARCH JOHN SMITH
HOUSTON RESEARCH FRANKLIN WONG
STAFFORD ADMINISTRATION AHMAD JABBAR
STAFFORD ADMINISTRATION JENNIFER WALLACE
STAFFORD ADMINISTRATION ALICIA ZELAYA
SUGARLAND RESEARCH JOYCE ENGLISH
SUGARLAND RESEARCH RAMESH NARAYAN
SUGARLAND RESEARCH JOHN SMITH
SUGARLAND RESEARCH FRANKLIN WONG

16 rows selected.

What is the highest paid salary in Houston ?

SELECT MAX(employee.salary)
FROM employee, dept_locations

19
WHERE employee.dno = dept_locations.dnumber
AND dept_locations.dlocation = 'HOUSTON';

MAX(EMPLOYEE.SALARY)
--------------------
55000

To obtain the Cartesian Product of two tables, use a SELECT statement with no WHERE
clause:

SELECT *
FROM department, dept_locations ;

DNAME DNUMBER MGRSSN MGRSTARTD DNUMBER DLOCATION


--------------- ------- --------- --------- ------- ----------
RESEARCH 5 333445555 22-MAY-78 1 HOUSTON
ADMINISTRATION 4 987654321 01-JAN-85 1 HOUSTON
HEADQUARTERS 1 888665555 19-JUN-71 1 HOUSTON
RESEARCH 5 333445555 22-MAY-78 4 STAFFORD
ADMINISTRATION 4 987654321 01-JAN-85 4 STAFFORD
HEADQUARTERS 1 888665555 19-JUN-71 4 STAFFORD
RESEARCH 5 333445555 22-MAY-78 5 BELLAIRE
ADMINISTRATION 4 987654321 01-JAN-85 5 BELLAIRE
HEADQUARTERS 1 888665555 19-JUN-71 5 BELLAIRE
RESEARCH 5 333445555 22-MAY-78 5 SUGARLAND
ADMINISTRATION 4 987654321 01-JAN-85 5 SUGARLAND
HEADQUARTERS 1 888665555 19-JUN-71 5 SUGARLAND
RESEARCH 5 333445555 22-MAY-78 5 HOUSTON
ADMINISTRATION 4 987654321 01-JAN-85 5 HOUSTON
HEADQUARTERS 1 888665555 19-JUN-71 5 HOUSTON
15 rows selected.

In which states do our employees work ?

SELECT DISTINCT dlocation


FROM dept_locations;

DLOCATION
---------------
BELLAIRE
HOUSTON
STAFFORD
SUGARLAND

List the Department name and the total salaries for each department:

SELECT department.dname, SUM( employee.salary )


FROM employee, department
WHERE employee.dno = department.dnumber
GROUP BY department.dname

Results:

DNAME SUM(EMPLOYEE.SALARY)
--------------- --------------------
ADMINISTRATION 93000
HEADQUARTERS 55000
RESEARCH 133000

20
We can also use a Column Alias to change the title of the columns

SELECT department.dname, SUM( employee.salary ) AS TotalSalaries


FROM employee, department
WHERE employee.dno = department.dnumber
GROUP BY department.dname

Results:

DNAME TOTALSALARIES
--------------- -------------
ADMINISTRATION 93000
HEADQUARTERS 55000
RESEARCH 133000

Here is a combination of a function and a column alias:

SELECT fname, lname,


salary AS CurrentSalary,
(salary * 1.03) AS ProposedRaise
FROM employee;

FNAME LNAME CURRENTSALARY PROPOSEDRAISE


-------- -------- ------------- -------------
JOHN SMITH 30000 30900
FRANKLIN WONG 40000 41200
ALICIA ZELAYA 25000 25750
JENNIFER WALLACE 43000 44290
RAMESH NARAYAN 38000 39140
JOYCE ENGLISH 25000 25750
AHMAD JABBAR 25000 25750
JAMES BORG 55000 56650

8 rows selected.
7 rows selected.

From the tree we can see that Mary tutors Bill, Sue and Jane. In turn, Sue tutors Sam. Finally,
Sam tutors both Tom and Alex.

WHERE Clause Expressions

There are a number of expressions one can use in a WHERE clause.

Subqueries using = (equals):

SELECT name, grade


FROM students
WHERE grade =
( SELECT MAX(grade) FROM students );

This assumes the subquery returns only one tuple as a result.


Typically used when aggregate functions are in the subquery.

Subqueries using the IN operator are used whenever the value of a column should be
found in a set of values. The set of values can be explicitly listed (as in the first example)
or they can be created on the fly using a subquery.

21
SELECT employee.fname, department.dname
FROM employee, department
WHERE employee.dno = department.dnumber
AND department.dname IN ('HEADQUARTERS', 'RESEARCH');

FNAME DNAME
-------- ---------------
JAMES HEADQUARTERS
JOHN RESEARCH
JOYCE RESEARCH
RAMESH RESEARCH
FRANKLIN RESEARCH

SELECT employee.fname
FROM employee
WHERE employee.dno IN
(SELECT dept_locations.dnumber
FROM dept_locations
WHERE dept_locations.dlocation = 'STAFFORD');

FNAME
-------
ALICIA
JENNIFER
AHMAD

In the above case, the subquery returns a set of tuples. The IN clause returns true when a
tuple matches a member of the set.

Subqueries using EXISTS. EXISTS will return TRUE if there is at least one row resulting
from the subquery.

SELECT fname, lname, salary


FROM employee
WHERE EXISTS
(SELECT fname
FROM EMPLOYEE e2
WHERE e2.salary > employee.salary)
AND EXISTS
(SELECT fname
FROM EMPLOYEE e3
WHERE e3.salary < employee.salary);

FNAME LNAME SALARY


-------- -------- ---------
JOHN SMITH 30000
FRANKLIN WONG 40000
JENNIFER WALLACE 43000
RAMESH NARAYAN 38000

The above query shows all employees names and salaries where there is at least one
person who makes more money (the first exists) and at least one person who makes
less money (second exists).

22
Subqueries with NOT EXISTS. NOT EXISTS will return TRUE if there are no rows
returned by the subquery.

SELECT fname, lname, salary


FROM employee
WHERE NOT EXISTS
(SELECT fname
FROM EMPLOYEE e2
WHERE e2.salary > employee.salary);

FNAME LNAME SALARY


-------- -------- ---------
JAMES BORG 55000

The above query shows all employees for whom there does not exist an employee who
is paid less. In other words, the highest paid employee.

The HAVING clause is similar to the WHERE clause. The difference is that WHERE is
used to filter individual rows while HAVING is used to filter groups according to the
GROUP BY clause.

Show the departments with average salary greater than 33000.

SELECT department.dname, AVG(salary)


FROM employee, department
WHERE employee.dno = department.dnumber
GROUP BY department.dname
HAVING AVG(salary) > 33000 ;

DNAME AVG(SALARY)
--------------- -----------
HEADQUARTERS 55000
RESEARCH 33250

Show departments with 3 or more employees:

SELECT department.dname, COUNT(employee.dno)


FROM department, employee
WHERE department.dnumber = employee.dno
GROUP BY department.dname
HAVING COUNT(employee.dno) >= 3;

DNAME COUNT(EMPLOYEE.DNO)
--------------- -------------------
ADMINISTRATION 3
RESEARCH 4

Change Values using UPDATE

The UPDATE command is used to change attribute values in the database.

UPDATE uses the SET clause to overwrite the value.

23
Change the last name of an Employee:

UPDATE employee
SET lname = 'SMITH'
WHERE lname = 'JONES';

Give an Employee a raise:

UPDATE employee
SET salary = salary * 1.05
WHERE fname = 'JOYCE' AND lname = 'ENGLISH' ;

Give all employees over the age of 50 a raise:

UPDATE EMPLOYEE
SET SALARY = SALARY * 1.02
WHERE TO_NUMBER( ( SYSDATE - bdate) / 365) >= 50;

PL NOTES

SQL> select to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS')


2 as "SYSDATE"
3 from dual;

SYSDATE
------------------------
Mon 27-Nov-2006 10:24:00

SQL> SET SERVEROUTPUT ON;

Program – 1 My First PL/SQL PROGRAM

SQL> BEGIN
2 dbms_output.put_line('Welcome to PL/SQL');
3 END;
4 /
Welcome to PL/SQL

PL/SQL procedure successfully completed.

Program - 2
SQL> begin
2 dbms_output.put_line('The next line is blank');
3 dbms_output.put_line('');
4 dbms_output.put_line('The above line should be blank');

24
5 end;
6 /
The next line is blank
The above line should be blank

SQL> CREATE TABLE PL1 (


2 ID VARCHAR2(20),
3 NAME VARCHAR2(20));

Table created.

SQL> INSERT INTO PL1


VALUES
('A1','MERT');

1 row created.

Program 3. to enter data in the table.

SQL> DECLARE
2
3 BEGIN
4
5
6 INSERT INTO PL1 VALUES('B3', 'AHMET');
7 INSERT INTO PL1 VALUES('B4', 'CAN');
8 INSERT INTO PL1 VALUES('B5', 'MUSTAFA');
9
10 END;
11 /

PL/SQL procedure successfully completed.

SQL> SELECT * FROM PL1;

ID NAME
-------------------- --------------------
A1 MERT
A2 AHMET
B1 ALI
B3 AHMET
B4 CAN
B5 MUSTAFA

6 rows selected.
This program will Display User Name:

Program 4

DECLARE
user_name VARCHAR2(8) := user;
BEGIN
dbms_output.put_line('Welcome to PL/SQL, ' || user_name || '!');

25
END;
/

Program 5

SQL> CREATE OR REPLACE PROCEDURE welcome


2 IS
3 user_name VARCHAR2(8) := user;
4 BEGIN -- `BEGIN' ex
5 dbms_output.put_line('Welcome to PL/SQL, ' || user_name || '!');
6 END;
7 /

Procedure created.

SQL> EXEC WELCOME;


Welcome to PL/SQL, REHAN!

PL/SQL procedure successfully completed.

Program 6
SQL> DECLARE
2 x NUMBER;
3 BEGIN
4 x := 72600;
5 dbms_output.put_line('The variable X = ');
6 dbms_output.put_line(x);
7 END;
8 /
The variable X =
72600

Program 7 ADDING two Numbers

SQL> DECLARE
2 x NUMBER;
3 y NUMBER;
4 z number;
5
6 BEGIN
7 x := 72600;
8 y := 5000;
9 z := x+y;
10 dbms_output.put_line('The sum of x +y = ');
11 dbms_output.put_line(z);
12 END;
13 /

26
OUTPUT
The sum of x +y =
77600

PL/SQL procedure successfully completed.

Program 8 - with stored Procedure


SQL> CREATE OR REPLACE PROCEDURE ADD_NUM
2 IS
3 x NUMBER;
4 y NUMBER;
5 z number;
6
7 BEGIN
8 x := 72600;
9 y := 5000;
10 z := x+y;
11 dbms_output.put_line('The sum of x +y = ');
12 dbms_output.put_line(z);
13 END;
14 /

Procedure created.

SQL> EXEC ADD_NUM;


The sum of x +y =
77600

27