You are on page 1of 50

STRUCTURED QUERY LANGUAGE (SQL)

Sql is used to make a request to retrieve data from a database


The DBMS process the SQL request, retrieve the requested data from the database and
return it.
This process of requesting data from a data base and receiving back the results is called a
data base query and hence the name structured query language
SQL is a language that are commercial RDBMS implementations understand SQL is a
non-procedural language.
We would be discussing SQL with respect to oracle syntax
1. In 1997 Oracle Corporation introduce the first commercial RDBMS.
2.1982 ANSI (American national standard institute) forms SQL standard committee.
3.1983 IBM (International Business Machine) announces DB2.
4.1986 ANSI SQLI standard is approved.
5.1987 ISO (International Standard Organization) SQL standards are approved.
6.1992 ANSI, SQL2 standard is approved.
7.2000 Microsoft corporation introduce SQL server 2000 aimed at enterprise application.
8.2004 SQL 2003 standard is published.
9. SQL is not a case sensitive language
Components of SQL:Oracle SQL compiles with industry accepted standards the SQL contains 5 sub
languages.
1. Data definition language (DDL)
2. Data manipulation language (DML)
3. Data control language (DCL)
4. Transaction control language (TCL)
5. Data query language (DQL)
Data definition language (DDL):The language is used to define the data base is called Data definition language
(DDL).
Data definition language is used to create the data base, after the data base delete the data
base. The DDL is used by the concept schema to store or retrieve the records to
From the data base respectively where these records describe everything i.e.,
entities, attributes and relationships.
Data Definition language (DDL) Commands:
Create
Alter
Drop
Truncate
Rename

1.Create:
Create command is used for creating relation in data base.
Naming rules for creating relation:
1.Table names and column names must being with character.
2.The length could be 1-30 characters long
3.must not duplicate the name of another object owned by the sum user
4.must not be oracle server reserved Keyword
Syntax:Create table<table-name><coloum1><data
Type(size),<coloum2><data type(size)>,------------<column n<data type (size)>);
The character i is the terminator for SQL statement
2. Alter :
Alter command is used to
1. Add a new column
2. Modify an existing column
3. Drop column
4. Add integrity constraints
5. Drop integrity constraints
1. Add a column:Alter table<table -name> add (col1 data type (size),col_2data type(size).Column
data type(size));
2. Modify a column:- column modification is of 2 types
a).data type modification
b).size modification
a).data type modification:Syntax:Alter table <table name> modify (column new Data type (size),.column new
data type(size));
a).size modification:Syntax:alter table<table name> modify(column data type(new size),..column new data
type(new size));
3. Drop a column:Syntax:Alter table<table name>Drop (column name);
(or)
Syntax:Alter table<table name>Drop column name;

4. Add integrities constrain:Syntax:Alter table <table name> ADD (column name <constrain name>);
5. Dropping integrity constraint:Syntax:Alter table <table name> drop constraint constraint_name
3.DROP:it drops the entire table
Syntax:Drop table <table name>
4.TRUNCATE:
Sometimes we wish to delete all rows and attributes of all the data in a table. One way of
doing this is with DROP TABLE. But what if we wish to simply delete the data but not
the table itself? For this, we can use the TRUNCATE TABLE command.
The syntax for TRUNCATE TABLE is
TRUNCATE TABLE <TABLE NAME>
Note: that the TRUNCATE TABLE command cannot delete any rows of data that would
violate FOREIGN KEY or other constraints.
5.RENAME:Sometimes we want to change the name of a column. To do this in SQL, we specify that
we want to change the structure of the table using the ALTER TABLE command,
followed by a command that tells the relational database that we want to rename the
column. The exact syntax for each database is as follows:
syntax for ALTER TABLE Rename Column is,
ALTER TABLE <table_name> RENAME COLUMN <column 1> TO <column 2>;
2.DML command
Data Manipulation Language (DML) statements are used for managing data in database.
DML commands are not auto-committed. It means changes made by DML command are
not permanent to database, it can be rolled back.
1.select
2.insert
3.update
4.delete

1.select:- retrieve data from the a database


Syntax:Select * from <table name> (or)
Select (column1,column2,column_n) from <table name>
2. Insert:-A row is inserted into a table by using insert command.
Syntax:Insert into <table name>values(list of values)
3.update:Its is used for modifying the existing row.
Syntax:Update table name set column name1=new value----column name=new value
Where(condition)
4.delete:1.used for reaming rows in table.
Syntax:Delete from table name(condition).
3.TCL COMMANDS:Transaction Control Language(TCL) commands are used to manage transactions in
database.These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.
Commit command:
Commit command is used to permanently save any transaaction into database.
Following is Commit command's syntax
commit;
Rollback command:
This command restores the database to last commited state. It is also use with savepoint
command to jump to a savepoint in a transaction.
Following is Rollback command's syntax
rollback to savepoint-name;

Savepoint command:
savepoint command is used to temporarily save a transaction so that you can rollback to
that point whenever necessary.
Following is savepoint command's syntax
savepoint savepoint-name;
4.DCL command
Data Control Language(DCL) is used to control privilege in Database. To perform any
operation in the database, such as for creating tables, sequences or views we need
privileges. Privileges are of two types,
System : creating session, table etc are all types of system privilege.
Object : any command or query to work on tables comes under object privilege.
DCL defines two commands,
Grant : Gives user access privileges to database.
Revoke : Take back permissions from user.
To Allow a User to create Session
grant create session to username;
To Allow a User to create Table
grant create table to username;
To provide User with some Space on Tablespace to store Table
alter user username quota unlimited on system;
To Grant all privilege to a User
grant sysdba to username
To Grant permission to Create any Table
grant create any table to username
To Grant permission to Drop any Table
grant drop any table to username
To take back Permissions
revoke create table from username

CREATING RECORDS
1)create a customer a relation with following attributes
name
Cus-id
Cus-name
Cus-accountno
Account type
Bank-branch
Cus-emailid

Type
Number
Character
Number
Character
Character
Character

Syntax:
create atable a customer(cusid number(10),cusname varchar2(10),cusaccountno
Number(10),accounttype varchar2(10),bankbarnch varchar2(10),cusemail varchar2(10));
Table created;
Sql>desc customer;
NAME
Cus-id
Cus-name
Cus-accountno
Account type
Bank-branch
Cus-emailid

NOT NULL?

DATATYPE
Number
Character
Number
Character
Character
Character

2)create a STUDENT relation witch following attribute


NAME
Sid
Sname
Dob
Sub1
Sub2
Sub3
Total
grade

ATTRIBUTE
Number
Character
Date
Number
Number
Number
Number
Character

Syntax: create atable a student(sid number(10),sname varchar2(10),dob date, sub1

Number(2),sub2 number(2),sub3 number(2),total number(3),grade varchar2(2));


Table created
Sql>desc student
NAME
Sid
Sname
Dob
Sub1
Sub2
Sub3
Total
grade

NOTNULL

DATATYPE
Number
Character
Date
Number
Number
Number
Number
Character

3)Create a EMPLOYEE a relation with following attributes


NAME
Eno
Ename
Salary
Dob
Doj
Dept no

ATTRIBUTE
Number
Character
Number
Date
Date
Number

Syntax:-create atable employee(eno number(10),ename varcher2(10),dob data,doj


Data,deptno number(10);
Table created
Sql>desc employee
NAME
NULL
Eno
Ename
Salary
Dob
Doj
Dept no

DATATYPE
Number
Character
number
date
date
number

4)create a DEPARTMENT a relation with following

NAME
Dno
Dname
location

ATTRIBUTE
Number
Character
Character

Syntax:-Create table department(dno number(10),dname varchar2(10),location


Varchar2(10));
Table created
Sql>desc deparment
NAME
Dno
Dname
location

NULL

DATATYPE
Number
Character
Character

5) create a SAILORS relation with following attributes


NAME
ATTRIBUTE
Side
Number
Sname
Character
age
Date
rating
Character

Syntax:-create table sailors(sid number(10),sname varchar2(10),age date,rating


Number(10));
Table created
Sql>desc sailors
NAME
Sid
Sname
age
rating

NULL

DATATYPE
Number
Character
Date
Character

6) create a BOATS relation with following attributes

NAME
Bid
Bname
Color

ATTRIBUTE
Number
Character
Character

Syntax:-create table boats(bid number(10),bname varchar2(10),color varchar2(10));


Table created
Sql>desc boats
NAME
Bid
Bname
Color

NULL

ATTRIBUTE
Number
Character
Character

7) create a RESERVES relation with following attributes


NAME
ATTRIBUTE
Sid
Number
Bid
Number
day
date

Syntax:-create table reserves (sid number(10),bid number(10),day date);


Table created
Sql>desc reserves
NAME
Sid
Bid
day

NULL

I). insert 5 records into customer table

DATATYPE
Number
Number
date

1. insert into customer (cusid,cusname,accno,acctype,bankbranch,cusemail)


Values (111,rani,2345,savings,npeta,sai@gmail.com);
2 insert into customer(cusid,cusname,accno,acctype,bankbranch,cusemail)
Values (112,priya,2346,saving,sklm,srija@gmail.com);
3. insert into customer (cusid,cusname,accno,acctype,bankbranch,cusemail)
Values (113,lahari,2347,saving,vzmram@gmail.com);
4. insert into customer (cusid,cusname,accno,acctype,bankbranch,cusemail)
Values (114,lalita,2348,savingvizag,rama@gmail.com);
5. insert into customer(cusid , cusname,accno,acctype,bankbranch,cusemail)
Values (115,madhu,2349,saving,hyd,ramu@gmail.com);
II). add new column phno to customer table
Alter table customer add phno number (10);
III). update the phno of the customer table
Update customer set phno=2345680000 where cusid=112;
IV). add unique constraint to cusid in a customer relation
Alter table customer add notnull (cusid)
V). remove customer from customer table whose name is madhu
Delete from customer where cusid=155;
I). insert 5 records into student table
1. insert into student (sid,sname,dob,sub1,sub2,sub3,total)
Values (20,srinu, 20-5-1993,70,80,60,210);
2. insert into student (sid,sname,dob,sub1,sub2,sub3,total)
Values (22,sravani, 14-4-1993, 80 ,90,70,240);
3. insert into student (sid,sname,dob,sub1,sub2,sub3,total)
Values (23, vani, 18-6-1993, 40, 60,80,180);
4. insert into student (sid,sname,dob,sub1,sub2,sub3,total)
Values (24,puja, 26-7-1993, 40, 50, 60, 150);
5. insert into student (sid,sname,dob,sub1,sub2,sub3,total)
Values (25,srivalli25-6-1993, 80, 60, 50 d,190);
II). define not null and unique constraint on student relation
Alter table student add not null s-id
Alter table student add unique s-name
III). calculate the total of marks and update the student table
Update student set total= (sub1+sub2+sub3) where sid=22;

IV). remove unique constraint from student relation


Alter table student drop unique s-name
Aggregate functions
Aggregate functions are function that take collection of rules as input a and return a
single value
SQL offers 5 built aggregate functions.
E.no
10
11
12
13
14

E.name
Samuel
Mohan
Tarak
Vasu
Bhaskar

Salary
20000
15000
10000
7000
8000

Date of birth
21/01/1991
20/03/1991
23/03/1991
30/03/1991
14/07/1991

Date of joing
12/06/2010
12/06/2010
12/06/2010
12/06/2010
12/06/2010

Dept no
32
12
03
20
28

Average:avg(column)
Minimum: min(column)
Total :sum(column)
Count:count(column)
Avg(column):- calculates the average of the column name special
Ex:-select avg(salary) from emp;
Max(column):- Gives maximum value of a particular column
Ex:- select max(age) from emp;
Min(column):- Gives maximum value of a particular column
Ex:- select min(age) from emp;
Sum(column) Gives maximum value of a particular column
Ex:- select sum(marks) from student;
Display the total marks of student table.
Count(column):-displays total number of column values for the column specified
In the column name format. Discards null values for that column

Ex:- select count(emp.no) from student;


Key constraints
Primary key:
SQL>create table cust
2(
3 accno number(5) primary key,
4 custno number(5),
5 Custname varchar(10)
6 );
Table created.
SQL>create table account
2(
3 accno number(5),
4 branch varchar(15),
5 balance number(5),
6 foreign key(accno)references cust
7 );
Table created.
SQL>desc cust;
Name
null
Accno
notnull
Custno
Custname

type
number(5)
number(5)
varchar(10)

SQL>insert into cust values(&accno,&custno,custname);


enter value for accno:110
enter value for ccustno:1210
enter value for custname:smith
old 1:insert cust values(&accno,&custno,&custname)
new 1:insert cust values (110,1210,smith)
1 row created.
SQL>/
Enter values for accno:111

Enter value for custno:1202


Enter value for custname:joseph
Old 1:insert into cust values(&accno,&custno,&custname)
New 1:insert cust values(111,1202,joseph)
1 row created.
SQL>select *from cust;
ACCNO
110
111
11
115
123

CUSTNO
1201
1202
1204
1227
1228

CUSTNAME
smith
joseph
lenin
stalin
ragu

SQL>desc account27;
NAME
ACCNO
BRANCH
BALANCE

NULL

TYPE
NUMBER(5)
VARCHAR2(10)
NUMBER(5)

SQL>insert into account27 values (&accno, &branch,&balance);


Enter value for accno:110
Enter value for branch:hyd
Enter value balance:2000
Old 1:insert into account27 values(&accno,&branch,&balance)
New 1:insert into account27 values(110,hyd,2000)
1 row created.
SQL>/
Enter value for accno:11
Enter value branch:vskp
Enter value for balance:3999
Old 1:insert into account27 values (&accno,&barnch,&balance)
New 1:insert into account27 values(11,vskp,3999)
1 row created.
SQL>/
Enter value for accno:123

Enter value branch:nrpm


Enter value for balance:4555
Old 1:insert into account27 values (&accno,&barnch,&balance)
New 1:insert into account27 values(123,nrpm,4555)
1 row created.
SQL>/
Enter value for accno:115
Enter value branch:vskp
Enter value for balance:4555
Old 1:insert into account27 values (&accno,&barnch,&balance)
New 1:insert into account27 values(115,vskp,4555)
. 1 row created
SQL>/select*from account27;
ACCNO
110
11
123
115

BRANCH
HYD
VSKP
NRPM
VSKP

BALANCE
2000
3999
4555
4555

SQL>/insert account27 values (124,bang,3333)


Insert account27 values(124,bang,3333)
ERROR at line1:
ORA_02291: integrity constraint (SCOTT.SYS_C001390)violated-parent key not found
SQL>/delete from cust where accno=110;
Delete from cust where accno=110
ERROR at line1:
ORA_02292: integrity constraint (SCOTT.SYS_C001390)violated-parent key not found
FOREIGN KEY
SQL>drop table account27;
Table dropped.

SQL>create table account28


2(
3 accno number(5),
4 branch varchar(15),
5 balance number(5),
6 foreign key(accno)references cust on delete cascade
7 );
Table created.
SQL>desc account28;
Name
null
Accno
branch
balance

type
number(5)
varchar2(10)
number(5)

SQL>insert into account28 values(&accno,&branch,balence);


enter value for accno:110
enter value for branch:vskp
enter value for balance:3000
old 1:insert into account28 values(&accno,&branch&balance)
new 1:insert cust values (110,vskp,3000)
1 row created.
SQL>
enter value for accno:11
enter value for branch:hyd
enter value for balance:4000
old 1:insert into account28 values(&accno,&branch&balance)
new 1:insert cust values (110,hyd,4000)
1 row created.
SQL>
enter value for accno:115
enter value for branch:bang
enter value for balance:3999
old 1:insert into account28 values(&accno,&branch&balance)
new 1:insert cust values (115,bang,3999)

1 row created.
SQL>select*fromaccount28;
ACCNO
BRANCH
110
vsp
11
hyd
115
bang

BALANCE
3000
4000
3999

SQL>delete from cust where accno=110;


1 row deleted.
SQL> select*from account28;
ACCNO
11
115

BRANCH
hyd
bang

BALANCE
4000
3999

VIEWS
SQL>select * from student 27;
SNO
1
2
3
4
5
6
7

SNAME
saradha
anu
saru
sita
mohan
vasantha
nikhil

7 rows selected.

SQL>Create view student_27


2 As

MARKS
80
70
75
65
30
89
50

RANK
2
3
3
5
15
4
6

3 selected sname,marks,rank from student27;


View created.
SQL>desc student_27;
Name
SNAME
MARKS
RANK

Null?

Type
VARCHAR2(10)
NUMBER(10)
NUMBER(10)

SQL>select * from student_27;


SNAME
Saradha
Anu
Saru
Sita
Mohan
Vasantha
Nikhil

MARKS
80
70
75
65
30
89
50

RANK
2
3
3
5
15
4
6

7 rows selected.
SQL>create view student_v as
2 select sno,sname,rank
3 from student27;
View created.

SQL> desc student_v;


Name
SNO
SNAME
RANK

null?

SQL> select * from student_v;

Type
NUMBER(10)
VARCHAR2(10)
NIUMBER(10)

SNO
1
2
3
4
5
6
7

SNAME
saradha
anu
saru
sita
mohan
vasanth
nikhil

RANK
2
3
3
5
15
4
6

7 rows selected.
SQL>select * from student_v where sno=3;
1 row deleted.
SQL>select * from student_v;
SNO
1
2
4
5
6
7

SNAME
sarada
anu
sita
mohan
vasanth
nikhil

RANK
2
3
5
15
4
6

6 rows selected.
SQL>select * from student 27;
SNO
SNAME
MARKS
1
saradha
80
2
anu
70
3
saru
75
4
sita
65
5
mohan
30
6
vasantha
89
7
nikhil
50

RANK
2
3
3
5
15
4
6

6 rows selected.
SQL>update student_v SET sname=stalin
2where sname=sarada;
1 row updated.
SQL>selected * from student_v;

SNO
1
2
3
4
5
6

SNAME
stalin
anu
sita
mohan
vasanth
nikhil

RANK
3
3
5
15
4
6

6 rows selected
SQL>selected * from student27;
SNO
SNAME
MARKS
1
stalin
80
2
anu
70
3
sita
65
4
mohan
30
5
vasantha
89
6
nikhil
50

RANK
2
3
5
15
4
6

6 rows selected.
SQL>inserted into student_v values(10,lenin,1);
1 row created.
SQL>select * from student_v;
SNO
1
2
3
4
5
6
10

SNAME
stalin
anu
sita
mohan
vasanth
nikhil
lenin

7 rows selected.

SQL>selecte * from student_v;

RANK
2
3
5
15
4
6
1

SNO
1
2
3
4
5
6
10

SNAME
stalin
anu
sita
mohan
vasanth
nikhil
lenin

RANK
2
3
5
15
4
6
1

7 rows selected.
SQL>select * from student;
SNO
1
2
3
4
5
6
10

SNAME
stalin
anu
sita
mohan
vasantha
nikhil
lenin

MARKS
80
70
65
30
89
50

RANK
2
3
5
15
4
6
1

7 rows select * from student27;


SNAME
Stalin
Anu
Sita
Mohan
Vasantha
Nikhil
Lenin

MARKS
80
70
65
30
89
50

RANK
2
3
5
15
4
6
1

7 row selected.

SQL OPERATORS

1. Arithmatic operators
2. Concatenation operators
3. Comparison operators
4. logical operators
5. set operators
Arithmetic operators:-+,-,*,/
SQL>select sal+comm. As addition from emp;
Example:
ADDITION
---------------1900
1750
2650
1500
4rows selected.
Example:
SQL>update emp set sal*1.1;
14rows updated.
Concatination operators:- //
The Concatination operators manipulates character string
Example:
SQL>create table tab1
2(
3 col1 varchar2(6),
4 col2 char(6),
5 col3 varchar(6),
6 col4 char(6)
7 );
Table created.
SQL> insert into tab1(col1,col2,col3,col4)
values(abc,def,ghi,jkl);

1 row created.
SQL>select col1//col2//col3//col4 as concat from tab1;
CONCAT
---------------Abcdef ghijkl
Eg:-SQL> select Name is//ename from emp;
NAMEIS//ENAME
-------------------Name is SMITH
Name is ALLEN
Name is JONES
Name is BLAKE
Name is SCOTT
rows selected
Comparision operators:- =,! =, >, <, > =,<= ;
In, Not in, All, between and, exists, like is Null, is not null.
A.Equality : text(=)
Eg :- SQL> select * from emp whare sal= 1760
EMPNO ENAME JOB
MGR HIREDATE SAL COMM DEPTNO
-------------------- ------ -------------- ---------- ------7499 ALLEN SALESMAN 7698 20-FEB-81 1760 300
30
B.in Equality Test (!=)
Eg:- SQL> select * from emp whare sal=1500;
EMPN ENAME
-------- ---------7369 SMATH
7499 ALLEN
7521 JONES

JOB
MGR
--------------CLEARK
7902
SALESMAN 7698
MANAGER 7698

HIREDATE
------------17-DEC-08
23-FEB-81
22-FEB-81

SAL COMM DEPTNO


----- -------- -----------880
20
1760 340
30
1375 500
30

7566 BLAKE ANALYST


7654 SCOTT ANALYST

7839 28-SEP-81 3273


7566 19-APR-87 3300

300

10
30

rows selected.
SQL>select*from emp where sal>1000;
EMPNO ENAME
JOB
MGR
7499
ALLEN SALESMAN 7698
7521
WARD SALESMAN 7698
7566
JONES MANAGER 7839
7654
MARTIN SALESMAN 7698
7698
BLAKE MANAGER 7839
7782
CLARK MANAGER 7839
7788
SCOTT ANALYST 7566
7839
KING
PRESIDENT
7844 TURNER SALESMAN 7698
7876 ADAMS CLERK
7788
7900
JAMES
CLERK
7698
7902
FORD
ANALYST 7566
7934
MILLER CLERK
7782

HIREDATE SAL COMM DEPTNO


20-FEB-81 1760 300
30
22-FEB-81 1375 500
30
02-APR-81 3272.5
20
28-SEP-81 1375 1400
30
01-MAY-81 3135
30
09-JUN-81
2695
10
19-APR-87
3300
20
17-NOV-81 5500
10
08-SEP-81
1650
0
30
23-MAY-87 1210
20
03-DEC-81
1045
30
03-DEC-81
3300
20
23-JAN-82
1430
10

13 rows selected.
D.Less than(or) less than equal to test(<,<=)
Eg:-SQL>select>\*from emp where sal>5000;
EMPNO ENAME JOB
MGR HIREDATE SAL COMM DEPTNO
7369
SMITH
CLERK
7902 17-DEC-80 880
20
7499
ALLEN
SALESMAN
7698 20-FEB-81 1760 300 30
7521
WARD
SALESMAN
7698 22-FEB-81 1375 500 30
7566
JONES
MANAGER7839 02-APR-81 3272.5
20
7654
MARTIN SALESMAN
7698 28-SEP-81 1375 1400 30
7698
BLAKE
MANAGER7839 01-MAY-81 3135
30
7782
CLARK
MANAGER7839 09-JUN-81 2695
10
7788
SCOTT
ANALYST 7566 19-APR-87 3300
20
7844
TURNER SALESMAN
7698 08-SEP-81 1650
30
7876
ADAMS
CLERK
7788 23-MAY-81 1210
20
7900
JAMES
CLERK
7698 03-DEC-81 1045
30
7902
FORD
ANALYST 7566 03-DEC-81 3300
20
12 rows selected
EXAMPLE
SQL>selected*from emp where Sal<=12000;
EMPNO ENAME
JOB
MGR HIREDATE SAL COMM DEPTNO

7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
7934MILLER

CLERK
7902 17-DEC-80 880
SALESMAN
1760 20-FEB-81 1760 300
SALESMAN
1375 22-FEB-81 1375 500
MANAGER3272.5
02-APR-81 3272.5
SALESMAN
1375 28-SEP-81 1375 1400
MANAGER3135 01-MAY-81 3135
MANAGER2695 09-JUN-81 2695
ANALYST 3300 19-APR-87 3300
PRESIDENT
5500 17-NOV-8/1 5500
SALESMAN
1650 08-SEP-81 1650 0
CLERK
1210 23-MAY-87 1210
CLERK
1045 03-DEC-81 1045
ANALYST 3300 03-DEC-81 3300
20
CLERK
1430 23-JAN-82 1430

14 rows selected
E):Equal to any no of Text Equivalent to=any
Eg:-SQL>select ename, sal, deptno from emp where Sal
2
IN
3(SELECT SAL FROM EMP WHERE DEPTNO=10);
ENAME SAL DEPTNO
SMITH 880
20
ALLEN 1760 30
WARD 1375 30
JONES
3270.5 20
4 rows selected
Example:
SQL>select empno,ename,job from emp
2 where ename not in(MILLER,FORD);
EMPNO
ENAME
JOB
7369
SMITH
CLERK
7499
ALLEN
SALESMAN
7521
WARD
SALESMAN
7566
JONES
MANAGER
4 rows selected
G).ALL:Compares a value to every value in a list. most be preceeded by
=,!=,>,<,>=,<=.Evalutes to true if the query returns no rows.

20
30
20
20
30
30
10
20
10
30
20
30
10

EXAMPLE:SQL>Select empno,ename,sal from emp


Where sal>=all(1400,3000);
EMPNO
7566
7698
7788
7839
7902

ENAME
JONES
BLAKE
SCOTT
KING
FORD

SAL
3272.5
3135
3300
5500
3300

H)Betweeen X and y :Greater then or equal x and less than or equal toY.
EX:SQL>Select sal from emp whre sal between 2000 and 3000:
SAL
-----2695
I). EXISTS:True if a sub query returns at least one row.
Example:
SQL>Select dname ,deptno from dept
2 where exists
3 (Select*from emp where dept.deptno=emp.deptno);
DNAME

DEPTNO

ACCOUNTING
RESEARCH
SALES

10
20
30

J). Like(%)the character %matches any string of two are more character
Except null.
E

Example:SQL>Select ename from emp where ename like s%;


ENAME
SMITH
SQL>Select ename from emp where ename like%S;
ENAME
JONES
ADAMS
JAMES
k.)IS NULL(OR) IS NOT NULL:-Tests for Nulls.
EX1:SQL>Select ename, deptno,comm From emp where comm Is null;
ENAME

DEPTNO

SMITH
JONES
BLAKE
CLARK
SCOTT
KING
ADAMS
JAMES
FORD
MILLER

20
20
30
10
20
10
20
30
20
10

COMM

10 rows selected.
EXAMPLE:
SQL>Select ename,comm.,detno from emp where comm is not null;
ENAME
ALLEN
WARD
MARTIN
TURNER

COMM

DEPTNO
300
500
1400
0

SQL>SELECT*From dept;
DEPTNO
DNAME

30
30
30
30
LOC

10
20
30
40

ACCOUNTING
RESEARCH
SALES
OPERATIONS

NEW YORK
DALLAS
CHICAGO
BOSTON

Logical operators:AND
OR
NOT
AND:Return true if both component conditions are true. Returns false if either is false.
Otherwise returns unknown.
Ex:-SQL>Select*from emp where job=CLERK AND deptno=10;
EMPNO ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
7934
MILLER CLERK 7782
23-JAN-82
1430
10
OR:Returns true if either component condition is true. Returns false if both are false
otherwise unknown.
EX:-SQL>Select ENAME,JOB,SAL from emp wher job=CLERK AND deptno=10;
ENAME JOB
SAL
MILLER CLEARK 1430
C)NOT:Returns true if the following condition is false return false if is true. It is
unknown,it remains unknown.
EX:-SQL>Select ename,sal from emp
2 where Not (sal between 1000 and 3000);
ENAME SAL
SMITH
800
KING
5000
JAMES
950

Set operators

1.Union
2.Union ALL
3.Intersect
Union:All rows selected by either queries.
EX:-SQL>Select sname,marks from student 27
2 UNION
3 select sname,marks from student27;
SNAME
Anu
Lenin
Mohan
Nikhil

MARKS
70
40
30
50

4 rows selected.
UNION ALL:All rows selected by either quares,including all duplicates.
EX:- SQL> Selected sname,marks from student 27
2 UNION ALL
3 select sname,marks from student27;
SNAME
MARKS
Stalin
80
Anu
70
Sita
65
Mohan
30
4 rows selected.
C)Intersect:Distinct row selected by both querier.
EX:- SQL>select sname,marks from student 27
2 INTERSECT
3 select sname,marks from student27;
SNAME
MARKS
Anu
70
Lenin
Mohan
30
Nikhil 50
4 rows selected.

D)MINUS:All discount rows selected by the first query but not the second.
EX:- SQL>select sname,marks from student 27
2 MINUS
3 select sname,marks from student27;
No rows selected.
SQL FUNCTIONS
ARTHAMETIC FUNCTIONS:
1.ABS:-Absolute value
Purpose:-It returns the positive value
Syntax:-Abs (value)
Example:-SQL>select abs (146) form dual;
ABS(146)
-----------146
Example:-SQL>select abs (-30)form dual;
ABS(-30)
-------------30
2.SIGN:SYNTAX:-sign (value)
Purpose:-sing is the flip side of absolute value where abs tells you the magnitude of value
,but not its sign.sign tells you the sign of you value but its magnitude.
Example:-SQL>select sing(146)form dual;
SIGN(146)
------------1
Sign(0)is always0
3.CELL:-

Syntax:-ceil(value)
Purpose:-Ceil gives the whole number i.e>=a specific value. Pay special attention to its
effect on negative number
Example:-SQL>select ceil(2)form dual;
CEIL(2)
---------2
4.FLOOR:Syntax:-floor(value)
Purpose:-Floor is opposite to ceil . It also gives whole number i.e <=number that value.
Example:-SQL>select floor (2)from dual;
FLOOR(2)
------------2
Example:-SQL>select floor (1.3)from dual;
FLOOR(1.3)
--------------1
Example:-SQL>select floor(-2.3)from dual;
FLOOR(-2.3)
----------------3
5.MOD:Syntax:-mod (value,divisor)
Purpose:-mod returns remainder of the value mod divider a value by a divisor and tells
you the remainder.
Example:-SQL>select mod (10,3)from dual;
MOD(10,3)
--------------1
Example:-SQL>select mod (4.1,0.3)from dual;

MOD(4.1,0.3)
---------------.2
6.POWER:Syntax:-power(value,exponent)
Purpose:-It returns positive exponent of the value
Example:-SQL>select power (3,2)from dual;
POWER(3,2)
---------------9
7.SQRT:Syntax:-sqrt (value)
Purpose:-returns sqrt of value
Example:-SQL>select sqrt (64)from dual;
SQRT(64)
..
8
8.EXP:Syntax:-exp(value)
Purpose:-exp,log these are rarely used in business calculations but are quit common in
signific and technical work.Exp is e(2.71828183) raised to the specified to the power.it
returns the exponent value.
Example:-SQL>select exp(3) from dual;
EXP(3)
.
20.085537
9.LN:Syntax:-in (value)
Purpose:-ln is the natural or base e of logorthem of value.
Example:-SQL>SQL>select in(20.085536)from dual;
LN(20.085536)
..
3
10.LOG:Syntax:-log(value)
Purpose:- it gives log value.
Example:-SQL>select log(10,100) from dual;

Log(10,100)
.
2
11.ROUND &TURNC
Syntax:-Round (value,pricision)
Purpose:-these are two releated single value function round rounds a number to a given
numer of digits of precision.it returns rounded value.
Example:-SQL> select round(5.1478943,3) from dual;
ROUND(5.1478943,3)
--------------------------5.148
TURNC:Syntax:-turnc(value,precision)
Purpose:-turncates is a digits of precision from a number.
Example:-SQl>select trunc(55.5) from dual;
Trunc(55.5)
.
55
12.GREATEST:Syntax:-greatest(v1,v2.vn)
Purpose:-it returns greast value of given list.
Example:-SQL>select greast(10,20,30,90) from dual;
Greatest(10,20,30,90)
..
90
13.LEAST:Syntax:-Least(v1,v2,..vn)
Purpose:-it returns least value of given list.
Example:-SQL> select least (10,20,30,90) from dual;
Least(10,20,30,90)
.
10
CHARACTER FUNCTIONS

1.CONCAT:Syntax:- Concat(char1,char2);
Purpose:-Returns char1 concatenated with char2 this function is equivalent to the
concatenation operator (11).
Example:-SQL>select concat(venkat,suresh)as name from dual;
NAME
Venkatsuresh
Example:-SQL>select concat(ename||is a,job)from emp
2 where JOB=CLERK;
CONCAT(ENAME||IS A,JOB)
SMITH is a CLERK
ADAMS is a CLERK
JAMES is a CLERK
MILLER is a CLERK
2.INIT CAP:Syntax:- In it cap(string);
Purpose:-Returns char with the first letter of each word in upper case, all other letters in
lower case.
Example:-SQL>select initcap(the soap) as capitals from dual;
CAPITAS
The soap
3.LOWER:Syntax:-lower(string)
Purpose:-Returns char with all letters in lower case from dual.
Example:-SQL>select lower(STALIN) as lower from dual;
LOWER
stalin
SQL>select lower(ename) from emp;

LOWER(ENAM)
....
Smith
Ward
Jones
King
4 rows selected.
4.UPPER:Syntax:-upper(string)
Purpose:- it convert all letters into upper case.
Example:-SQL>select upper(SISTEM COLLEGE) as uppercase from dual;
UPPERCASE
.
SISTEM COLLEGE
5.LENGTH:Syntax:-Length(string)
Purpose:-it returns length of the given string
Example:-SQL>select length(sarada)from dual;
LENGTH(SARADA)
..
6
6.rpad:Syntax:-Rpad(string,n,symbol);
Purpose:-it adds the given symbol to right of the given string.
Example:-SQL>select Rpad(pare15,ab)as rpad from dual;
RPAD
..
pareabababababa
A33 TO COPY
11.SUBSTR:Syntax:-substr(string, star position number of characters);
Purpus:-it extracts number of characters from the given start position of the string.
example:-SQL>select substr(sistam,2;4)as sub string from dual;
SUBS
------Ista

12.INSTR:Syntax:-instr(string,char);
Purpose:-it returns the given character position.
Example:-SQL>select in str(sistam2,4)as sub string from dual;
INSTR(STRING,S)
--------------------------1
13)ASCII:Syntax:-ascii(char)
Purpose:-it returns ascii code for the given character
Example:-sql>select ascii(a)from dual;
ASCII(A)
------------65

DATE FUNCTIONS

1.ADD-MONTHS:Syntax:-Add-month(d,n)
Purpose:-Returns the date d +n month. The argument n can be integer.
EXAMPLE:- SQL> select add_months(sydate,1)from dual;
ADD_MONTH
22-DEC-07
2.LAST DAY:Syntax:-Last day(d)
Purpose:-Returns the date of the last day of the month that contains d.you might use the
function todermine how many days one left in the correct month.
Example:-SQL>select sysdate,last_day (sysdate) as last from dual;
SYSDATE LAST
22-NOV-07
30-NOV-07
3.MONTHS BETWEEN:Syntax:-months-between (d1,d2);
Purpose:-Returns number of months between dates d1 is lesss than d2 result is positive if
earlier negative.
Example:-SQL>select months_between(22-NOV-06,30-NOV-07) as month from
dual;
MONTHS
-12.25806
SQL>select months_between(30-NOV-07,22-NOV-06)as months from dual;
MONTHS
12.258065
4.NEXT-DAY;Syntax:- next day(d,char);
Purpose;-It gives the next day of the given day.
Example:-This example returns the data of the nest Tuesday after march 15,1992.
SQL>Select next-day(15-mar-92,Tuesday) from dual;
NEXT DAY(
.
18-MAR-92

5.TO DATE:Syntax:-To-date
Purpose:-It returns the data in given format.
Example:-SQL>select to-date(10/11/2006,mm/dd/yy) as formatdate from dual;
FORMATDAT
.
11-OCT-06
6.TO CHAR:Syntax:-To-char
Purpose:- It returns the data in words.
Example:-SQL>select to-char(sysdate,month) as Tochar from dual;
TOCHAR
.
November
7.USER:Syntax:-User
Purpose:-Return the current oracle user with the type varchar2.
Example:-SQL>select user,vid from dual;
USER
VI
.

SCOTT
vid
8.Vsize:Syntax:- Vsize(expr)
Purpose:-Returns the number of bytes in the internal representation of expression.
Example:-SQL>select ename,vsize(ename) as byte from emp where deptno=10;
ENAME
BYTE
.
CLARK
5
KING
4
MILLER
6

TRANSACTION CONTROL LANGUGES


Commit
Roll back
Save point
To save point
Example:-SQL>select * from student27;
SNO SNAME
1 stalin
2 anu
4 sita
5 mohan
6 vasanth
7 nikhil
10 lenin

MARKS

RANK

80
70
65
30
89
50

2
3
5
15
4
6
1

7 rows selected.
SQL> deleted.
SQL> select * from student27 where sno=10;
1 row deleted.
SNO SNAME MARKS RANK
1 stalin
2 anu
4 sita
5 mohan
6 vasanth
7 nikhil

80
70
65
30
89
50

6 rows selected.
SQL>roll back;
Rollback complete.
SQL>select * from student27;

2
3
5
15
4
6

SNO SNAME

MARKS

RANK

80
70
65
30
89
50

2
3
5
15
4
6
1

1 stalin
2 anu
4 sita
5 mohan
6 vasanth
7 nikhil
10 lenin
7 rows selected.

SQL> delete from student27 where sno=10;


1 row deleted.
SQL>select * from student27;
SNO SNAME

MARKS

RANK

80
70
65
30
89
50

2
3
5
15
4
6

1 stalin
2 anu
4 sita
5 mohan
6 vasanth
7 nikhil
6 rows selected.
SQL>commit;
Commit complete.

SQL>select * from student27;


SNO SNAME
1 stalin
2 anu
4 sita
5 mohan

MARKS

RANK

80
70
65
30

2
3
5
15

6 vasanth
7 nikhil

89
50

4
6

6 rows selected.
JOINS
A join is a query that combines rows from two or more tables, views or materialized
views
A join is performed when ever multiple tables appear in the queries from clause.
The query select list can select any columns from any of these tables
The common column names with in the tables should qualify all reference to those
columns
Join types:
INNER JOIN/SIMPLE JOIN/EQUI JOIN
OUTER JOIN
SELF JOIN
INNER JOINS:-Return a row only when the columns in the join contain values
That satisfy the join condition.This means that if a row has a null
Values in one of the join condition, that row isnt returned.
OUTER JOINS:-Can return a row even when one of the columns in the join condition
Contains a null values.
SELF JOINS:-Return rows joined on the same table.
A non-equijoin uses an operator other than the equality operator in the join.
Examples of non-equality operator are:
not-equal(<>),
less than(<),
greater than(>),
less than or equal to(<=),
greater than or equal to(>=),
LIKE,
IN,and
BETWEEN.
The query shown that the join is performed with the other WHERE conditions:
SQL>select * from Employee
2/
EMPNO

ENAME

HIREDATE

ORIG_SALARY

CURR_SALARY

122
123
104
105

Alison
James
Celia
Robert

21-MAR-96
12-DEC-78
24-OCT-82
15-JAN-84

45000
23000
53000
31000

48000
32000
58000
36000

4 rows selected
SQL>select * from job;
Hit a key to continue
EMPNO
Painter
Tester
Dediator
Chemist

JOBTITLE

4 rows selected.
The query shown that the join is performed with the other WHERE conditions:
SQL>SELECT e.empno,e.ename,j.jobtitle,e.orig_salary
FROM employee e,job j
WHERE e.orig_salary<43000
AND e.empno=j.empno;
EMPNO
123
105
108

ENAME
James
Robert
Jode

JOBTITLE
Dediator
Accountant
Developer

ORIG_SALARY
23000
31000
21000

Inner joins use join conditions in the FORM clause just like natural join;
Inner join use join conditions in the FROM clause just like natural join,
But you must specify the columns from each table to join on:
SQL>select e.empno,e.ename,d.dname
2 from emp e inner join dept d
3 on e.deptno=d.deptno
4 where e.join=MANAGER;
EMPNO ENAME
DNAME
------------ ------------- -----------7782
CLARK ACCOUNTING
7566
JONES
RESEARCH
7698
BLAKE
SALES

Right outer joins:


Right outer joins:return all the rows form the table on the right instead of the table on the
left.
Return all the rows from the table on the right of the join condition instead of the table
on left.
SQL>select e.empno,e.ename,d.dname
2 from emp e right outer join dept d
3 on e.deptno=d.deptno
4 where d.loc=CHICAGO
5 order by d.dname,e.ename;
EMPNO
ENAME
-----------------------ALLEN SALES
7698
BLAKE
7900
JAMES
7654
MARTIN
7844
TURNER
Left outer join demo

DNAME
-----------SALES
SALES
SALES
SALES
SALES

Aleft outer join.the outer join operator appears on the right of the equaiity operator:
SQL>select el.enameEmployee,
2 e2.enameReports To,
3 from emp el left outer join emp e2
4 on el.MGR=e2.empno
5 order by el .empno;
Employee
------------SMITH
ALLEN
WARD
JONES
MARTIN
CLARK
SCOTI
14 rows selected.

Reports To
-----------FORD
BLAKE
BLAKE
KING
BLAKE
KING
JONES
Working with equijoins:

SQL>
SQL> SELECT Employee.Employee_ID ID, Employee.Start_Date,
2 Employee.Employee_Nane,Department.Department_Name,Department.Location
3 FROM Employee,Department
4 WHERE Department.Department_ID=Employee.Department_ID;
ID
------7369
7499
7788
7782

START DAT
----------------17-DEC-80
20-FEB-81
09-DEC-82
09-JUN-81

EMPNAME
---------------SMITH
ALLEN
SCOTT
CLARK

DEPT_NAME
------------------RESEARCH
SALES
RESEARCH
ACCOUNTING

LOCATION
------------DALLAS
CHICAGO
DALLAS
NEWYORK

4 rows selected.

SUB QUERIES
A SUB QUEREY answer the multiple part of questions.
A sub query in the where clause of a select statement is called as nested sub query.
A sub query contain another sub query.
To make the statement easier for readability, qualify the column in a sub query with table
name or table alias.
A sub queery can be part of a column, in the select list.
Type of sub queries:
Single row sub query
Multiple row sub query
Multiple column sub query
Single row sub query return only one row from the inner select statement .
Single row sub query operators are >,=,>=,<>,<=.
Multiple row sub query return more then one row from the inner select statement.
Multiple row sub query operators are IN,ANY,ALL.
Multiple column sub query return more then one column from the inner select statement.
SQL>select * from employee;

ID FIRST NAME LAST NAME LAST DATE END DATE


SALARY
CITY
DESCRIPTION
01
jason
martin
1996-JUL-25 2006-JUL-25
1234.56
toronto
programmer
02
Alison
mathews
1976-MAR-21 1986-FEB-21
6661.78
vancouver tester
03
linda
green
1987-JUL-30
1996-JAN-04
4322.78
new york
tester
04
james
cat
1996-SEP-17
2002-APR-15
1232.78
vancouver tester
4 row selected.
SQL>SELECT first_name,last_name
2FROM employee
3WHERE id=
4(SELECT id
5FROM employee
6WHERE last_name=cat);
FIRST_NAME
James

LAST_NAME
cat

SQL>1 SELECT eName


2 from Emp
3 WHERE sal>(SELECT min(sal)
4 FORM Emp
5 WHERE deptno=( SELECT deptno
6 FROM dept
7 WHERE loc=NEW YORK));
ENAME
ALLEN
JONES
BLAKE
CLARK
4 rows selected.
Nested Sub queries:
SQL> SELECT city,AVG(salary)
2 FROM employee

3 GROUP BY city
4 HAVING AVG(salary)<
S (SELECT MAX (AVG (salary)) FROM employee WHERE id in (SELECT id FROM
employee)
6 GROUP BY city);
CITY
AVG(SALARY)
Toronto
1234.56
Vancouver 3823.78
Multiple Row Subquery with ALL:
ALL with a Multiple Row Subquery: must place an=,<>,<,>,<=,or>= operator before
ALL.
SQL>SELECT id,last_name
2 FROM employee
3 where salary>ALL
4 (SELECT salary
5 from employee where description=Tester);
ID LAST_NAME
Larry
Multiple Row Subquery with ANY:ANY with a Multiple Row Subquery: must place an =,<>,<,>,<=,or>= operator before
ANY
SQL>SELECT id,last_name
2 FROM employee
3 WHERE salary
5 FROM employee where city=New York);
ID LAST_NAME
Cat
Martin
05
Black
04
Rice
06
Green
03
Smith
02
Mathew
7 rows selected.

Multi Row Subquery with IN:


Multiple Row Subqueries: IN with subquery.
SQL>SELECT id first_name
2 FROM employee
3 WHERE id IN
4 (SELECT id
5 FROM employee
6 WHERE first_name LIKE%e%);
ID FIRST_NAME
James
Celia
Robert
08
James

PL/SQL PROGRAMS

ADDITION OF TWO NUMBERS:


SQL>Declare
2 x number(5):=& number;
3 y number(5):=& number;
4 z number;
5 begin
6 z:=x+y;
7 dbms_output.line(sum is||z);
8 end;
9/
Enter value for number:12
Old 2: x number(5):=& number;
New 2: x number(5):=12;
Enter value for number:23
Old 3: y number(5):=& number;
New 3:y number(5):=23;
Sum is 35
PL/SQL procedure successfully completed.

REVERSE NUMBER:
SQL>Declare
2 n number(5):=&n;
3 r number(5):=0;
4 s number(5):=0;
5 begin
6 loop
7 r:=n mod 10;
8 s:=s* 10+r;
9 n:=n/10;
10 exit when n=10;
11 end loop;
12dbms_output.put_line(the revsrse no is||s);
13 end;
14 /
Enter value for n:123
Old 2:n number(5):=&n;
New 2:n number(5):=123;
the reverse no is 321

Pl/sql procedure successfully completed

SELECT STATEMENT USED IN PL/SQL


SQL> DECLARE
2 my name emp.ename%TYPE:=joe;
3BEGIN
4 SELECT ename
5 INTO my name
6 FROM emp
7 WHERE ename=JAMES;
8
9 DBMS OUTPUT.PUT LINE(Name is//my name);
10 END;
11 /
Name is JAMES
PL/SQL procedure successfully completed
INSERT STATEMENT USED IN PL/SQL
SQL> BEGIN
2 INSERT INTO emp(empno)
3 VALUES(12);
4
5 COMMIT;
6 END;
7/
PL/SQL procedure successfully completed.
DELETE STATEMENT USED IN PL/SQL
SQL> BEGIN
2 DELETE FROM employee;
3 END;
4/
PL/SQL procedure succefully completed.
SQL> select * from employee;
No rows selected.

FUNCTIONS
SQL>create or replace function fname(no in number)
2 return number
3 is
4 N number(5);
5 begin
6 N:=no;
7 return n;
8 end;
9/
Function created.
SQL>declare
2 X number(5):=0;
3 Begin 4
X:=fname(10);
Dbms-output.put-line(x);
7/
10
PL/SQL procedure successfully completed.

TRIGGERS

Oracles syntax for creating a trigger based on two tables:


SQL>CREATE TABLE my Table1 (a INTEGER, b CHAR (10));
Table created.
SQL > CREATE TABLE my table2 (c CHAR (10), d INTEGER);
Table created.
SQL>CREATE TRIGGER trig1
2 AFTER INSERT ON my table1
3 REFERENCING NEW AS new Row
4 FOR EACH ROW
5 (new Row. a <=10)
6 BEGIN
7 INSERT INTO mytable2 VALUES (: new Row . b , :new Row. a );
8 END trig1;
9.
SQL>run;
1 CREATE TRIGGER trig1
2 AFTER INSERT ON my table1
3 REFERENCING NEW AS new Row
4 FOR EACH ROW
5 WHEN (new ROW .a <=10)
6 BEGIN
7 INSERY INTO my table2 VALUES (: new Row .b ,: new Row .a);
8 * END trig1;
Trigger created.
SQL> insert into my table1 values (1,a);
1 row created.
SQL> insert into my table 1 values (2,b);
1 row created.
SQL >select * from my table1;
A B
1 a
2 b
SQL> select * from my table 2;
C D
A 1
B 2

You might also like