You are on page 1of 32

Introduction to

SQL Lecture 1

What is Database?
Database: This is the data structure used to store organized information. A database is
Topically mad up of many liked tables of rows and columns.
Database: organize form of data in specific order is called database
Database: database is a shared collection of logically related data that is stored to meet
the requirements of different users of an organization.
Database is a shared collection of logically related data designed to meet the information
needs of an organization
What is DBMS?
STANDS FOR Database Management SystemA DBMS is a database program.
Or its a software system that user a standard method of cataloging, retrieving, running
queries on data
The DBMS manages incoming data organizes it and provides ways for the data to be
modified or extracted by users or other programs.
Some examples include MYSQL, postures, Microsoft Access, SQL Server,
File Maker, Oracle, DBASE, Clipper and FoxPro since there are so many database
management systems available, it is important for there to be a way for them to
communicate with each other
What is RDBMS?
Short for relational database management system and pronounced as separate letters,
A type of database management system (DBMS) that stores data in the form of related
tables. Relational Databases are powerful because they require few assumptions about
how data is related or how it will be extracted from the database as result, the same
database can be viewed in many different ways.
Finally

Relational Database Management System. Is the type of DBMS in which the


database is organized and accessed according the relationships between data
values the RDBMS was invented by a team lead by Dr. Edmund F. Codd and
funded by IBM in the early 1970s Examples Of RDBMS systems: Oracle, SQL
Server, DB2, Sybase, etc
Relational Database management system. A database management system
which ability to access data organized in tabular files that can be related to each
other by a common field (item). An RDBMS has the capability to recombine the
data items from different files
Relational database management system: in which data can be viewed and
manipulated in tabular form. Data can be stored in any order and tables of
information are easily related or joined to each other.
Relational database management system: a database management system that
allows data arranged in a tabular form to be related to data in other tables via
common fields. For example, an RDBMS for company personnel might include a

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 1

table of salaries and another of telephone number , the two tables could be related
to each other by sharing an ID field that contained a ID number for each
employee of the company .
A relational database management system (RDBMS) is a database management
system (DBMS) that is based on the relational model as introduced by Edgar F.
Codd.

What is SQL?
SQL (pronounced ess-que-el) stands for structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards
Institute), it is the standard language for relational database management systems.
SQL Statements are used to perform tasks such as update data on a database, or
retrieve data from a database. Some common relational database management
systems that use SQL are: Oracle, Sybase, Microsoft Access, SQL server, ingress, etc.
Al though most database systems use SQL, most of them also has their own
additional proprietary extensions that are usually only used on their system. However,
that standard SQL commands such as Select, Update, delete, Create and
Drop can be used to accomplish almost everything that one needs to do with a
database.

Further category of SQL


(1) DML (data manipulation language)
a) Insert
b) Delete
c) Update

(2)DDL (data Definition Language)


a) Create
b) Drop
c) Alter

(3)DCL (data control language)


a) Grant
b) Revoke

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 1

(4)TC (Transaction Control)


a) Commit,
b) roll back,
c) save point

(5)DRL (data retrieval language)


a) Select

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 2

DRL (Data Retrieval Language)+ Some Things Others


The SQL data retrieval statement is a statement which can retrieve the data from
a database
This statement is start with SELECT keyword
1-SQL> Cle scr
2-SQL> Clear screen
3-SQL> Show user
4-SQL> Select * from cat;
5-SQL> Desc dept
6-SQL> Desc emp
7-SQL> Select * from emp;
8-SQL> Set pagesize 25
9-SQL> Set pagesize 300
10-SQL> Select empno,ename,job from emp;
11-SQL> Select ename,empno,job from emp;
12-SQL> Select 1,2 from emp;
13-SQL> Select empno,ename as name from emp;
14-SQL> Select empno,ename as std Name from emp;
15-SQL> Select empno,ename as Name from emp;
16-SQL> Select empno,Mr||ename as ename from emp;
17-SQL> Select empno,Mr||ename as ename , sal,sal*10/100 as per10 from
emp;
18-SQL> Select empno,ename,sal as basic , sal*45/100 as Hrent, sal*10/100
as MidAll, sal*5/100 as tax, (sal+(sal*45/100)+(sal*10/100))-sal*5/100 as
Net Salary from emp;
19-SQL> Select empno,ename,sal as basic , sal*45/100 as Hrent, sal*10/100
as MidAll, sal*5/100 as tax,sal+hrent+MidAll-tax as Net Salary from emp;
20-SQL> Select * from emp order by ename;
21-SQL> Select * from emp order by sal desc;
22-SQL> Select * from emp order by sal desc, ename asc;
23-SQL> Select * from emp order by 6 desc, 1 asc;
24-SQL> Select empno,ename,sal,sal+sal*10/100 as net from emp order by
net;
25-SQL> Select empno,ename,sal,sal+sal*10/100 as net from emp orde by
5;
26-SQL> Select * from emp where sal>2000;
27-SQL> Select * from emp where sal>=2000;
28-SQL> Select * from emp where sal>=2000 order by sal desc;
29-SQL> Select empno,ename,sa,sal+sal*10/100 as net from emp where
net>=2000 order by sal desc;
30-SQL> Select * from emp where job=MANAGER;
31-SQL> Select * from emp where job=manager;
32-SQL> Select * from emp where hiredate<10-jan-1990;
33-SQL> Select * from emp where hiredate<10-jan-1992;
Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 2

34-SQL> Select * from emp where sal>2000 and job=MANAGER;


35-SQL> Select * from emp where sal2000 and job=MANAGER or
deptno=10;
36-SQL> Select * from emp where 1=2;
37-SQL> Select * from emp where 1=1;
38-SQL> Select * from emp where 1=1 and sal>2000;
39-SQL> Select * from emp where sal>2000 and sal<5000
40-SQL> Select * from emp where job<>MANAGER;
41-SQL> Select * from emp where NOT JOB=MANAGER;
42-SQL> Select * from emp where comm=;
43-SQL> Select * from emp where comm= ;
44-SQL> Select * from emp whee comm Is not null;
45-SQL> Select * from emp where hiredate between 01-jan-1900 and 01desc-1980
46-SQL> Select * from emp where ename between A AND S;
47-SQL> Select * from emp where ename like A;
48-SQL> Select * from emp where ename like A%;
49-SQL> Select * from emp where ename like %A%
50-SQL> Select * from emp where ename like %AA%;
51-SQL> Select * from emp whee ename like %A%A%;
52-SQL> Select deptno from emp;
53-SQL> Select * from emp where ename like %\_% escape \ from emp
54-SQL> Select DISTINCT DEPTNO FROM
55-SQL> Select DISTINCT DEPTNO,JOB FROM EMP
56-SQL> Select DISTINCT ENAME,DEPTNO,JOB FROM EMP
57-SQL> SELECT ENAME FROM EMP
58-SQL> SELECT distinct ename from emp
59-SQL> SELECT ename from emp GROUP BY ENAME
60-SQL> SELECT JOB FROM EMP GROUP BY JOB
61-SQL> Select DEPTNO from emp GROUP BY DEPTNO
62-SQL> Select deptno, job from emp group by deptno;
63-SQL> Select deptno,job from emp group by job,deptno;
64-SQL> Select deptno,job from emp where deptno=10 group by job,deptno;
65-SQL> Select deptno,job from emp deptno=10 group by job,deptno order
by job;
66-SQL> Select deptno,job from emp where deptn=10 group by deptno,job
order by job desc;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 2

Some extra metrials which are used in sql and pl/sql language
Operaters
Relational Operator
<,>,<=,>=,<>,=
Logical operators
AND, OR AND NOT
Arithmetic operator
+ ,-,*,/
SQL operators;
Is, is not, like, not like, between , not between , in , not in , etc from oracle 10g
Clause

Class assignemtns:
Continue during lecture---------------------

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

FUNCTIONS
Functions are small programs that are used to perform specific task when called
by it name . there are two types of functions

1- user define function


2- Built-in functions
User Define Functions
Users defined functions are those functions that are developed by the user itself
and stored in the database, and call it when required. These types of function we
will define on PL/SQL.

Built-In Functions.
Built in functions are red made functions which are already stored in the
database and can be called when required. Built in functions are further divide
into two categories.

1- Single Row functions


2- Group/Aggregate function

Single Row functions are those functions that apply to an individual row, i.e.
its is effective on a row basis and apply to each row one by one. Single row
functions return a single result row for every row of required table or view.
These functions can appear in select list, WHERE CLAUSES, START WITH AND
CONNECT BY CLAUSES, and AND HAVING CLAUSES.

While the aggregate functions need a group of rows to be apply. The group of
rows means one ore more than one rows.
It means group functions are effective on a group.

Single Row Functions


Single row functions are further divide into the following subcategories.
1- Character Single Row Functions( Apply on The Character Data)
2- Numeric Single Row Functions (Apply on Numeric Value)
3- Date Single Row Functions ( Apply on Date Values)
Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

4- Conversion Single Row Functions ( Convert From one type to other Type)
5- Misc Functions
Character
Functions
Upper
Lower
Initcap
Soundex
Substr
Instr
Replace
Translate
Concate
Rtrim
Ltrim
Trim
Length

Numeric
Functions
Round
Trunc
Ceil
Floor
Sign
Abs
Exp
Ln
Log
Mod
Remainder
Power
Sqrt

Date
Functions
Next_Day
Last_Day
Months_Between
Add_months

Conversion
Functions
Chr
To_number
To_char
To_Date
Ascii

Misc
Functions
Nvl
Nanvl
Nvl2
Decode
Length
Lpad
Rpad
Sysdate
User
Uid

Upper,Lower and Initcap


Use for case conversation
Syntax: lower (string), upper (string), initial (string)
Select ename,upper(ename) ename from emp;
Select lower(ename) ename, upper(ename) ename , intitcap( ename) ename
from emp;
Select * from emp whee job=manager;
Select * from emp where lower(job)=manager;
Select
empno,initcap(Ename)
Ename,
job
from
emp
where
initcap(ename)=Manager;
Soundex
User for phonetic representation. It case insensitive
Syntax: soundex(string)
Select * from emp where ename=blakeee;
Select * from emp where soundex(ename)=blakee;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

Substr
Use to pick portion of string from specific string.
Syntax: substr(strin,start value, end value);
Note:= last one parameter is optional

Select ename,substr(Ename,1,1) from emp;


Select ename,substr(ename,1) from emp;
Select ename,substr(ename,3) from emp;
Select * from emp where substr(ename,1,1)=A;
Select * from emp where upper(substr(ename,1,1)=A;
Instr
Use to fine the position of a character in particular string.
Syntax: instr(strint,character to fine, start value, number of occurance);
Note: = last tow parameters are optional
Select ename,instr(ename,A,1,1) from emp;
Select ename,instr(ename,A,1,2) from emp;
Select ename,instr(ename.A;,3,1) from emp;
Select ename,instr(ename,A) from emp;
Select ename,instr(ename,A,2) from emp;

Replace
Use to find a portion of string in the string and replace with
other string replace occur as a whole string not character by
Character
Syntax: replace (string, characters to replace, characters to replace with);
Selet ename, replace(ename,AD,AP) as ename from emp;
Select ename, replace(ename,AD, ) as ename from emp;
Translate
Use to find a portion of string in the string and replace with
Other string, replace occurs character by character
Syntax: translate(string,characters to replace,characters to replace with);
Select ename,translate(ename.AD,AP) as ename from emp;
Select ename,translate(ename,AD, ) as ename from emp;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

Concat
Use to Concatenate more that two strings
Sysntax: concat(string1,string2);
Select ename,job,concat(ename,job) ename from emp;
Select ename,job,concat(concat(ename,-)-job)) as ename from emp;
Round
Use to round the fraction portion of numeric value.
Sysntax: round(numberic value, round value);
Note:= last one parameter is optional
Select round (10.456,1) from dual;
Select round (10.456,2) from dual;
Select round (10.456,0) from dual;
Select round (10.456) from dual;
Select round (10.456,-1) from dual;
Select round (10.456,-2) from dual;
Select round(15,594,-1) from dual;
Select round(12.594,-1) from dual;
Select empno,sal,sal*10.8967/100+sal as net from emp;
Some of the one type of point and some of the difrent point
So
Select empno,sal,round(sal*10.8967/100+sal,2) as net from emp;
Select empno,sal,round(sal*10.8796/100+sal,0) as net from emp;
Select round (sysdate,Month) from dual;
Select round (sysdate,year) from dual;
Trunc
Use to truncate the fraction portion of numeric value.
Syntax: trunc(numeric value, trunc value)
Note: = last one parameter is optional
Select trunc(10.456,1) from dual;
Select trunc(10.456,2) from dual;
Select trunc(10.456,0) from dual;
Select trunc(10.456) from dual;
Select trunc(10.456,-1) from dual;
Select trunc(10.456,-2) from dual;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

Select trunc(sysdate,Month) from dual;


Select trunc(sysdate,Year) from dual;
Ceil
Use to convert the numberic number that have fractional part
to higher value digit.
Syntax: ceil (numeric value);
Select ceil(10.456) from dual;
Select ceil(10.001) from dual;
Select ceil (-10.456) from dual;
Select ceil (10) from dual;
Floor
Use to convert the numeric number that have fractional part
to lower value digit.
Syntax: floor (numeric value);
Select floor (10.456) from dual;
Select floor (10.001) from dual;
Select floor (-10.456) from dual;
Select floor (10) from dual;
Sign
Use to return 0,1 and -1 according to the expression
Syntax: sign (expression);
Select sign (1300-1300) from dual;
Select sign (1300-1400) from dual;
Select sign (1300-1200) from dual;

LTrim, Rtrim,Trim
Trim the spaces characters, or remove the spaces
Syntax: Ltrim(string), Rtrim(string),Trim(string);
Select ename,ltrim(ename) from emp;
Select * from emp where ename=KING ;
Select * from emp where rtrim(ename)=KING;
Select * from emp where rtrim(ltrim(ename))=KING;
Select * from emp where trim(ename)=KING;
Length
Find the length of the string specified.
Syntax: length(string)
Select ename,length(ename) from emp;
Select ename,length(oracle) from dual;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

Mod
Find the reminder
Syntax: mod(dividend,devisor);
Select mod(10,2) mod(11,2),mod(2,5) from dual;
Select * from emp where mod(sal,2)=0;
Select empno,sal,decode(mod(sal,2),0,sal+1,sal)
From emp;
Select empno,sal,decode(mod(sal,2),1,sal+1,sal) from emp;
Remainder
Find the remainder
Syntax: remainder (Dividend, devisor);
Select remainder (10, 2), remainder (11, 2), remainder (2, 5) from dual;
Abs
Convert negative value to positive.
Syntax: abs (expression);
Select 4-5, ABs (1300-1400) from dual;
Select sysdate,sysdate+60,round((sysdat+60)-sysdate) days1,
Abs(round((sysdate+60))-sysdate)) absdays from dual;

Exp
Find the power equivalent value
Syntax: exp (expression);
Select exp (100) from dual;
Ln and log
Ln find the natural logarithm and log find the logarithm
Syntax: ln(expression),log(expression,expression);
Select ln(100),log(100,2) from dual;
Power
Find the power equivalent value
Syntax: power (expression,expression);
Select power (10, 2) from dual;
Sqrt
Find the square root value
Syntax: sqrt(expression)
Select sqrt(100) from dual;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

Date Function
Next_day
Find the next day fro the date specified.
Syntax: next_day(date,day);
Select next_Day(sysdate,Monday) from dual;
Last_Day
Find the last day of the month the date sepicifed.
Syntax : last_day(date);
Select last_day (sysdate) from dual;
Months_Between
Find the difference in months between to date.
Syntax : months_between(date-date);
Select months_between(sysdate,hiredate) from emp;
select months_between(sysdate,to_date(10-mar-1983)) from dual;
select months_between(sysdate,'01-jan-1982')/12 as age from dua;
select * from emp
where round(months_between(sysdate,hiredate)/12)>25;
select empno,ename,hir as montly,
round(months_between(sysdate,hiredate))*sal as grand_total from emp ;

add_months
add no of months in a date
syntax: add_months(date,no.of months);
select add_months(sysdate,2) from dual;
select add_months(hiredate,2) from dual;
select sysdate as today, last_day(add_months(sysdate,6)) as lastday from dual;
select round(months_between(sysdate,to_date(10-jul-1983))/12) yrs from dual;

assign ment find your age by day,year,and months

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

select
round(months_between(sysdate,to_date('10-jul-1983'))/12) yrs,
round(round(months_between(sysdate,to_date('10-jul-1983'))/12)/12)
as months
round(round(round(months_between(sysdate,to_date('10-jul1983'))/12)/12)/12) as day
from dual;

To_number
Chracters that represent number can be converted to
number value
Syntax: to_number(character value that representing number)
Select to_number(123),2+456,2+to_number(456) from dual;
To_date
Characters the represent date can be converted to date
value
Syntax: to_date(character value that representing date);
select ('02/22/2003','MM/DD/YY') from dual;
problem it menas oracle not stesfiy about the above formts
select to_date('02/22/2003','MM/DD/YY') from dual;
select to_char(10-jan-1983,day) from dual;
it have problem
select to_char(to_date('10-jul-1983'),'day') from dual;
To_Char
Convert date or numbers to characters
Syntax: to_char(number)
Syntax : to_char(date,format)
Select 123, to_char (123) from dual;
Select sal,to_char(sal) as salary from emp;
Select ename,to_char(hiredate,dd/mm/yy) from emp;
Select to_char(hiredate,month,ddth,yy) from emp;
Select to_char(to_Date(22-feb-2005),day) from dual;
Select empno,ename,hiredate,to_char(hiredate,DDth Month, YYYY) from emp;
Select sysdate,to_char(sysdate,dd/mm/yyyy), to_char(sysdate,hh:mi:ss pm)
from dual;
Select empno,ename,hiredate, to_char(hiredate,HH:mi:ss) from emp;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

Select to_char(sysdate,day) from dual;


Select to_char(sysdate+1,day) from dual;

Date formats
Day
Dd
Ddth
Dy
Day
D
Ddd

Month
mm
mon
Month
Rm

Year
Y
YY
YYY
YYYY
Year

Time Formats
Ss (seconds)
HH, hh12, am, pm
Select
sysdate,to_char(sysdate,ddth,month,yyyy),to_char(sysdate,hh:mi:ss,am) from
dual;
Select sysdate,sysdate+2,sysdate+2/24 from dual;
Select sysdate,to_Char(sysdate,d),to_char(sysdate,ddd),to_char(to_date(31dec-2007),ddd) from dual;
Select sysdate,to_char(sysdate,YYYY B.C) from dual;

Nvl
Substitute a value for null value.
Syntax: nvl(nul_value,alternate_value)
Select empno,sal,sal+comm. As net from emp;
Select empno,sal,sal+nvl(comm,0) as net from emp;
Select empno,sal,comm.,nvl(comm,0) as comm from emp;
Select empno,sal,comm.,nvl(to_char(comm.),-) as omm from emp;
Nvl2
Allow different action based on where value is null.
Syntax: to_date(character value that representind date)
Select empno,eame,hiredate,nvl2(hiredate,Hired,Not Yet Hired) from emp;
select ename,job,hiredate,comm,nvl2(comm,'yes','no') from emp;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 3

10

Decode
Determine action based upon value in a list
Syntax: decode (condition, action, condition, action, else action)
Syntax: decode (value, if1, then1, if2, then2, if3 else)
Select empno,ename,sal,deptno,decode(deptno,10,sal*10/100,20,sal*20/100) as
increment_employee from emp;
Select
empno,ename,sal,job,decode(upper(job),MANAGER,sal*12/100,ANALYST,
sal*10/100,sal*5/100) as increment_emp from emp;
Lpad and Rpad
Used to pad or file a character string to a fixed width
Syntax: Lpad(string, length ,padding value)
Rpad(string ,elength, padding value)
Select empno,ename,lpad(ename,30,*),rpad(ename,30,*),Lpdad(ename,30 )
from emp;
select rpad(ename,25,'-'),job from emp;
Sysdate,user and uid
Function that return signle value and need no pramentr ot
pass in
Syntax: sysdate,user,uid
Select sysdate,user,uid from dual;

Class Assignments:Continue during leacture..

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 4

Joining Tables
In relational database management system the relation are normalized and we
need to display data from multiple table. To display data from multiple tables you
need to mention the names of the entire table with column name in select
statement. E.g.
Select emp. empno, enmp. Ename, emp.deptno, dept.deptno, dept.dname
From EMP, dept;
Select empno,ename,emp.deptno,deptn.deptno,dname
From EMP, dept;
The above queries will generate a Cartesian product, because it simply joning
every row of one table with every row from another table.
We need to mentioned the proper join condition to avoid Cartesian product.

What is Cartesian products


simply join every row in the first table to every row in the second table
without regard for the defined relationship between tablesusually producing
a meaningless, I/O-intensive result.
Joining Types
1- inner join (Equi Join, Match the column using equal operator)
2- Outer join (Llike Equi join But also joining massing row like outer left join,
outer right joining and full joining)
3- Self join ( link same table with each other)
4- Cross join (Match the column without using equal operator)
Inner Join or Equi join Examples
Select empno, ename, emp.deptno,dept.deptno,dname
From EMP, dept
Where emp.deptno=dept.deptno;
Select empno, ename, emp.deptno, dept.deptno, dname
From EMP inner join dept using (deptno);
Select empno,ename,deptno,dname
From EMP inner join dept using (deptno);
Outer Join Examples (left outer join, right outer join)
Select empno,ename,emp.deptno,dept.deptno,dname
Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 4

From EMP, dept


Where emp.deptno=dept.deptno(+)
Select empno,ename,emp.deptno,dept.deptno,dname
From emp,dept
Where emp.deptno(+)=deptno.deptno;
Select empno,ename,deptno,dname
From EMP outer left join dept using (deptno);
Select empno,ename,deptno,dname
From EMP outer right joins deptno using (deptno);
select empno,ename,deptno,dname
from emp full join dept using(deptno);
Cross Join Examples
Select empno,ename,sal,grade
From emp,salgrade
Where sal>=losal and sal<hisal;
Select empno,ename,sal,grade
From emp,salgrade
Where sal between losal and hisal;
Select empno,ename,sal,job,dname,loc,grade
From emp,dept,salgrade
Where emp.deptno=dept.deptno
And sal between losal and hisal;
Self Join Examples
Select a.ename as client, b.ename as boos
From emp a , emp b
Where a.mgr=b.empno;
Select a.ename as client, b.ename as boos
From emp a, emp b
Where a.empno=b.mgr;

Class assignment:Continue during lecturers.

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 6

Group Functions
Functions need a group of rows to be applied. The group of rows means one ore
more than one rows.
It means group functions are effective on a group.
Following are the different group functions
Max, min, median, sum, avg, count, stddev
Select sum(sla) from emp;
Selectsum(sal),avg(sal),min(sal),max(sal),median(sal),
count(sal),count(*),count(comm)
From emp;
Select sum(sal), avg(sal) from emp
Group by deptno;
Select deptno,sum(sal),avg(sal) from emp;
Group by deptno;
Select * from emp
Having avg(sal)>2000;
Select deptno, avg(sal) from emp
Where avg(sal)>2000
Grop by deptno;
Select deptno,avg(sal) from emp
Having avg(sal)>2000
Group by deptno;
SUBQUERIES
Query with in query is called sub query. It is used to search for unknown
condition.
Select * from emp
Where deptno=(select deptno from emp where ename=BLAKE);
Select * from emp
Where deptno=(select deptno from emp);
Select * from emp
Where sal=(select max(sal) from emp);

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 6

Select * from emp


Where sal>(select avg(sal) from emp);
Select * from emp
Where hiredate<(select hiredate from emp where ename=BLAKE)
And job=CLERK;
Select * from emp
Where job in (select job from emp where ename=BLAKE or ename=SMITH);
Select * from emp
Where deptno=(select deptno from emp where ename=CLARK)
And job=(select job from emp where ename=SMITH);
select * from emp
where deptno=(select deptno from emp where ename=CLARK)
OR job=(select job from emp where ename=SMITH);
Select * from emp
Where (deptno,job)=(select deptno,job from emp where ename=CLARK);
Select * from emp
Where sal>any (select sal from emp where job=CLERK);
Select * from emp
Wehre sal>all(select sal from mep where job=CLERK);
Select * from emp
Where sal=(select max(sal) from emp);
Select * from emp
Where sal=(select max(sal) from emp where sal<>(select max(sal) from emp));

select distinct(a.sal) from emp a where 3>=(select count(distinct(sal)) from emp b


where a.sal<=b.sal)
order by sal desc
/

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 7

DML (Data Manipulation Language)


SQL modification statement makes changes to database data in tables and
columns
There are three modification statements.

INSERT statemtn add rows to tables


UPDATE statemtnmodify columns in table rows
DELETE statementremove rows from tables

INSERT statement
The INSERT Statemtn adds one ore more rows to a table.. it has two formats
INSERT INTO table-1[(columns list)] values (value- list);
And ,
INSERT INTO table-1[(columns list)] (query-specification)
INSERT INTO table-1 values[(values);

The first from insert a single row into table-1 and explicitly specifies the columns
values for the row. The second forms uses the result of query-specification insert
one or more rows into table-1. the result rows from the query are the rows added
to the insert table.
NOTE: the query connotes reference table-1.
Both forms have and o optional column list specification. Only the columns listed
will be assigned values. Unlisted columns are set to null, so unlisted columns
must allow nulls.
Specification rows (second forms) are assigned to the corresponding column in
column list in order. If the optional column list is missing, the default column list is
substituted. The default column list contains all columns in table-1 in the order
they were declared in
CREATE TABLE, OR CREATE VIEW.

Examples
Insert into EMP values (234,jamal,Analyst, 7782,12-jan-2007, 1200, 0, 10);
Insert into EMP values (234,jamal,Analyst, null, sysdate, 1200, null, 10);
Insert into EMP values (234,jamal,Analyst, null,sysdate, default, null, 10);
Insert into EMP values (234,jamal,Analyst, 7782,12-jan-2007, 1200, 0, 10)
Insert into EMP (empno, ename, job) values (234,ali,manager);
Insert into EMP (empno, ename, job) values (null,ali,manager);
Insert into emp select * from employee;
Insert into abc select * from abc;
Insert into emp select * from dept;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 7

Insert into employee (ename,job) select dname,loc from dept;


Insert into emp (ename,job,dname) select ename,job,dname from emp,dept
Where emp.deptno=dept.deptno;
Insert into employee (ename,job,dname,sal) select ename,job,dname,sal
From emp,dept,salgra
Where emp.deptno=dept.deptno
And sal between losal and hisal;
UPDATE Statement
The UPDATE statemtn modifies columns in selected table rows, it has the
following genral format:
UPDATE table-1 set set-list[where predicate]
The optional WHARE clause has the same format as in the SELECT Statement.
See WHERE CLAUSE. The WHARE clause chooses which table rows to update.
If it is missing, all rows are in table-1 are updated.
The SET clause expression and WHERE Clause predicate can contain sub
queries, but the sub queries cannot reference table-1. this prevents situation
where result are dependent on the order of processing.
Update emp set sal=2000;
Update emp set sal=sal+sal*1/100;
Update emp set sal=sal+sal*10/100 where job=MANAGER;
Update emp set comm=50 where comm Is null;
Update emp set comm=50,sal=sal+10/100 where comm is null;
Update emp set sal=(select hisal from salgrade where grade=4);
Update emp set sal=(select hisal from salgrade where grade=6);
Update emp set sal=(select hisal from salgrade where grade=6)
Where job=MANAGER;
Update emp set ename=initcap(ename);
Update emp set ename=rtrim(ename);

DELETE Statement
THE DELETE statement rovmes selected rows from a table. It has the follwing
general format:
DELETE from table-1[where predicate]

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 7

The optional WHERE clause has the same format as in the SELECT Statement.
See WHERE Clause. The WHERE clause chooses which table rows to delete. If
it is missing, all rows are in table-1 are removed.
The WHERE Clause predicate can contain sub queries, but each sub queries
cannot reference table-1. this prevents situations where result are dependent on
the order of processing.
Delete from emp;
Delete from emp where deptno=10;
Delete from emp where job=CLERK;
Delete from emp
Where sal= (select hisal from salgrade where grad=4);
Delete FROM EMP
WHERE SAL IN (SELECT SAL FROM EMP WHERE JOB='ANALYST');
Delete from emp where sal>(select max(sal)
From emp where sal<(select max(sal) from emp
where sal<(select max(sal) from emp)));

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

DDL (Data Definition Language)


The SQL creation Statements permanently create objects in database and all
these statement start with word create like create table, create view,
Alter , drop,
Alter Command:
ALTER command is used when we want to making changes in the structure of
the table and e.g. to add column, to add constraint, to drop constraint, to enable
constraint, to disable constraint, to rename column, to drop column.
Note: the alter table command is applying after creation the table.
Drop Command:
Drop command is used whenever we want to drop a table, drop view, drop
sequence, drop index etc.
When we ant to make the changes in the structure of a table we must used the
alter + drop

Create Table
CREATE TABLE will create a new, initially empty table in the current database.
The table will be owned by the user issuing the command.
If as scheam name is given( for example, CREATE TABLE myschema.mytable
)
Then the table is crate in the specified schema. Otherwise it is created in the
current schema.
Temporary tables exist in a special schema, so a schema name may not be
given when creating a temporary table. The name of the table must be distinct
from the name of any other table, sequence, index, or view in the same schema.
CREATE TABLE also automatically creates a data type that represents the
composite type corresponding to one row of the table. Therefore, tables cannot
have the same name as nay existing data type in the same schema.
The optional constraint clauses specify constraints (texts) that new of updated
rows must satisfy fro an insert or update operation to succeed. A constraint is an
SQL object that helps define the set of valid values in the table in various ways.
Examples
Create table department
(
Deptno number (2),

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Dname varchar2 (10),


Location varchar2 (10)
);

Create table employee


(
Empno number(5),
Name varchar2(10),
Job varchar2(10),
Mgr number (4),
Hiredate date,
Salary number(7,2),
Comm. Number(4),
Deptno number(2)
);
WHAT IS CONSTRAINTS:
Constraints mean restriction to restrict the two tables or restrict the column in a
table.
A constraint clause can constrain a single column or group columns in a table.
The point of these constraints is to get oracle to do most of the work in
maintaining the integrity of your database.
There are tow ways to specify constraints: as part of the column definition (
A column constraint) or at the end of the create table statement (a table
constraint)
If we need to constraint several columns then we should must be used the table
constraints.
Types of Constraints:
The following are different types of constraint
Primary key, foreign key, not null, unique key, check, candidate key
The candidate key
A candidate key is a combination of one for more columns, the values of which
uniquely identify each row of a table.
Create table abc
(
City varchar2 (12) not null,
Date1
date not null,

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Add
varchar2 (10),
Constraint abc_uq unique (city, date1)
);
The key of this table is the combination of city and date1.
The primary key
The primary key is a key which uniquely identity the single row of a table
The primary key is a kay which has the following characteristic
Foreign key
Unique
Not null
Index
Relation ship facilities

Create table deparment


(
Deptno number(10) primary key,
Dname varchar2(10),
Location varchar2(20)
);
Create table employee
(
Empno number(4) primary key,
Name varchar2(10) not null,
Job varchar2(10),
Mgr number(4) references employee(empno),
Hiredate date,
Salary number(7,2) check (salary beween 0 and 15000),
Comm. Number(4),
Deptno number(2) references department(deptno
);
How to show the constraint
Select constraint_name, constraint_type from user_constraints
Where table_name='DEPTARTMENT'
Create table deparment
(
Deptno number(5) constraint deptn_pk primary key,
Dname varchar2(10) constraint nn_dname not null,
Location varchar2(20)

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

);
Create table employee
(
Empno number(4) constraint empno_pk primary key,
Ename varchar2(10) constraint nn_name not null,
Job varchar2(10).
Mgr number(4) constraint mgr_sk references employee(empno),
Hiredate date,
Salary number(7,2) constraint salary_chk check(salary between 0 and 15000),
Comm Number(4),
Deptno number(5) constraint deptno_fk references department(deptno)
);
Table Level constraints
Defining constraints at table level in the following examples
Create table deparemnt
(
Deptno number(4),
Dname varchar2(10) constraint nn_dname not null,
Location varchar2(10),
Constraint deptno_pk primary key(deptno)
);

Create table employee


(
Empno number(4),
Name varchar2(10) constraint nn_dname not null,
Job number(4),
Mgr number(4),
Hiredate number(7,2),
Comm number(5),
Deptno number(4),
Constraint empno_pk primary key(empno),
Constraint mgr_sk foreign key(mgr) references employee(empno),
Constraint deptno_fk foreign key (deptno) references department (deptno)
);

Alteration After Createing the Table


To add the constraint after creation a table and also add a new column to a table
Alter table employee

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Add(
Addresss varchar2(20)
);
Alter table employee
Add(
Address varchar2(20),
Phone varchar2(0)
);
alter table employee
add(
address varchar2(20) constraint add_nn not null
);
Alter table employee
Add constraint job_nn not null (job);
Alter table employee
Add constraint empno_pk primary key (deptno)
alter table student_information add
CONSTRAINT fk_province_id FOREIGN KEY(province_id) REFERENCES
province(province_id)
/
/

Modify size or Data Type


It means to increase and decrees the size of a table column after the creation the
table or also converts the data type of a table column.
Alter table emp1
Modify (
EName varchar2 (30)
);
Alter table employee
Modify
(
Comm varchar2 (10)
);

Renaming Column

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Alter table employee


Rename column job to Empoyee_job;

Dropping Column or Constraints


Alter table employee
Drop column job;
Select constraint_name, constraint_type from user_constraints
Where table_name='employee'
Alter table employee
Drop constraint empno_pk
Alter table employee
Drop constraint salary_chk;

Disabling and Enabling Constraints


Alter table emplolyee
Disable constraint pk_empno;
Alter table employee
Enable constraint pk_empno;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Views
View is a logical table based on one or more tables or views.
A view contains no data itself. The tables upon which a view is based are called
base tables.
Purpose of view
1- For security purpose
2- To ease the complex queries.
Types of View
1- Simple View (From single Table DML allowed)
2- Complex View (having group function or joins, DML not allowed)
Altering View
No alter command for view, but drop and recreate the view or use create or
replace command.
Examples
Create or replace view view1 as select * from emp;
Create or replace view view1 as select empno,ename,job from emp;
Create or replace view view1 (empno, name, Category) as select empno, ename,
job from EMP;
Create or replace view view1 as select * from emp where deptno=10;
Create or replace view view3 as select * from emp where deptno=10 with check
option;

Create or replace view view4 as select * from emp where deptno=10 with read
only;
Create or replace view view1 as select deptno,sum(sal) total from emp group by
deptno;
Create or replace view view1 as select emp.* dname,loc,grade from emp, dept,
salgrade
Where emp.deptno=dept.deptno
And sale between losal and hisal;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Create or replace view view1 as select dname,null,grade ,sum(sal) total from


emp,dept
where emp.deptno=dept.deptno
Union
Select null,grade,sum(sal) total from emp , salgrade where emp.sal between
losal and hisal;

Indexes
Indexes help us retrieve data from tables quicker. And index is a schema object that
contains any entry fro each value that appears in the indexed columns(s) of the table or
cluster and provides direct, fast access to rows.
Oracle database support several type of index.

create unique index uq on detail(empno)

CREATE INDEX BTREE_INDX ON EMP(SAL)

CREATE Bitmap INDEX Bitmap_idx ON Gender(sex)

Replding an index

It means to assign the another tablepsace and also specifiy the size for using .
alter index abc_index
rebuild
storage (initial 8m next 4m pctincrease 0)
tablespace users
/

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

Introduction to

SQL Lecture 9

Partitioned a table
You can divide the rows of a single table into multiple parts. Dividing a tales data
in the manner is called partitioning the table, the table that is partitioned is called
partitioned table, and the parts are called partitioned

Create table student(id numer,name varchar2(20)


)
partition by range(name)
(partition part1 values less than(B)
talespace part1_ts,
partition part2 values less than(maxvalue)
tablespace part2_ts)
;

Prepared by Eng: Zamary Shahab

zamary_shahab2007@yahoo.com mob: 0798981007

You might also like