Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Lab Commands

The document describes 4 main types of DBMS languages: 1) Data Definition Language (DDL) is used to define and modify database objects like tables and indexes. It includes commands like CREATE, ALTER, DROP, RENAME, TRUNCATE. 2) Data Manipulation Language (DML) is used to manipulate data within database objects. It includes commands like INSERT, SELECT, UPDATE, DELETE. 3) Data Control Language (DCL) is used to control access to data. It includes commands like GRANT, REVOKE. 4) Transaction Control Language (TCL) is used to manage transactions. It includes commands like COMMIT, ROLLBACK, SAVEPOINT.

Uploaded by

Shilpi Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Lab Commands

The document describes 4 main types of DBMS languages: 1) Data Definition Language (DDL) is used to define and modify database objects like tables and indexes. It includes commands like CREATE, ALTER, DROP, RENAME, TRUNCATE. 2) Data Manipulation Language (DML) is used to manipulate data within database objects. It includes commands like INSERT, SELECT, UPDATE, DELETE. 3) Data Control Language (DCL) is used to control access to data. It includes commands like GRANT, REVOKE. 4) Transaction Control Language (TCL) is used to manage transactions. It includes commands like COMMIT, ROLLBACK, SAVEPOINT.

Uploaded by

Shilpi Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 151

DBMS Languages

 Data Definition Language (DDL)

 Data Manipulation Language (DML)

 Data Control Language (DCL)

 Transaction control Language (TCL)

NCS, APS /SITE 1


Data Definition Language

Create

Alter

Drop

Rename

Truncate
NCS, APS / SITE 2
Data Manipulation Language

Insert

Select

Update

Delete

NCS, APS / SITE 3


Data Control Language
Grant
Revoke

Transaction Control Language


Commit
Rollback
Savepoint
NCS, APS / SITE 4
DDL
Create
Syntax:
Create table TN
( CN1 data type ,
CN2 data type,
CN3 data type,
CN4 data type,
….
);

NCS, APS / SITE 5


Example:
SQL> create table emp (
2 id number(3),
3 salary number(10),
4 name varchar2(30),
5 dob date,
6 addr varchar2(20)
7 );
Table created.

NCS, APS / SITE 6


DML
Insert (Simple form)
Syntax:
INSERT INTO tablename VALUES
( val1,val2, val3, val4 …);

Example
SQL> insert into emp values
(3,6000,‘siva','01-jan-75','vellore');
1 row created.

NCS, APS / SITE 7


Inserting interactively

INSERT INTO <tablename> VALUES


( &column name1,
&column name2,
&column name3,
&column name4,
…);

NCS, APS / SITE 8


SQL> insert into emp values(
2 &id,&salary,'&name','&dob','&addr');
Enter value for id: 1
Enter value for salary: 2000
Enter value for name: red
Enter value for dob: 23-oct-1986
Enter value for addr: vellore
old 2: &id,&salary,'&name','&dob','&addr')
new 2: 1,2000,'red','23-oct-1986','vellore')

1 row created.
NCS, APS / SITE 9
SQL> /
Enter value for id: 2
Enter value for salary: 2000
Enter value for name: blue
Enter value for dob: 24-oct-1987
Enter value for addr: chennai
old 2: &id,&salary,'&name','&dob','&addr')
new 2: 2,2000,'blue','24-oct-1987','chennai')

1 row created.

NCS, APS / SITE 10


DML
Select (Entire Table)
Syntax:
Select * from tablename;

Example:
SQL> select * from emp;
ID SALARY NAME DOB ADDR
---------- ---------- ----------------------- ------------- --------------------
1 2000 red 23-OCT-86 vellore
2 2000 blue 24-OCT-87 chennai
3 6000 siva 01-jan-75 vellore
NCS, APS / SITE 11
Select (Particular column)
Syntax:
Select CN1,CN2 from tablename;

Example:

SQL> select id from emp;


ID
----------
1
2
3
NCS, APS / SITE 12
DDL

ALTER

Add new columns

Modify the data type

Increase / decrease the column width

Drop column

Rename the column name

NCS, APS / SITE 13


Alter (Add –to add new columns)

Syntax:

ALTER TABLE tablename

ADD columnname datatype;

Example:

SQL> alter table emp add age number(2);

Table altered.

NCS, APS / SITE 14


Alter (Modify the data type)

Syntax:
ALTER TABLE tablename
MODIFY column name newdatatype;
Example:
SQL> alter table emp modify age varchar2(2);
Table altered.
SQL> alter table emp modify age number(2);
Table altered.

NCS, APS / SITE 15


SQL> alter table emp modify id varchar2(3);

alter table emp modify id varchar2(3)

ERROR at line 1:

ORA-01439: column to be modified must be empty to


change datatype

NCS, APS / SITE 16


Alter ( Increase / decrease the column width)
Syntax:
ALTER TABLE tablename
MODIFY column name datatype newwidth;
Example:
SQL> alter table emp modify age number(4);
Table altered.

SQL> alter table emp modify age number(2);


Table altered.

NCS, APS / SITE 17


SQL> alter table emp modify id number(2);
alter table emp modify id number(2)
*
ERROR at line 1:
ORA-01440: column to be modified must be empty to
decrease precision or scale

SQL> alter table emp modify id number(4);


Table altered.

NCS, APS / SITE 18


Alter (Drop –delete column)

Syntax:

ALTER TABLE tablename

DROP COLUMN columnname;

Example:

SQL> alter table emp drop column dob;

Table altered.

NCS, APS / SITE 19


Alter (Rename the column Name)

Syntax:

ALTER TABLE tablename

RENAME COLUMN oldcn TO newcn;

Example:
SQL> alter table emp11
rename column eno to emp_no;
Table altered.

NCS, APS / SITE 20


RENAME
Changes table name
Syntax:
RENAME old tablename TO new tablename;
Example:
SQL> rename emp to emp1;
Table renamed.

SQL> rename emp1 to emp;


Table renamed.

NCS, APS / SITE 21


TRUNCATE
Removes the rows, not the definition
Syntax:
TRUNCATE TABLE tablename;
Example:
SQL> truncate table emp;
Table truncated.

SQL> select * from emp;


no rows selected

NCS, APS / SITE 22


DROP
Removes the rows and table definition
Syntax:
DROP TABLE <tablename>;
Example:
SQL> drop table emp;
Table dropped.

SQL> select * from emp;


select * from emp
*
ERROR at line 1:
ORA-00942: table or view does not exist
NCS, APS / SITE 23
To view the structure of the table
Syntax:
DESC tablename;
Example:
SQL> desc emp11;
Name Null? Type
---------------------------------- -------- -----------------------
ENO NUMBER(3)
ENAME VARCHAR2(5)
AGE NUMBER(3)

NCS, APS / SITE 24


DML
Insert (null values)
Syntax:
INSERT INTO tablename VALUES
( val1,’’,’’,val4);
Example
SQL> insert into emp11 values
(1,'',25);
1 row created.
SQL> select * from emp11;
ENO ENAME AGE
---------- ----------- -----------
1 25
NCS, APS / SITE 25
DML
Insert (to particular columns)
Syntax:
INSERT INTO tablename (cn1,cn2) VALUES
( val1,val2);
Example
SQL> insert into emp11(eno,ename) values (2,'y');
1 row created.
SQL> select * from emp11;
ENO ENAME AGE
---------- ----------- ----------
1 25
2 y
NCS, APS / SITE 26
Select (Particular rows)
Syntax:
SELECT * FROM tablename
WHERE conditions;
Example:
SQL> select * from emp11
where ename='y';
ENO ENAME AGE
---------- ----------- ----------
2 y
SQL> select * from emp11
where ename='Y';
no rows selected

NCS, APS / SITE 27


Select (Particular column and rows)
Syntax:
SELECT cn1,cn2 FROM tablename
WHERE conditions;
Example:
SQL> select eno,age from emp11
where eno=1;

ENO AGE
---------- ----------
1 25

NCS, APS / SITE 28


Select (using NULL value)
Syntax:
SELECT * FROM tablename
WHERE cn IS NULL;
Example:
SQL> select * from emp11
where ename is null;
ENO ENAME AGE
---------- ----------- ----------
1 25

NCS, APS / SITE 29


SQL> select * from emp11
where ename is not null;

ENO ENAME AGE


---------- ----------- ----------
2 y 26
3 z 25

NCS, APS / SITE 30


Select (with Alias name)
Syntax:
SELECT cn1 alias name 1, cn2 alias name 2
FROM tablename;
Example:
SQL> select eno emp_no, age old
from emp11;
EMP_NO OLD
------------ ----------
1 25
2 26
3 25
NCS, APS / SITE 31
Select (with distinct clause)
Syntax:
SELECT DISTINCT cn
FROM tablename;
Example:
SQL> select distinct age
from emp11;
AGE
----------
25
26
NCS, APS / SITE 32
UPDATE (Simple update)
Syntax:
UPDATE tablename
SET col = new value;
Example:
SQL> update emp11
set age=27;

3 rows updated.

NCS, APS / SITE 33


UPDATE (Using where clause)
Syntax:
UPDATE tablename
SET col1 = new value, col2 = new value
WHERE conditions;
Example:
SQL> update emp11
set age=25
where eno=2;

1 row updated.
NCS, APS / SITE 34
UPDATE (Using Null)
Syntax:
UPDATE tablename
SET col1 = new value, col2 = new value
WHERE cn IS NULL;
Example:
SQL> update emp11 set age=25
where ename is null;
1 row updated.
SQL> update emp11 set age=27
where ename is not null;
2 rows updated.

NCS, APS / SITE 35


UPDATE (Using Null data)
Syntax:
UPDATE tablename
SET col1 = ‘’, col2 = ‘’
WHERE conditions;
Example:
SQL> update emp11 set ename=''
where eno=2;
1 row updated.
SQL> update emp11 set ename=‘’
where eno=4;
0 rows updated.

NCS, APS / SITE 36


DELETE (Delete all rows)

Syntax:

DELETE FROM tablename;

Example:

SQL> delete from emp11;

3 rows deleted.

NCS, APS / SITE 37


DELETE (Using where clause –delete specific rows)
Syntax:
DELETE FROM tablename
WHERE conditions;

Example
SQL> delete from emp11
where ename='z';

1 row deleted.

NCS, APS / SITE 38


DELETE(Using Null)
Syntax:
DELETE FROM tablename
WHERE cn IS NULL;
Example
SQL> delete from emp11
where ename is null;
1 row deleted.
SQL> delete from emp11
where age is not null;
2 rows deleted.
NCS, APS / SITE 39
Operators in SQL

Arithmetic operator: +, -, *, /

Logical Operator – AND, OR, NOT

Comparison Operator –
=, !=, <, <=, >, >=,
between, not between,
in, not in, like, not like,
is null, is not null

NCS, APS / SITE 40


SQL> select * from stu;
REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
1 27 34
2 25 43
3 34 21
4 12 14
SQL> select c1+c2 ad, c1-c2 sub, c1*c2 mul, c1/c2 div from stu;
AD SUB MUL DIV
---------- ---------- ---------- ----------
61 -7 918 .794117647
68 -18 1075 .581395349
55 13 714 1.61904762
26 -2 168 .857142857

NCS, APS / SITE 41


SQL> update stu set total = c1+c2
where regno=&regno;
Enter value for regno: 1
old 2: where regno=&regno
new 2: where regno=1

1 row updated.

SQL> /
Enter value for regno: 2
old 2: where regno=&regno
new 2: where regno=2

1 row updated.

NCS, APS / SITE 42


Logical Operator :
Syntax:
SELECT * FROM tn
WHERE cond1 L.OP cond2;
Example: (AND)
SQL> select * from stu
where regno=1 and c1=27;
REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
1 27 34 61
SQL> select * from stu
where regno=1 and c1=25;
no rows selected
NCS, APS / SITE 43
Example: (OR)

SQL> select * from stu

where regno=1 or c1=25;

REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
1 27 34 61
2 25 43 68

NCS, APS / SITE 44


Comparison Operators:
Syntax for =, !=, >, >=, <, <=:
SELECT * FROM tn
WHERE cn com.op value;
Example:
SQL> select * from stu where c1=12;
REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
4 12 14 26
SQL> select * from stu where regno != 3;
REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
1 27 34 61
2 25 43 68
4 12 14 26 NCS, APS / SITE 45
SQL> select * from stu where c2 >30;

REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
1 27 34 61
2 25 43 68

SQL> select * from stu where c2 >= 34;

REGNO C1 C2 TOTAL
---------- ---------- ---------- ----------
1 27 34 61
2 25 43 68

NCS, APS / SITE 46


Comparison Operators:
Syntax for BETWEEN, NOT BETWEEN:
SELECT * FROM tn
WHERE cn com.op value1 AND value2;
Example:
SQL> select total from stu where total between 55 and 65;
TOTAL
----------
61
55
SQL> select c1 from stu where c1 not between 25 and 35;
C1
----------
12

NCS, APS / SITE 47


Comparison Operators:
Syntax for IN, NOT IN:
SELECT * FROM tn
WHERE cn com.op (v1, v2,…);
Example:
SQL> select total from stu where total in (78,56,26);
TOTAL
----------
26
SQL> select c1 from stu where c1 not in(25,34,27,55);
C1
----------
27
NCS, APS / SITE 48
SQL> select * from emp11 where ename in('a','y','Y');

ENO ENAME AGE


---------- ----------- ----------
2 y

SQL> select empno,hiredate from emp


where hiredate in ('23-JAN-82','01-MAY-81');

EMPNO HIREDATE
----------- --------------
7698 01-MAY-81
7934 23-JAN-82
NCS, APS / SITE 49
SQL> select * from emp11;
ENO ENAME AGE
-------- ----------- ----------
1 sahil 25
2 anu
3 vijay 26

Comparison Operators:
Syntax for LIKE, NOT LIKE:
SELECT * FROM tn
WHERE cn com.op (pattern);

NCS, APS / SITE 50


SQL> select ename from emp11 where ename like ('s%');
ENAME
---------
sahil

SQL> select ename from emp11 where ename like ('%u');


ENAME
---------
anu

SQL> select ename from emp11 where ename like ('S%l');


no rows selected

NCS, APS / SITE 51


SQL> select ename from emp11 where ename like ('v%y');
ENAME
---------
vijay
SQL> select ename from emp11 where ename like ('___');
ENAME
---------
anu
SQL> select ename from emp11 where ename like ('_i%');
ENAME
---------
vijay

NCS, APS / SITE 52


SQL> select ename from emp11 where ename like ('s_h%');
ENAME
---------
sahil

SQL> select ename from emp11 where ename like ('%i_');


ENAME
---------
sahil

NCS, APS / SITE 53


Constraints:
Domain Integrity Constraints:

Not Null, Check

Entity Integrity Constraints:

Unique, Primary Key

Referential Integrity Constraints:

Foreign Key

NCS, APS / SITE 54


Syntax 1 (during Create):
CREATE TABLE tn
(cn1 datatype con_type,
cn2 datatype con_type,
cn3 datatype con_type,
. . . );

Example:
SQL> create table emp2
(eno number(2) primary key,
ename varchar2(10) not null,
address varchar2(20) unique,
salary number(4) check (salary >=5000),
age number(2) check (age between 18 and 60));
Table created.
NCS, APS / SITE 55
Syntax 2 (constraint name along with cn):
CREATE TABLE tn
(cn1 datatype CONSTRAINT con_name con_type,
cn2 datatype CONSTRAINT con_name con_type,
cn3 datatype CONSTRAINT con_name con_type,
. . . );
Example:
SQL> create table dept2
(dno number(2) constraint dept_dno_pk primary key,
dname varchar(7) constraint dept_dn_nn not null,
dloc varchar(7) constraint dept_dl_uni unique,
no_of_emp number(3) constraint dept_emp_chk check (no_of_emp>10));

Table created.
NCS, APS / SITE 56
Syntax 3(with constraint name):
CREATE TABLE tn
(cn1 datatype,
CONSTRAINT con_name con_type (cn1), . . . );

Example:
SQL> create table c1 ( a number(3), b varchar2(5), c varchar2(7),
constraint c1_a_pk primary key (a),
constraint c1_b_uni unique (b),
constraint c1_c_chk check (c like ('s%')));

Table created.;

NCS, APS / SITE 57


Syntax 1 (Foreign key):

CREATE TABLE tn
(cn1 datatype REFERENCES parent_tn (pk cn) );

Example:

SQL> create table c2


(f number(3) references c1 (a));

Table created.

NCS, APS / SITE 58


Syntax 2 (Foreign key):

CREATE TABLE tn
(cn1 datatype CONSTRAINT con_name REFERENCES
parent_tn (pk cn) );

Example

SQL> create table c3


(d number(3) constraint c3_d_fk references c1 (a));

Table created.
NCS, APS / SITE 59
Syntax 3(with constraint name):
CREATE TABLE tn
(cn1 datatype,
CONSTRAINT con_name FOREIGN KEY (cn1)
REFERENCES parent_tn (pk cn) );

Example:
SQL> create table c4
(s number(3),
constraint c3_s_fk foreign key(s) references c1 (a));

Table created.
NCS, APS / SITE 60
SQL> create table works
(emp_no number(4),
dnum number(3),
constraint works_eno_fk foreign key(emp_no) references
emp2(eno),
constraint works_dnum_fk foreign key(dnum) references
dept2(dno),
constraint works_pk primary key(emp_no,dnum));

Table created.

NCS, APS / SITE 61


Constraints (Using ALTER Command):

Syntax (for Primary key, Unique & Check):


ALTER TABLE tn

ADD CONSTRAINT con_name con_type (cn);

Example:
SQL> alter table emp11 add constraint pk_eno_emp11

primary key(eno);

Table altered.

NCS, APS / SITE 62


SQL> alter table emp11 add constraint un_age_emp11
unique(age);

Table altered.

SQL> alter table emp11 add constraint chk_age_emp11

check (age between 18 and 58);

Table altered.

NCS, APS / SITE 63


Syntax (for Not Null):
ALTER TABLE tn

MODIFY cn datatype

CONSTRAINT con_name NOT NULL;

Example:
SQL> alter table emp11 modify ename varchar2(5)

constraint emp11_ename_nn not null;

Table altered.

NCS, APS / SITE 64


Syntax (for Foreign key):

ALTER TABLE tn

ADD CONTRAINT con_name FOREIGN KEY (cn1)

REFERENCES parent_tn (pk cn);

Example:
SQL> alter table emp11 add constraint fk_dno_emp11

foreign key (dno) references dept1 (dno);

Table altered.

NCS, APS / SITE 65


Dropping the Constraints:

Syntax:
ALTER TABLE tn

DROP CONSTRAINT con_name;

Example:
SQL> alter table emp11

drop constraint chk_age_emp11;

Table altered.

NCS, APS / SITE 66


SQL * PLUS FUNCTIONS:
Group functions
Single Row Functions

Group functions:
Result based on group of rows.

Single Row Functions:


returns only one value for every row.
Can be used in SELECT command and included in
WHERE clause

NCS, APS / SITE 67


Group functions:
Result based on group of rows.

Syntax:
SELECT gf (cn) FROM tn;

Example:
SQL> select min(sal) from emp;

MIN(SAL)

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

800
NCS, APS / SITE 68
SQL> select max(sal) from emp;
MAX(SAL)
---------------
5000

SQL> select avg(sal) from emp;


AVG(SAL)
---------------
2073.21429

SQL> select sum(sal) from emp;


SUM(SAL)
--------------
29025
NCS, APS / SITE 69
SQL> select stddev(sal) from emp;
STDDEV(SAL)
---------------------
1182.50322

SQL> select variance(sal) from emp;


VARIANCE(SAL)
-----------------------
1398313.87

SQL> select count(*) from emp;


COUNT(*)
---------------
14
NCS, APS / SITE 70
SQL> select count(sal) from emp;

COUNT(SAL)
-----------------
14

SQL> select count(distinct sal) from emp;

COUNT(DISTINCTSAL)
-------------------------------
12

NCS, APS / SITE 71


Single Row Functions (Types):
Numeric functions
Character functions
Date functions
Conversion functions
Miscellaneous functions

Numeric functions:
Syntax:
SELECT n.f(CN) from TN ;
SELECT n.f(value) from DUAL;

NCS, APS / SITE 72


SQL> select abs(-34) from dual;
ABS(-34)
---------
34

SQL> select cos(0) from dual;


COS(0)
---------
1

SQL> select cosh(180) from dual;


COSH(180)
---------
7.447E+77

NCS, APS / SITE 73


SQL> select exp(10) from dual;
EXP(10)
---------
22026.466
SQL> select power(2,2) from dual;
POWER(2,2)
----------
4
SQL> select mod(10,2) from dual;
MOD(10,2)
---------
0
SQL> select mod(10,3) from dual;
MOD(10,3)
---------
1
NCS, APS / SITE 74
SQL> select ceil(87.7) from dual;
CEIL(87.7)
----------
88
SQL> select ceil(87.3) from dual;
CEIL(87.3)
----------
88
SQL> select floor(87.7) from dual;
FLOOR(87.7)
-----------
87
SQL> select floor(87.3) from dual;
FLOOR(87.3)
-----------
87
NCS, APS / SITE 75
SQL> select round(34.645,2) from dual;
ROUND(34.645,2)
---------------
34.65

SQL> select round(34.643,2) from dual;


ROUND(34.643,2)
---------------
34.64

SQL> select round(98.645) from dual;


ROUND(98.645)
-------------
99

NCS, APS / SITE 76


SQL> select trunc(34.645,2) from dual;
TRUNC(34.645,2)
---------------
34.64

SQL> select trunc(34.643,2) from dual;


TRUNC(34.643,2)
---------------
34.64

SQL> select trunc(34.645) from dual;


TRUNC(34.645)
-------------
34
NCS, APS / SITE 77
SQL> select sqrt(100) from dual;
SQRT(100)
---------
10
SQL> select ln(100) from dual;
LN(100)
---------
4.6051702
SQL> select sign(3) from dual;
SIGN(3)
---------
1
SQL> select sign(-3) from dual;
SIGN(-3)
---------
-1
NCS, APS / SITE 78
Character functions:
Syntax:
SELECT c.f(CN) from TN ;
SELECT c.f(value) from DUAL;

SQL> select initcap('senthil') from dual;


INITCAP
-------
Senthil

SQL> select lower('SENTHIL') from dual;


LOWER('
-------
senthil

NCS, APS / SITE 79


SQL> select upper('senthil') from dual;
UPPER('
-------
SENTHIL

SQL> select ltrim('senthil','sen') from dual;


LTRI
----
thil

SQL> select ltrim('senthil','il') from dual;


LTRIM('
-------
senthil

NCS, APS / SITE 80


SQL> select ltrim('sensenthil','sen') from dual;
LTRI
----
thil

SQL> select ltrim('sensenthil','SEN') from dual;


LTRIM('SEN
----------
sensenthil

SQL> select rtrim('senthil','thil') from dual;


RTR
---
sen

NCS, APS / SITE 81


SQL> select translate('senthil','s','b') from dual;
TRANSLA
-------
benthil

SQL> select translate('senthil','se','b') from dual;


TRANSL
------
bnthil

SQL> select translate('senthil','sl','b') from dual;


TRANSL
------
benthi

NCS, APS / SITE 82


SQL> select replace('senthil','sen','b') from dual;
REPLA
-----
bthil

SQL> select replace('senthil','sl','b') from dual;


REPLACE
-------
senthil

SQL> select substr('senthil',3,2) from dual;


SU
--
nt

NCS, APS / SITE 83


SQL> select lpad('senthil',15,'@') from dual;
LPAD('SENTHIL',
---------------
@@@@@@@@senthil
SQL> select rpad('senthil',15,'@') from dual;
RPAD('SENTHIL',
---------------
senthil@@@@@@@@
SQL> select length('senthil') from dual;
LENGTH('SENTHIL')
-----------------
7
SQL> select chr(74) from dual;
C
-
J
NCS, APS / SITE 84
Date functions:
Syntax:
SELECT d.f(CN) from TN ;
SELECT d.f(value) from DUAL;

SQL> select add_months('18-jan-2001',2) from dual;


ADD_MONTH
---------
18-MAR-01

SQL> select add_months('18-dec-2001',2) from dual;


ADD_MONTH
---------
18-FEB-02

NCS, APS / SITE 85


SQL> select last_day('18-jan-2001') from dual;
LAST_DAY(
---------
31-JAN-01

SQL> select last_day('27-feb-2002') from dual;


LAST_DAY(
---------
28-FEB-02

SQL> select months_between('01-jan-2001','31-jan-2001') from dual;


MONTHS_BETWEEN('01-JAN-2001','31-JAN-2001')
-------------------------------------------
-.9677419

NCS, APS / SITE 86


SQL> select round(sysdate,'year') from dual;
ROUND(SYS
---------
01-JAN-09

SQL> select round(to_date('25-aug-09'),'year') from dual;


ROUND(TO_
---------
01-JAN-10

SQL> select round(sysdate,'month') from dual;


ROUND(SYS
---------
01-FEB-09

NCS, APS / SITE 87


SQL> select round(sysdate,'day') from dual;
ROUND(SYS
---------
25-JAN-09

SQL> select trunc(sysdate,'year') from dual;


TRUNC(SYS
---------
01-JAN-09

SQL> select trunc(sysdate,'month') from dual;


TRUNC(SYS
---------
01-JAN-09

NCS, APS / SITE 88


SQL> select trunc(sysdate,'day') from dual;
TRUNC(SYS
---------
25-JAN-09

SQL> select next_day('13-dec-2002','sunday') from dual;


NEXT_DAY(
---------
15-DEC-02

SQL> select next_day('13-dec-2002','wednesday') from dual;


NEXT_DAY(
---------
18-DEC-02

NCS, APS / SITE 89


SQL> select greatest ( '25-jan-2006', '23-feb-2009') from dual;
GREATEST('2
-----------
25-jan-2006

SQL> select greatest ( to_date('25-jan-2006'), to_date('23-feb-2009')) from


dual;
GREATEST(
---------
23-FEB-09

Conversion functions:
Syntax:
SELECT con.f(CN) from TN ;
SELECT con.f(value) from DUAL;
NCS, APS / SITE 90
SQL> select to_char(hiredate,'DDth month yyyy') from emp;
TO_CHAR(HIREDATE,'D
-------------------
17TH december 1980
02ND april 1981
SQL> select to_char(hiredate,'DDth fmmonth yyyy') from emp;
TO CHAR(HIREDATE,'D
-------------------
17TH december 1980
02ND april 1981
SQL> select to_char(hiredate,'DDth Month yyyy') from emp;
TO_CHAR(HIREDATE,'D
-------------------
17TH December 1980
02ND April 1981

NCS, APS / SITE 91


SQL> select to_char(hiredate,'ddth MONTH yy') from emp;
TO_CHAR(HIREDATE,
-----------------
17th DECEMBER 80
02nd APRIL 81

SQL> select to_char(sysdate,'dd/mm/yy') from dual;


TO_CHAR(
--------
27/01/09

SQL> select to_char(sysdate,'MONTH dd yy') from dual;


TO_CHAR(SYSDATE
---------------
JANUARY 27 09
NCS, APS / SITE 92
SQL> select to_date('03/mar/03') from dual;
TO_DATE('
---------
03-MAR-03

SQL> select to_date('27 JANUARY 09') from dual;


TO_DATE('
---------
27-JAN-09

SQL> select to_number('45') from dual;


TO_NUMBER('45')
---------------
45

NCS, APS / SITE 93


Miscellaneous functions:
Syntax:
SELECT m.f(CN) from TN ;
SELECT m.f(value) from DUAL;
SQL> select uid from dual;
UID
----------
66
SQL> select user from dual;
USER
------------------------------
SCOTT
SQL> select vsize('scott') from dual;
VSIZE('SCOTT')
--------------
5
NCS, APS / SITE 94
NVL Function:
Syntax:
select nvl(CN, value) from TN;
Example:
SQL> select seno, nvl(seno,0) from semp;
SENO NVL(SENO,0)
---------- -----------
0
1 1
1 1
0
4 4
4 4

6 rows selected.
NCS, APS / SITE 95
SET OPERATORS:

Union
Union all
Intersect
Minus

Syntax:
SELECT cn1, cn2 FROM TN1
set operator
SELECT cn3, cn4 FROM TN2;

NCS, APS / SITE 96


Example:
SQL> select * from fj1;
ENO NAM DNO
---------- --- ---
1 x cse
2 y cse
3 z eie

SQL> select * from fj2;


DNO DNAM
----- ---------
cse comp
mec mech
NCS, APS / SITE 97
SQL> select dno from fj1
2 union
3 select dno from fj2;
DNO
---
cse
eie
mec
SQL> select dno from fj1
2 union all
3 select dno from fj2;
DNO
---
cse
cse
eie
cse
mec NCS, APS / SITE 98
SQL> select dno from fj1
2 intersect
3 select dno from fj2;
DNO
---
cse
SQL> select dno from fj1
2 minus
3 select dno from fj2;
DNO
---
eie
SQL> select dno from fj2
2 minus
3 select dno from fj1;
DNO
---
mec
NCS, APS / SITE 99
Join:
To combine the data spread across tables
Performed by the ‘WHERE’ clause
Using Primary key, Foreign key columns
Types:
Simple Join
- Equi join
- Non-Equi join
Outer Join
- Left Outer Join
- Right Outer Join
- Full Outer Join
Self Join
NCS, APS / SITE 100
Syntax:
SELECT columns
FROM table1, table2
WHERE join conditions;

Equi Join:
SQL> select eno, name, a.dno, dname
2 from fj1 a, fj2 b
3 where a.dno = b.dno;

ENO NAM DNO DNAM


---- ------ ----- --------
1 x cse comp
2 y cse comp
NCS, APS / SITE 101
Natural Join
Syntax:
SELECT columns
FROM table1 NATURAL JOIN table2;

Example:
SQL> select eno, name, dno, dname
2 from fj1 natural join fj2 ;

ENO NAM DNO DNAM


---- ------ ----- --------
1 x cse comp
2 y cse comp

NCS, APS / SITE 102


Left Outer Join:
Syntax 1:
SELECT columns
FROM table1, table2
WHERE table1.cn = table1.cn (+);
Example 1:
SQL> select eno, name, a.dno, dname
2 from fj1 a, fj2 b
3 where a.dno = b.dno(+);
ENO NAM DNO DNAM
---- ------ ----- --------
1 x cse comp
2 y cse comp
3 z eie

NCS, APS / SITE 103


Syntax 2:
SELECT columns
FROM table1 LEFT OUTER JOIN table2
ON conditions;
Example 1:
SQL> select eno, name, a.dno, dname
2 from fj1 a left outer join fj2 b
3 on a.dno = b.dno;

ENO NAM DNO DNAM


---- ------ ----- --------
1 x cse comp
2 y cse comp
3 z eie

NCS, APS / SITE 104


Right Outer Join:
Syntax 1:
SELECT columns
FROM table1, table2
WHERE table1.cn (+) = table1.cn ;
Example 1:
SQL> select eno, name, a.dno, dname
2 from fj1 a, fj2 b
3 where a.dno (+) = b.dno;
ENO NAM DNO DNAM
---- ------ ----- --------
1 x cse comp
2 y cse comp
mech

NCS, APS / SITE 105


Syntax 2:
SELECT columns
FROM table1 RIGHT OUTER JOIN table2
ON conditions;
Example 1:
SQL> select eno, name, a.dno, dname
2 from fj1 a right outer join fj2 b
3 on a.dno = b.dno;

ENO NAM DNO DNAM


---- ------ ----- --------
1 x cse comp
2 y cse comp
mech

NCS, APS / SITE 106


Full Outer Join:
Syntax :
SELECT columns
FROM table1 FULL OUTER JOIN table2
ON conditions;
Example :
SQL> select eno, name, a.dno, dname
2 from fj1 a full outer join fj2 b
3 on a.dno = b.dno;
ENO NAM DNO DNAM
---- ------ ----- --------
1 x cse comp
2 y cse comp
3 z eie
mech
NCS, APS / SITE 107
SELF JOIN

SQL> select * from semp;

ENO ENAME SENO DNO SAL


---------- ---------- ---------- ----- ----------
1 kha cse 1000
2 pkr 1 cse 200
3 ncs 1 cse 500
4 sna mech 1000
5 cra 4 mech 300
6 kkn 4 mech 300

6 rows selected.

NCS, APS / SITE 108


SQL> select a.eno, a.ename supervisee, b.eno,
2 b.ename supervisor, a.dno, a.sal
3 from semp a, semp b
4 where a.seno=b.eno;

ENO SUPERV ENO SUPERV DNO SAL


------- ---------- -------- ----------- ------ -------
2 pkr 1 kha cse 200
3 ncs 1 kha cse 500
5 cra 4 sna mech 300
6 kkn 4 sna mech 300

NCS, APS / SITE 109


VIEW:
Syntax:
CREATE VIEW view_name AS
SELECT command;

Example:

SQL> select * from emp1;


ENO ENAM DNO
------ ---------- ----------
1x 10
2y

NCS, APS / SITE 110


SQL> create view v1 as
2 select * from emp1
3 where dno=10;
View created.
SQL> select * from v1;
ENO ENAM DNO
------ ---------- ----------
1x 10
SQL> insert into v1 values (6,'r',10);
1 row created.
SQL> insert into v1 values (7,'n',20);
1 row created.

NCS, APS / SITE 111


SQL> select * from emp1;
ENO ENAM DNO
------ ---------- ----------
1x 10
2y
6r 10
7n 20
SQL> select * from v1;
ENO ENAM DNO
------ ---------- ----------
1x 10
6r 10

NCS, APS / SITE 112


SQL> select * from dept1;
DNO DNAME
------ ----------
10 cse
30 mech
40 ece

SQL> create view v2 as


2 select eno, ename, emp1.dno, dname
3 from emp1, dept1
4 where emp1.dno = dept1.dno;
View created.

NCS, APS / SITE 113


SQL> select * from v2;
ENO ENAM DNO DNAME
---------- --------- ---------- -----------
1 x 10 cse
6 r 10 cse

SQL> insert into v2 values (8,'i',10,'cse');


insert into v2 values (8,'i',10,'cse')
*
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-
preserved table

NCS, APS / SITE 114


PL/SQL
Procedural language SQL

SQL statements combined with procedural constructs

*** Before running the PL/SQL block the following


command should be given to enable the output

SQL>SET SERVEROUTPUT ON;

NCS, APS / SITE 115


PL/SQL Block (Syntax):
DECLARE

Local declarations;

BEGIN

executable statements;

EXCEPTION

exception handlers;

END;

NCS, APS / SITE 116


Attributes
%type – used to refer to the database columns

%rowtype – represents a row in table

Syntax:

variablename tablename.columnname<attribute>

Example:

r student.rollno%type;

y student%rowtype;

NCS, APS / SITE 117


Control Structures:
Conditional control

- if then

- if then else

- if then elsif

Iterative control

- Simple loop

- For loop

- While loop

NCS, APS / SITE 118


Conditional Control:
Syntax:
IF condition THEN

statements;

ELSIF

statements;

END IF;

NCS, APS / SITE 119


Example:
declare
a emp1.age%type;
e emp1.eno%type;
begin
e:=&e;
select age into a from emp1 where eno=e;
if a>18 then
update emp1 set status = 'major' where eno=e;
else
update emp1 set status = 'minor' where eno=e;
end if;
dbms_output.put_line('updated');
end;
/
NCS, APS / SITE 120
declare
a emp1.age%type;
e emp1.eno%type;
begin
e:=&e;
select age into a from emp1 where eno=e;
if (a>9 and a<15) then
update emp1 set category = 'school' where eno=e;
elsif (a>15 and a<25) then
update emp1 set category = 'college' where eno=e;
else
update emp1 set category = 'company' where eno=e;
end if;
dbms_output.put_line('updated');
end;
/
NCS, APS / SITE 121
Simple loop:
Syntax:
LOOP
statements;
EXIT WHEN condition;
END LOOP;

declare
a number:=100;
begin
loop
a:=a+25;
exit when a=250;
end loop;
dbms_output.put_line(a);
end;
NCS, APS / SITE 122
WHILE loop
WHILE condition
LOOP
statements;
END LOOP;
declare
i number:=0;
j number:=0;
begin
while i<100 loop
j:=j+1;
i:=i+2;
dbms_output.put_line(i||','||j);
end loop;
end;
/
NCS, APS / SITE 123
FOR loop
FOR variable IN [REVERSE] initial value . . final value
LOOP
statements;
END LOOP;
declare
i number:=0;
j number:=0;
begin
for i in 1..10
loop
j:=j+1;
dbms_output.put_line(i+2||','||j);
end loop;
end;
NCS, APS / SITE 124
SQL> select * from student;

ROLLNO NAME MARK


---------- --------------- ---------
1 arya 35
2 pooja 36
3 ajith 32
4 shalini 37
5 surya 38
6 jho 33

6 rows selected.
NCS, APS / SITE 125
SQL> declare
2 r student.rollno%type;
3 n student.name%type;
4 begin
5 select rollno,name into r,n from student
6 where mark=35;
7 dbms_output.put_line(r);
8 dbms_output.put_line(n);
9 exception
10 when no_data_found then
11 dbms_output.put_line('such an item not available');
12 end;
13 /
1
arya

PL/SQL procedure successfully completed.


NCS, APS / SITE 126
SQL> declare
2 r student.rollno%type;
3 n student.name%type;
4 begin
5 select rollno,name into r,n from student
6 where mark=34;
7 dbms_output.put_line(r);
8 dbms_output.put_line(n);
9 exception
10 when no_data_found then
11 dbms_output.put_line('such an item not available');
12 end;
13 /
such an item not available

PL/SQL procedure successfully completed.

NCS, APS / SITE 127


CURSOR:
Cursor is the pointer to the temporary area (context area) created for storing
the data manipulated by a PL/SQL program

Cursor Processing:
Declare the cursor
CURSOR cursor_name IS select statement;
Open the cursor for a query
OPEN cursor_name;
Fetch the results into PL/SQL variables
FETCH cursor_name INTO list_of_variables;
Close the cursor
CLOSE cursor_name;

NCS, APS / SITE 128


Cursor Attributes:
%notfound ,
%found,
%rowcount,
%isopen
Example:
declare
cursor a is select * from stu;
aa stu%rowtype;
begin
if a%isopen then
dbms_output.put_line('cursor opened');
else
dbms_output.put_line('Cursor not opened');
end if;
NCS, APS / SITE 129
open a;
loop
fetch a into aa;
exit when a%notfound;
dbms_output.put_line('Fetched rows '||a%rowcount);
end loop;
if a%isopen then
dbms_output.put_line('cursor opened');
else
dbms_output.put_line('Cursor not opened');
end if;
close a;
if a%isopen then
dbms_output.put_line('cursor opened');
else
dbms_output.put_line('Cursor not opened');
end if;
NCS, APS / SITE 130
end;
declare
cursor c1 is select eno,age from emp1;
id emp1.eno%type;
a emp1.age%type;
ag emp1.age%type;
nu number;
begin
nu := &nu;
ag:=0;
open c1;
loop
fetch c1 into id, a;
exit when c1%notfound;

NCS, APS / SITE 131


if (nu = id) then
ag := a;
dbms_output.put_line(a);
end if;
end loop;
if (ag = 0) then
dbms_output.put_line('no not available');
end if;
close c1;
end;
Enter value for nu: 1
old 9: nu := &nu;
new 9: nu := 1;
26
PL/SQL procedure successfully completed.
NCS, APS / SITE 132
declare
cursor c1 is select eno,age from emp1;
sn emp1.eno%type;
a1 emp1.age%type;
begin
open c1;
loop
fetch c1 into sn,a1;
exit when c1%notfound;
if a1>18 then
update emp1 set status='major‘ where eno=sn;
else
update emp1 set status='minor‘ where eno=sn;
end if;
end loop;

NCS, APS / SITE 133


dbms_output.put_line(c1%rowcount||' rows are updated');
close c1;
end;
/
6 rows are updated
PL/SQL procedure successfully completed.

SUBPROGRAMS
Subprograms are PL/SQL block that can be created and invoked
whenever required

* Procedure

* Function

NCS, APS / SITE 134


PROCEDURE

Procedure is the subprogram that does not return any value

Syntax:
CREATE OR REPLACE PROCEDURE proc_name(parameters) IS
local declarations;
BEGIN
executable statements;
EXCEPTION

exception handlers;
END;

NCS, APS / SITE 135


create or replace procedure mark(snum number) is
m1 number;
m2 number;
begin
select mark1,mark2 into m1,m2
from student
where sno = snum;
If m1<m2 then
update student set mark3 = m1+m2 where sno = snum;
else
dbms_output.put_line('no update');
end if;

NCS, APS / SITE 136


exception
when no_data_found then
dbms_output.put_line ('no data found');
end;

To Execute
exec proc_name (parameter values);

Parameter specification in list:


in – value passed
out – value returned
inout—value in and out

NCS, APS / SITE 137


create or replace procedure t3
(a in stu.regno%type,b out varchar) is
m2 number;
begin
select c2 into m2 from stu where regno=a;
if m2<25 then
b:='fail';
else
b:='pass';
end if;
end;
/

NCS, APS / SITE 138


SQL> variable v varchar2(7);
SQL> print v;
V
--------------------------------

SQL> exec t3(4,:v);


PL/SQL procedure successfully completed.

SQL> print v;
V
--------------------------------
fail

NCS, APS / SITE 139


create or replace procedure t4(a in out number) is
m1 number;
m2 number;
begin
select c1,c2 into m1,m2 from stu where regno=a;
if m2<25 then
a:=m2;
else
a:=m1;
end if;
end;
/

NCS, APS / SITE 140


SQL> variable d number;
SQL> begin
2 :d := 1;
3 end;
4 /
PL/SQL procedure successfully completed.
SQL> print d;
D
----------
1
SQL> execute t4( :d);
PL/SQL procedure successfully completed.
SQL> print d;
D
----------
27
NCS, APS / SITE 141
SQL> create or replace procedure fib (n number) is
2 f1 number;
3 f2 number;
4 i number;
5 c number;
6 begin
7 f1 := 0;
8 f2 := 1;
9 dbms_output.put_line(f1);
10 dbms_output.put_line(f2);
11 for i in 3 .. n
12 loop
13 c := f1+f2;
14 dbms_output.put_line(c);

NCS, APS / SITE 142


15 f1 := f2;
16 f2 := c;
17 end loop;
18 end;
19 /
Procedure created.
To execute the procedure
SQL> exec fib(&n);
Enter value for n: 5
0
1
1
2
3
PL/SQL procedure successfully completed.

NCS, APS / SITE 143


FUNCTION:
Function is a subprogram which returns a value.
Syntax:
CREATE OR REPLACE FUNCTION fun_name (parameters)

RETURN datatype IS

local declarations;

BEGIN

executable statements;

EXCEPTION

exception handlers;

END;

NCS, APS / SITE 144


create or replace function fact (num number)
return number is
i number;
f number;
begin
if (num=0 or num=1) then
return(1);
else
f:=1;
for i in 1 .. num
loop
f := f*i;
end loop;
return f;
end if;
end;
NCS, APS / SITE 145
SQL> declare
2 a number;
3 begin
4 a:=&a;
5 dbms_output.put_line( fact(a));
6 end;
7 /
Enter value for a: 4
old 4: a:=&a;
new 4: a:=4;
24
PL/SQL procedure successfully completed.
SQL> select fact(8) from dual;
FACT(8)
----------
40320
NCS, APS / SITE 146
create or replace function grt(a number)
return number is
m1 number;
m2 number;
begin
select c1,c2 into m1,m2 from stu where regno=a;
if m1>m2 then
return m1;
else
return m2;
end if;
end;
/
NCS, APS / SITE 147
TRIGGERS:
It is a stored procedure which is fired when any manipulation on the specified
table.
Syntax:
CREATE OR REPLACE TRIGGER trig_name

BEFORE/AFTER INSERT/UPDATE/DELETE ON table name

FOR EACH STATEMENT/ FOR EACH ROW

DECLARE

local decl.;

BEGIN

executable statements;

END;
NCS, APS / SITE 148
Variable names used in triggers
*two are used :old and :new
- old specifies the row value before change
- new specifies the value after change

Example:
create or replace trigger tot
before insert on stu
for each row
begin
:new.total := :new.c1 + :new.c2;
end;

NCS, APS / SITE 149


create or replace trigger del1
before delete on dept1
for each row
begin
delete from emp1
where dno = :old.dno;
end;

create or replace trigger ins


before insert on emp1
for each row
begin
insert into dept1(dno) values (:new.dno);
end;
NCS, APS / SITE 150
create or replace trigger insc
after insert on dept1
for each row
begin
insert into emp1(dno) values (:new.dno);
end;

NCS, APS / SITE 151

You might also like