1) SQL Running Notes
1) SQL Running Notes
=========
Topic-1 : DBMS(17-06-2022)
==========================
What is Data?
- data is raw fact(there is no meaning).
Ex:
smith 10021
What is Information?
- processing data is called as "information".
Ex: CustomerNames CustomerID
============ ===========
smith 10021
- information is always provide meaning full statements.
What is Database?
- it is a collection of interrelated data/ information that has been organized in proper
systematically(i.e table) manner.
What is DBMS?
- it is a s/w which is used to manage and maintain data/ information in database.
- by using DBMS s/w we can do,
> create database(memory)
> stored data/information
> manipulate data/information
> retrieving data / information
> deleting data / information
2. flat file:
=============
- data can stored in file with the help of OS.
Disadvantages:
==============
i) Data redundancy
ii) Data inconsistency
iii) Data retrieval
iv) Data integrity
v) Data security
vi) Data indexing
i) Data redundancy:
====================
- storing same information in multiple files in computer.
1
ii) Data inconsistency:
=======================
- once we change any modifications in one file then the corresponding copy file will not effected
this problem is called as "data inconsistency".
v) Data security:
=================
- there is no security for flat file data.
Note: to overcome the disadvantages of flat file and books & papers we use a concept is called as "DBMS"
(database management system).
What is DBMS?
- it is a s/w which is used to manage and maintain data/information in database.
- by using DBMS s/w we can do,
> create database(memory)
> stored data/information
> manipulate data/information
> retrieving data / information
> deleting data / information
What is Database?
- it is a collection of interrelated data/ information that has been organized in proper
systematically(i.e table) manner.
Types of databases?
===================
- there are two types databases in real world.
1. OLTP:
========
- these databases are used for storing "day-to-day" transactional data/information for running
business.
2
- we can perform live operations(insert,update,delete,small data select)
Ex: oracle,sqlserver,mysql,db2,sybase,..........etc
Ex: Banking
x-customer open new a/c: 21-05-2015
25-05-2015:
===========
day-1 :Deposite transaction,Withdraw transaction:
2. OLAP:
========
- these databases are used for storing "historical data / big data".
- we can perform only operation i.e "select" operation.
Models of DBMS:
===============
1. Hierarchical database management system(HDBMS)
Ex: IMS s/w (Information management system)
2. Network database management system(NDBMS)
Ex: IDBMS s/w (Integrated database management system)
Ex s/w : Oracle,sqlserver,mysql,db2,sybase,informix,ingrees,teradata,maxdb.....etc
Ex s/w : MongoDB,Cassandra.....etc
====================================================================
Topic-2: ORACLE
======== =======
- oracle is a rdbms(ordbms) product/ DB software/ back end tool from "oracle corporation" in 1979.
- it is used to store data/information permanently
3
(i.e HD) along with security.
- it can deployee(install) in any operating system
like windows,linux,unix,mac,solaries....etc
- so that oracle is a platform independent an RDBMS product.
Versions of oracle:
===================
from oracle 1.0 --------- oracle19C version.
file1 file2
====== =====
y x ---- inconsistency
y y ---- consistency
Ex: recyclebin,falshback,purge,
partition tables.....etc are not allowed.
Note:
=====
- there are two components are installed in system.
1. client component
2. server component
1. client component:
====================
- a user can perform 3 operations:
i) connect to oracle server
ii) to send request to oracle server
iii) to get response from oracle server
Ex:
===
sqlplus,toad,sql developer,pl/sql developer....etc
4
2. server component:
====================
- it again having two more sub components are,
i) instance
ii) database
i) instance:
============
- it is a temporary memory
- data can be stored in temporary.
- this component memory is allocating by system from RAM.
ii) database:
=============
- it is permanent memory
- allocating by system from HD.
- data can be stored permanent.
NOTE:
=====
- Now a user want to work on oracle db then we follow two steps mechanism.
SQLplus vs SQL:
===============
sqlplus sql
======= =====
1. it is a db tool. it is db language.
solution:
=========
- go to services
- go to oracleserviceORCL and click on it
> go to select "startup type" is "automatic"
> click on "start" button
> click on ok.
problem-2:
==========
Enter user-name: system/tiger
solution:
=========
- go to click on sqlplus
- enter username : \sys as sysdba
- enter password : sys
connected.
SQL> CONNECT
ENTER USERNAME : system
ENTER PASSWORD : tiger
CONNECTED.
Ex:
SQL> CREATE USER MYDB4PM IDENTIFIED BY ABC;
6
User created.
NOTE:
=====
- every new user is called as dummy user in oracle because this user is not having any privilege
(permissions) like connect,create table,insert data, .....etc.so that admin should given permissions to new
user with help of "grant" command.
- every new user is called as "schema" in oracle.whereas schema is nothing but it is a collection of
objects such as "tables,views,synonyms,procedure,triggers,....etc".
ex:
grant connect to MYDB4PM;
SQL> CONN
Enter user-name: MYDB4PM/ABC
Connected.
Ex:
Enter user-name: system/tiger
Connected.
SQL> ALTER USER MYDB4PM IDENTIFIED BY MYDB4PM;
7
Mr.Aravind
9154898074
Topic-3: SQL
======== ====
- sql is a db language which was introduced by "IBM".it is used to communicate with DB.
- sql is not case sensitive language that means we can write sql queries in either upper case / lower
case / combination of upper & lower cases.
Ex:
SELECT * FROM EMPLOYEE;----executed
select * from emp;----executed
SelecT * From Emp;----executed
- every sql query should ends with ";" semicolon.
New features:
=============
> recyclebin
> flashback
> purge
New commands:
============
- insert all
- merge
8
4. Transaction Control Language(TCL):
======================================
- commit
- rollback
- savepoint
numeric datatypes:
===================
i) int
ii) number(p,s)
i) int:
======
- storing integer format values only.
Ex:
SNO int --------> SNO number(38)
SNO number(5)
==============
0
12
121
9999
10000
99999
ii) number(p,s):
=================
- storing integer and also float values.
9
P(precision)
============
- counting all digits including left & right digits of decimal expression.
Ex:
56.25 precision = 4
8734.45 precision = 6
987970.134 precision = 9
S(scale):
=========
- counting the right side digits only.
Ex:
56.25 scale = 2 precision = 4
8734.45 scale = 2 precision = 6
97978960.6534 scale = 4 precision = 12
Ex:
price number(7,2)
=================
0.0 -----9999.99
10000.00
99999.99
Ex:
Name char(10)
=============
smith ----> error
'smith'---> allowed
10
Ex: pancardno,mailid,password,..
'[email protected]','sai@24'.
1. Non-unicode datatypes
> are storing "localized data".(i.e english lang.only)
i) char(size)
ii) varchar2(size)
2. Unicode datatypes
> are storing "globalized data"(i.e all national lang's)
i) Nchar(size)
ii) Nvarchar2(size)
i) char(size):
==============
- it fixed length datatype.(static)
- max. size is 2000 bytes
- 1 char = 1 byte.
- wasted memory
ename char(10)
==============
'hello'----> hello (5 bytes / 10 bytes = 5 bytes(wasted))
ii) varchar2(size):
===================
- it is a variable length datatype.(dynamic)
- max.size 4000 bytes
- 1 char = 1 byte
- save memory
Ex:
ename varchar2(10)
=================
'hello'----> hello (5 bytes / 5 bytes = 0 bytes(wasted))
'hel' -----> hel( 3 bytes / 3 bytes = 0 bytes)
'he' ------> he (2 bytes / 2 bytes = 0 bytes)
i) Nchar(size):
11
===============
- it fixed length datatype.(static)
- max. size is 2000 bytes
- 1 char = 1 byte.
- wasted memory
- storing unicode char's(i.e all national language's char's)
ii) Nvarchar2(size):
=====================
- it variable length datatype.(dynamic)
- max. size is 4000 bytes
- 1 char = 1 byte.
- saved memory
- storing unicode char's(i.e all national language's char's)
Long datatype:
==============
- it is a variable length datatype(dynamic)
- max size 2GB.
- storing non-unicode & unicode char's.
- 1 char = 1 byte
- a table is having only one long datatype column.
Date datatypes:
===============
- storing date & time information.
i) date:
========
- can store date & time information of a particular day.
- here time is optional.when user not insert time information
then system will take '00:00:00 am' (or) '12:00:00 am' by
default.
- oracle database default date format is
'dd-mon-yyyy/yy hh:mi:ss am/pm'
1 1 2 1 1 1 ---------> 7 bytes
ii) timestamp:
==============
- can store date & time along with milliseconds.
12
- are storing image file / audio file / video files in the form of 01010100101010010100 binary
format.
LOB datatypes:
==============
- large objects datatypes.
i) CLOB:
========
- character large object.
- can store non-unicode char's.
- max size is 4gb.
ii) NCLOB:
==========
- National character large object.
- can store unicode char's(all natonal lang's)
- max size is 4gb
iii) BLOB:
==========
- binary large object.
- store image/audio/video files in the form of
10010101010100 binary format.
- max size is 4gb.
non-unicode char's:
===================
char(size) -2000 bytes
varchar2(size) -4000 bytes
long -2gb
Clob - 4gb
unicode char's:
===================
Nchar(size) - 2000 bytes
Nvarchar2(size) - 4000 bytes
long - 2gb
NClob - 4gb
binary data:
============
raw - 2000 bytes
long raw - 2gb
Blob - 4gb
=============================================================
13
DDL:
====
create:
=======
- is used to create a new db object such as tables, views, synonyms, sequences, procedure,
functions,.....etc
step1:
======
username : system/tiger(admin)
step2:
======
create user mydb4pm identified by mydb4pm;
step3:
======
grant connect to mydb4pm;
grant create table to mydb4pm;
step4:
======
username : mydb4pm/mydb4pm(user)
EX:
create table students(stid int,sname char(10),sfee number(6,2)) )
to view the structure of a table in oracle:
===========================================
syntax:
=======
desc <table name>; (desc = describe)
Ex:
SQL> DESC STUDENTS;
to view list of tables in oracle:
================================
syntax:
=======
select * from tab;
Ex:
select * from tab;
2) ALTER:
=========
- is used to change the structure of a table.
14
- this command is having 4 sub commands those are,
i) Alter - Modify:
==================
- to change datatype and size of datatype of a particular column in a table.
syntax:
=======
alter table <table name> modify <column name> <new datatype>[new size];
EX:
SQL> ALTER TABLE STUDENTS MODIFY SNAME VARCHAR2(5);
syntax:
=======
alter table <table name> add <new column name> <datatype>[size];
EX:
SQL> ALTER TABLE STUDENTS ADD SADDRESS VARCHAR2(10);
syntax:
=======
alter table <table name> rename <column> <old column name> to <new column name>;
EX:
SQL> ALTER TABLE STUDENTS RENAME COLUMN SNAME TO STUDENTNAME;
syntax:
=======
alter table <table name> drop <column> <column name>;
EX:
SQL> ALTER TABLE STUDENTS DROP COLUMN SFEE;
3) RENAME:
==========
- to change a table name.
syntax:
15
=======
rename <old table name> to <new table name>;
EX:
SQL> RENAME STUDENTS TO SDETAILS;
SQL> RENAME SDETAILS TO STDUENTS;
4) TRUNCATE:
============
- to delete all rows but not columns from a table.
- permanent rows deletion. (we cannot restore)
- cannot delete a specific row because it doesn’t support "where" condition.
syntax:
=======
truncate table <table name>;
Ex:
SQL> TRUNCATE TABLE STUDENTS;
5) DROP:
========
- to drop / delete a table(i.e rows x columns) from database.
syntax:
=======
drop table <table name>;
EX:
DROP TABLE STUDENTS;
NOTE:
=====
from oracle10g enterprise edition once we drop a table from a database i.e temporary.so that we
can restore deleted table into database by using following commands are.
1. recyclebin:
==============
- it is similar to windows recyclebin in computer.
- it is a pre-defined / system defined table in oracle.
which is used to store the information about dropped tables.
EX:
SQL> DESC RECYCLEBIN;
16
To view the information of dropped tables in recyclebin:
=========================================================
syntax:
=======
select object_name,original_name from recyclebin;
EX:
SQL> SELECT OBJECT_NAME,ORIGINAL_NAME FROM RECYCLEBIN;
OBJECT_NAME
ORIGINAL_NAME
--------------------------------- -----------------------------------------------
BIN$37vn0OMvT0Cc7M3TIV9viA==$0 STUDENTS
2.FLASHBACK:
============
- this command is used to restore deleted tables into db memory.
syntax:
=======
flashback table <table name> to before drop;
Ex:
SQL> FLASHBACK TABLE STUDENTS TO BEFORE DROP;
3. PURGE:
=========
-this command is used to delete / drop a table permanently.
EX:
SQL> PURGE TABLE TEST1;
EX:
PURGE RECYCLEBIN;
17
drop table <table name> purge;
EX:
DROP TABLE STUDENTS PURGE;
NOTE:
=====
- here "recyclebin,flashback,purge are introduced in oracle10g enterprise edition".
syntax1:
========
insert into <table name> values(v1,v2,.....);
EX:
SQL> INSERT INTO EMP(EID)VALUES(1023);
SQL> INSERT INTO EMP(EID,ENAME)VALUES(1024,'WARD');
SQL> INSERT INTO EMP(EID,ENAME,SAL)VALUES(1025,'MILLER',18000);
SQL> INSERT INTO EMP(SAL,EID,ENAME)VALUES(18000,1026,'JONES');
NOTE:
=====
- in this method we can insert values for required columns only and missing columns will take "null"
by default.
syntax1:
========
insert into <tn> values(&col1,&col2,......);
EX:
SQL> INSERT INTO EMP VALUES(&EID,'&ENAME',&SAL);
Enter value for eid: 1026
Enter value for ename: SCOTT
Enter value for sal: 35000
18
SQL> / (TO RE-EXECUTE THE LAST EXECUTED SQL QUERY IN SQLPLUS EDITIOR)
SQL> /
..............................................................................
syntax2:
========
insert into <tn>(col1,col2,....)values(&COL1,...);
EX:
SQL> INSERT INTO EMP(EID)VALUES(&EID);
Enter value for eid: 1029
SQL> /
........................
=============================================================================
DQL/DRL:
========
i) select:
==========
- to retrieving all rows from a table at a time.
(or)
- to retrieving a specific row by using "where" condition.
syntax:
=======
select * / <list of columns> from <table name> [ where <condition> ];
Here, " * " ----- all columns in a table.
EX:
SELECT * FROM DEPT;
(OR)
SELECT DEPTNO,DNAME,LOC FROM DEPT;
NOTE:
=====
- when we want to display data in proper systematically order of a big data tables in sql plus
environment then we need to set the following properties are
1) pagesize n:
===============
19
- by default a page can have 14 rows.
- "n" ---- no.of rows in a page.
- maximum size of pagesize property is 0-50000.
syntax:
=======
sql> set pagesize n;
2) lines n:
===========
- by default each line will occupied 80 bytes of memory.
- here "n" no.of bytes in each line.
- maximum bytes of each line is 32767 bytes.
syntax:
=======
set lines n;
ex: set lines 100;
ALIAS NAMES:
============
- it is a temporary name.
- we can create alias names on two level in DB.
i) column level alias: - created alias name on columns.
================
ii) table level alias: - created alias name on table.
==============
syntax:
=======
select <column name1> <column alias name1>,
<column name2> <column alias name2>,......
from <table name> <table alias name>;
EX:
SQL> SELECT DEPTNO X,DNAME Y,LOC Z FROM DEPT D;
CONCATENATION OPERATOR( || ):
=============================
- adding two or more than two string expressions.
syntax:
========
<string1>||<string2>||<string3||......
EX:
SQL> SELECT 'Mr.'||ENAME||' '||'WORKING AS A'||' '||JOB FROM EMP;
OUTPUT:
=======
Mr.SMITH WORKING AS A CLERK
DISTINCT KEYWORD: - to eliminate duplicate values from a column.
==================
20
syntax: distinct <column name>
=======
EX:
SQL> SELECT DISTINCT JOB FROM EMP;
SQL> SELECT DISTINCT DEPTNO FROM EMP ORDER BY DEPTNO;
EX:
SQL> CREATE TABLE NEWDEPT1 AS SELECT * FROM DEPT;
(OR)
SQL> CREATE TABLE NEWDEPT1 AS SELECT * FROM DEPT WHERE 1=1;
EX:
SQL> CREATE TABLE NEWDEPT2 AS SELECT * FROM DEPT WHERE 1=2;
EX:
SQL> CREATE TABLE NEWEMP1 AS SELECT EMPNO,ENAME,SAL FROM EMP;
21
insert into <destination table name> select * from <source table name>;
rules:
======
1. no.of column in both tables should same.
2. order of columns and datatypes of columns in both tables must match.
EX:
SQL> INSERT INTO NDEPT2 SELECT * FROM DEPT;
INSERT ALL:
===========
- insert all command is used to insert rows into multiple table but rows must be an existing table.
syntax:
=======
insert all into <tn1> values(<col1>,<col2>,......)
into <tn2> values(<col1>,<col2>,.................)
into <tn3> values(<col1>,<col2>,.................)
..................................................
..................................................
into <tn n> values(<col1>,<col2>,................)
select * from <old table name>;
EX:
SQL> INSERT ALL INTO TEST1 VALUES(DEPTNO,DNAME,LOC)
INTO TEST2 VALUES(DEPTNO,DNAME,LOC)
INTO TEST3 VALUES(DEPTNO,DNAME,LOC)
SELECT * FROM DEPT;
1. pre-defined functions:
=========================
i) single row functions (scalar functions)
ii) multiple row functions(grouping / aggregative functions)
22
> numeric functions
> string / character functions
> date functions
> conversion functions
> analytical functions
What is dual?
=============
- pre-defined table.
- is also called as a "dummy table" in oracle.
- use to test function functionalities.
- is having only a single row & a single column.
Numeric functions:
===================
i) abs():
=========
- to convert (-ve) values into (+ve) values.
syntax: abs(n)
=======
EX:
SQL> SELECT ABS(-11) FROM DUAL;
ABS(-11) = 11
----------
EX:
SQL> SELECT ENAME,SAL,COMM,ABS(COMM-SAL) RESULT FROM EMP;
ii) ceil():
===========
- it return a value which is greater than or is equals to the given expression.
syntax: ceil(n)
=======
EX:
SQL> SELECT CEIL(9.0) FROM DUAL;
CEIL(9.0) = 9
----------
23
SQL> SELECT CEIL(9.3) FROM DUAL;
CEIL(9.3) = 10
----------
SQL> SELECT CEIL(9.8) FROM DUAL;
CEIL(9.8) = 10
----------
iii) floor():
=============
- it return a value which is less than or is equals to the given expression.
syntax: floor(n)
=======
EX:
SQL> SELECT FLOOR(9.0) FROM DUAL;
FLOOR(9.0) = 9
----------
SQL> SELECT FLOOR(9.3) FROM DUAL;
FLOOR(9.3) = 9
----------
SQL> SELECT FLOOR(9.8) FROM DUAL;
FLOOR(9.8) = 9
----------
24
NOTE:
=====
if an expression is having less than 0.5 then add 0 to given expression.
if an expression is having greater / is equals to then add 1 to given expression.
0.3 < 0.5 ---> adding 0
0.5 >= 0.5 ---> adding 1
0.6 >= 0.5 ---> adding 1
Functions in oracle:
-------------------------------------
> To Perform Task & Must Return Value.
> Oracle Supports Two Types Functions. Those Are
1) Pre-Define / Built in Functions (Use in Sql & Pl/Sql)
2) User Define Functions (Use in Pl/Sql)
1) Pre-Define Functions:
---------------------------------------------
> These Are Again Classified into Two Categories.
A) Single Row Functions (Scalar Functions)
B) Multiple Row Functions (Grouping Functions)
Single Row Functions:
--------------------------------------------
> These Functions Are Returns A Single Row (Or) A Single Value.
> Numeric Functions
> String Functions
> Date Functions
> Conversion Functions
How To Call a Function:
------------------------------
Syntax:
---------------
Select <Fname>(Values) From Dual;
What Is Dual:
------------------------
> Pre-Define Table In Oracle.
> Having Single Column & Single Row
> Is Called As Dummy Table In Oracle.
> Testing Functions (Pre-Define & User Define) Functionalities.
To View Strc.Of Dual Table:
----------------------------------------------------
Sql> Desc Dual;
To View Data Of Dual Table:
----------------------------------------------------
Sql> Select * From Dual;
Numeric Functions:
--------------------------------------
1) Abs():
> Converts (-Ve) Value Into (+Ve) Value.
Syntax:
---------------
Abs(Number)
Ex:
25
Sql> Select Abs(-12) From Dual; --------> 12
Sql> Select Ename,Sal,Comm,Abs(Comm-Sal) From Emp;
2) Ceil():
> Returns A Value Which Is Greater Than Or Equal To Given Value.
Syntax:
---------------
Ceil(Number)
Ex:
Sql> Select Ceil(9.0) From Dual;------9
Sql> Select Ceil(9.3) From Dual;-------10
3) Floor():
Syntax:
Floor(Number)
Ex:
Sql> Select Floor(9.0) From Dual;------9
Sql> Select Floor(9.8) From Dual;------9
4) Mod():
Returns Remainder Value.
Syntax:
Mod(M,N)
Ex:
Sql> Select Mod(10,2) From Dual;-------0
5) Power():
The Power Of Given Expression
Syntax:
Power(M,N)
Ex:
Sql> Select Power(2,3) From Dual;----------8
Round():
> Nearest Value Given Expression.
Syntax:
Round(Number,[Decimal Places])
Ex:
Sql> Select Round(5.50) From Dual;------6
Sql> Select Round(32.456,2) From Dual;------32.46
Trunc:
-------
> Returns A Value Which Will Specified Number Of Decimal Places.
Syntax:
Trunc(Number,Decimal Places)
Ex:
Sql> Select Trunc(5.50) From Dual;---------5
Sql> Select Trunc(32.456,2) From Dual;----32.45
String Functions:
--------------------
Length():
------------------
> Length Of Given String.
Syntax:
26
Length(String)
Ex:
Sql> Select Length('Hello') From Dual;------------------------5
Sql> Select Length('Good Morning') From Dual;--------12
Sql> Select Ename,Length(Ename) From Emp;
Sql> Select * From Emp Where Length(Ename)=4;
Lower():
----------------
To Convert Upper Case Char's Into Lower Case Char's.
Syntax:
Lower(String)
Ex:
Sql> Select Lower('Hello') From Dual;
Sql> Update Emp Set Ename=Lower(Ename) Where Job='Clerk';
Upper():
---------------
Syntax:
Upper(String)
Ex:
Sql> Select Lower('Hello') From Dual;
Initcap():
------------------
To Convert First Char. Is Capital.
Syntax:
Initcap(String)
Ex:
Sql> Select Initcap('Hello') From Dual;
Sql> Select Initcap('Good Morning') From Dual;
Ltirm():
---------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Left
Side
Of Given String.
Syntax:
Ltrim(String1[,String2])
Ex:
Sql> Select Ltrim(' Sai') From Dual;
Sql> Select Ltrim('Xxxxxxsai','X') From Dual;
Sql> Select Ltrim('123SAI','123') From Dual;
Rtrim():
---------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Right Side Of Given String.
Syntax:
Rtrim(String1[,String2])
Ex:
Sql> Select Rtrim('Saixxxxxxx','X') From Dual;
Trim():
------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Both Sides Of Given String.
Syntax:
27
----------------
Trim('Trimming Char' From 'String')
Ex:
Sql> Select Trim('X' From 'Xxxxxxsaixxxx') From Dual;
Lpad():
------------
To Fill A String With Specific Char. On Left Side Of Given
String.
Syntax:
---------------
Lpad(String1,Length,String2)
Ex:
Sql> Select Lpad('Hello',10,'@') From Dual;
@@@@@Hello
Rpad():
-------------
To Fill A String With Specific Char. On Right Side Of Given
String.
Syntax:
---------------
Rpad(String1,Length,String2)
Ex:
Sql> Select Rpad('Hello',10,'@') From Dual;
Hello@@@@@
Concat():
-----------------
Adding Two String Expressions.
Syntax:
--------------
Concat(String1,String2)
Ex:
Sql> Select Concat('Good','Bye') From Dual;
Replace():
-------------------
To Replace One String With Another String.
Syntax:
---------------
Replace(String1,String2,String3)
Ex:
Sql> Select Replace('Hello','Ell','Xyz') From Dual;
Hxyzo
Sql> Select Replace('Hello','L','Abc') From Dual;
Heabcabco
Translate():
------------------------
To Translate A Single Char With Another Single Char.
Syntax:
--------------
Translate(String1,String2,String3)
28
Ex:
Sql> Select Translate('Hello','Elo','Xyz') From Dual;
Hxyyz
Sol: E = X , L=Y , O=Z
Hello => Hxyyz
Ex:
Sql> Select Ename,Sal,Translate(Sal,'0123456789','$B@Gh*V#T%')
Salary From Emp;
Ename Sal Salary
---------- --------------- -------------------------
Smith 800 T$$
Sol: 0=$,1=B,2=@,3=G,4=H,5=*,6=V,7=#,8=T,9=%.
Substr():
-----------------
It Returns Req.Substring From Given String Expression.
Syntax:
---------------
Substr(String1,<Starting Position Of Char.>,<Length Of Char's>)
Ex:
Sql> Select Substr('Hello',2,3) From Dual; Ell
Ex:
Sql> Select Instr('Hello Welcome','O') From Dual;---------> 5
Sql> Select Instr('Hello Welcome','Z') From Dual;-----> 0
Sql> Select Instr('Hello Welcome','O',1,2) From Dual;-----11
Sql> Select Instr('Hello Welcome','E',5,2) From Dual;-------13
Sql> Select Instr('Hello Welcome','E',1,4) From Dual;--------8
Note:
----------
Position Of Char's Always Fixed Either Count From Left To Right (Or) Right To Left.
Sol: Hello Welcome
12345 6 78910111213
Ex:
Sql> Select Instr('Hello Welcome','E',-1,3) From Dual;--------2
Sql> Select Instr('Hello Welcome','L',-4,3) From Dual;-------3
Sql> Select Instr('Hello Welcome','L',-6,3) From Dual;----------0
Date Functions:
------------------
1) Sysdate:
---------------------
29
> Current Date Information Of The System.
Ex:
Sql> Select Sysdate From Dual;
Sql> Select Sysdate+10 From Dual;
Sql> Select Sysdate-10 From Dual;
Add_Months():
--------------------------
> Adding No.Of Months To The Date.
Syntax:
---------------
Add_Months(Date,<No.Of Months>)
Ex:
Sql> Select Add_Months(Sysdate,3) From Dual;
Sql> Select Add_Months(Sysdate,-3) From Dual;
Last_Day():
---------------------
> Returns The Last Day Of The Month.
Syntax:
--------------
Last_Day(Date)
Ex:
Sql> Select Last_Day(Sysdate) From Dual; Next_Day():
--------------------
> Returns The Next Specified Day From The Given Date.
Syntax:
---------------
Next_Day(Date,'<Day Name>')
Ex:
Sql> Select Next_Day(Sysdate,'Sunday') From Dual;
Months_Between():
------------------------------------
> Returns No.Of Months Between Two Date Expressions.
Syntax:
---------------
Months_Between(Date1,Date2)
Ex:
Sql> Select Months_Between('05-Jan-81','05-Jan-80') From Dual;----- 12
Sql> Select Months_Between('05-Jan-80','05-Jan-81') From Dual;----- -12
Note: Here, Date1 Is Always Greater Than Date2 Otherwise
Oracle Returns Nagative Value.
Conversion Functions:
-------------------------
1. To_Char()
2. To_Date()
To_Char():
-------------------
> Date Type To Char Type To Display Date In Different Fromat.
Syntax:
To_Char(Date,[<Format>])
Year Formats:
30
---------------------------
Yyyy - 2020
Yy - 20
Year - Twenty Twenty
Cc - Centuary 21
Ad / Bc - Ad Yaer / Bc Year
Ex:
Sql> Select To_Char(Sysdate,'Yyyy Yy Year Cc Ad') From Dual;
To_Char(Sysdate,'Yyyyyyyearccad')
----------------------------------------------------------
2020 20 Twenty Twenty 21 Ad
Q: To Display Employee Who Are Joined In Year 1982
By Using To_Char() Function ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')=1982;
Q: To Display Employee Who Are Joined In Year 1980,1982,1987
By Using To_Char() Function ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')
In(1980,1982,1987);
Month Format:
----------------------------
Mm - Month Number
Mon - First Three Char From Month Spelling
Month - Full Name Of Month
Ex:
Sql> Select To_Char(Sysdate,'Mm Mon Month') From Dual;
To_Char(Sysdate,
----------------
08 Aug August
Sql> Select To_Char(Sysdate,'Mm Mon Month') From Dual;
To_Char(Sysdate,
----------------
08 Aug August
Q: To Display Employee Who Are Joined In Feb,May,Dec Months
By Using To_Char() ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Mm')
In(02,05,12);
31
Sun - 1
Mon - 2
Tue - 3
Wen - 4
Thu - 5
Fri - 6
Sat - 7
Day - Full Name Of The Day
Dy - First Three Char's Of Day Spelling
Ex:Sql> Select To_Char(Sysdate,'Ddd Dd D Day Dy') From Dual;
To_Char(Sysdate,'Ddddd
----------------------------------------------
220 07 6 Friday Fri
Q: To Display Employee Who Are Joined On "Friday" By Using
To_Char() ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Day')='Friday';
Q: To Display Employee On Which Day Employees Are Joined ?
Sol:
Sql> Select Ename||' '||'Joined On'||' '||To_Char(Hiredate,'Day')
From Emp;
Note:
------
In Oracle Whenever We Using To_Char() And Also Within To_Char()
When We use Day / Month Format Then Oracle Server Internally
Allocate Some Extra Memory For Day/Month Format Of Data.
To Overcome The Above Problem That Is To Remove Extra
32
Week Format:
--------------------------
Ww - Week Of The Year
W - Week Of Month
Ex:
Sql> Select To_Char(Sysdate,'Ww W') From Dual;
To_C
---------
32 2
Time Format:
-------------------------
Hh - Hour Part
Hh24- 24 Hrs Fromat
Mi - Minute Part
Ss - Seconds Part
Am / Pm - Am Tme (Or) Pm Time
Ex:
Sql> Select To_Char(Sysdate,'Hh:Mi:Ss Am') From Dual;
To_Char(Sys
------------------------
12:04:21 Pm
To_Date():
------------------
To Convert Char Type To Oracle Date Format Type.
Syntax:
To_Date(String[,Fromat])
Ex:
Sql> Select To_Date('08/August/2020') From Dual;
To_Date('
---------
08-Aug-20
Sql> Select To_Date('08-Aug-2020')+10 From Dual;
To_Date('
---------
18-Aug-20
33
Sql> Select Avg(Sal) From Emp Where Deptno=10;
Min():
----------
> It Returns Min.Value From Group Of Values.
Ex:
Sql> Select Min(Hiredate) From Emp;
Sql> Select Min(Hiredate) From Emp Where Job='Manager';
Sql> Select Min(Sal) From Emp;
Max():
-----------
> It Returns Max.Value From Group Of Values.
Ex:
Sql> Select Max(Sal) From Emp;
Count():
----------------
> It Returns No.Of Rows In A Table / No.Of Values In A Column
> Three Types,
I) Count(*)
Ii) Count(<Column Name>)
Iii) Count(Distinct <Column Name>)
Ex:
Test
--------
Sno Name
--- -----
101 A
102 B
103
104 C
105 A
106 C
Count(*):
----------------
> Counting All Rows (Duplicates & Nulls) In A Table.
Ex:
Sql> Select Count(*) From Test;
Count(*)
------------------
6
Count(<Column Name>):
--------------------------------------------
> Counting All Values Including Duplicate Values But Not Null Values
From A Column.
Ex:
Sql> Select Count(Name) From Test;
Count(Name)
-----------------------
5
Count(Distinct <Column Name>):
--------------------------------------------------------------
34
> Counting Unique Values From A Column.Here "Distinct" Keyword
Is Eliminating Duplicate Values.
Ex:
Sql> Select Count(Distinct Name) From Test;------- 3
CLAUSES:
========
- is a statement which is used to add to sql query for providing some facilities are "filtering rows, sorting
values,grouping similar data,finding sub total and grand total" based on columns automatically.
- where
- order by
- group by
- having
- rollup
- cube
where:
=====
- is used to filtering rows before grouping data in a table.
- is used in "select,update,delete" commands only.
syntax:
=======
where <filtering condition>
EX:
select * from emp where empno=7788;
update emp set sal=45000 where job='clerk';
delete from emp where deptno=10;
ORDER BY:
=========
- to arrange values in ascending / descending order.
- by default 'ascending' order.
- if we want to arrange values in descending order
then we a keyword is called as "desc".
- use in "select" command only.
syntax:
=======
select * / <list of columns> from <tn> order by
<col1> asc/desc,<col2> asc/desc,.......;
EX:
SQL> SELECT * FROM EMP ORDER BY ENAME;
SQL> SELECT ENAME FROM EMP ORDER BY ENAME;
SQL> SELECT ENAME FROM EMP ORDER BY ENAME DESC;
35
SQL> SELECT * FROM EMP ORDER BY SAL;
SQL> SELECT * FROM EMP ORDER BY SAL DESC;
EX: waq to display employees who are working under deptno is 30 and arrange those employees salaries in
descending order?
SQL> SELECT * FROM EMP WHERE DEPTNO=30 ORDER BY SAL DESC;
EX: waq to arrange employees deptno's in ascending order and those employees salaries are arrange in
descending from each deptno wise?
SQL> SELECT * FROM EMP ORDER BY DEPTNO,SAL DESC;
NOTE:
=====
- order by clause can apply on not only column names even though we can apply on position of columns in
select query.
EX:
SELECT * FROM EMP ORDER BY 6;
SELECT EMPNO,ENAME,SAL FROM EMP ORDER BY 3;
SELECT ENAME,SAL FROM EMP ORDER BY 2;
SELECT SAL FROM EMP ORDER BY 1;
NOTE:
====
- to arrange the above nulls in correct order by order by clause then we need "null clauses" those are,
1. nulls first :
================
- it will arrange nulls first and later numbers in ascending order.
Ex: SQL> SELECT * FROM EMP ORDER BY COMM NULLS FIRST;
2. nulls last:
==============
- it will arrange numbers first and later nulls in descending order.
EX:
SQL> SELECT * FROM EMP ORDER BY COMM DESC NULLS LAST;
36
GROUP BY:
=========
- is used to grouping similar data based on columns automatically.
- when we use "group by" clause we must use "grouping / aggregative" functions to get the final result.
- can be used in "select" command only.
syntax:
=======
select <col1>,<col2>,.....,<aggregative function name1>,....from <table name> group by <col1>,<col2>,........;
Ex:
group by
|
job( count(job))
|
clerk || salesman || president || manager || analyst
clerk salesman manager analyst
clerk salesman manager
clerk salesman
(4) (4) (1) (3) (2)
EX: waq to find out the no.of employees from each job wise?
SQL> SELECT JOB,COUNT(JOB) NO_OF_EMPLOYEES FROM EMP GROUP BY JOB;
EX: waq to find out the no.of employees from each job along with their deptno wise?
SQL> SELECT JOB,DEPTNO,COUNT(JOB) FROM EMP GROUP BY JOB,DEPTNO;
EX: waq to display no.of employees,sum of salary,min,max and avg salary of each deptno wise?
SQL> SELECT DEPTNO,COUNT(DEPTNO) NO_OF_EMPLOYEES,SUM(SAL) SUM_OF_SALARY,MIN(SAL)
MIN_SALARY,MAX(SAL) MAX_SALARY,AVG(SAL) AVG_SAL FROM EMP GROUP BY DEPTNO ORDER BY
DEPTNO;
HAVING:
=======
- to filtering rows after grouping data in a table.
- it can use after "group by" clause.
syntax:
=======
select <col1>,<col2>,.....,<aggregative function name1>,....
from <table name> group by <col1>,<col2>,.....having <filtering condition>;
EX: waq to display jobs in which job the no.of employees are more than 3?
SQL> SELECT JOB,COUNT(JOB) NO_OF_EMPLOYEES FROM EMP GROUP BY JOB HAVING COUNT(JOB)>3;
EX: waq to display deptno's in which deptno the sum of salary is less than to 10000?
SQL> SELECT DEPTNO,SUM(SAL) SUM_OF_SALARY FROM EMP GROUP BY DEPTNO HAVING SUM(SAL)
<10000 ORDER BY DEPTNO;
37
ALL CLAUSES IN A SINGLE SELECT QUERY:
=====================================
SYNTAX:
=======
select <col1>,<col2>,.....,<aggregative function name1>,....
from <table name>
[where <filtering condition>
group by <col1>,<col2>,.....
having <filtering condition>
order by <column name1> <asc/desc>,......];
EX: SQL> SELECT DEPTNO,COUNT(DEPTNO) FROM EMP WHERE SAL>1000 GROUP BY DEPTNO HAVING
COUNT(DEPTNO)>3 ORDER BY DEPTNO DESC;
JOINS:
======
- generally in RDBMS data can be organized into multiple tables.so that from those multiple tables
if we want to retrieval the required data then we use a technique is called as "joins".
- joins are used to retrieval data from multiple tables at a time.
- joins statements can be written in two ways:
38
2. Ansi joins(oracle9i version)
=============
> inner join
> outer join - left outer join - right outer join - full outer join
> cross join
> natural join
Note:
=====
1. to join two or more than two tables by using "where" clause condition then we called as "non-ansi"
joins.
syntax:
=======
select * from <tn1>,<tn2> where <joining condition>;
2. to join two or more than two tables by using "on" clause condition then we called as "ansi" joins.
syntax:
=======
select * from <tn1> <join key> <tn2> on <joining condition>;
- when we use equi join then we should have a common column in both tables.
- datatypes of columns must be match.
- having relationship in between tables is just optional.
- it retrieval matching rows only.
Ex: waq to retrieve course and the corresponding student details from course,student tables by using equi
join?
non-ansi format:
================
SQL> SELECT * FROM COURSE,STUDENT WHERE COURSE.CID =STUDENT.CID;
(OR)
SQL> SELECT * FROM COURSE C,STUDENT S WHERE C.CID =S.CID;
(OR)
SQL> SELECT STID,SNAME,CNAME,CFEE FROM COURSE C,STUDENT S
WHERE C.CID=S.CID;
ansi format:
================
39
SQL> SELECT * FROM COURSE INNER JOIN STUDENT ON COURSE.CID =STUDENT.CID;
(OR)
SQL> SELECT * FROM COURSE C INNER JOIN STUDENT S ON C.CID =S.CID;
(OR)
SQL> SELECT STID,SNAME,CNAME,CFEE FROM COURSE C INNER JOIN STUDENT S
ON C.CID=S.CID;
COURSE STUDENT
====== =======
CID CID
==== ===
11
23
32
3
NULL
RULE OF JOINS:
==============
a row in a table is comparing with all rows of another table.
non-ansi join:
==============
SQL> SELECT STID,SNAME,CNAME FROM COURSE C,STUDENT S WHERE C.CID=S.CID AND
CNAME='ORACLE';
ansi join:
==============
SQL> SELECT STID,SNAME,CNAME FROM COURSE C inner join STUDENT S on C.CID=S.CID AND
CNAME='ORACLE';
EX:
waq to display employees who are working in the location is chicago?
non-ansi join:
===============
SQL> SELECT ENAME,LOC FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO AND LOC='CHICAGO';
ansi-join
=========
SQL> SELECT ENAME,LOC FROM EMP E inner join DEPT D on E.DEPTNO=D.DEPTNO AND LOC='CHICAGO';
EX:
waq to display sum of salaries of each department names wise?
non-ansi join:
40
==============
SQL> SELECT DNAME,SUM(SAL) FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO GROUP BY DNAME;
ansi join:
==============
SQL> SELECT DNAME,SUM(SAL) FROM EMP E inner join DEPT D on E.DEPTNO=D.DEPTNO GROUP BY
DNAME;
EX:
waq to display sum of salaries of department names in which department total salary is more than 10000?
non-ansi join:
==============
SQL> SELECT DNAME,SUM(SAL) FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO GROUP BY DNAME
HAVING SUM(SAL)>10000;
ansi join:
==========
SQL> SELECT DNAME,SUM(SAL) FROM EMP E inner join DEPT D on E.DEPTNO=D.DEPTNO GROUP BY
DNAME HAVING SUM(SAL)>10000;
OUTER JOINS:
============
- retrieving matching and also unmatching rows from multiple tables.
ansi join:
==========
SQL> SELECT * FROM COURSE C LEFT OUTER JOIN STUDENT S ON C.CID=S.CID;
non-ansi join:
==============
- when we want to write outer joins statements in non-ansi format then we use a join operator is called as
(+).
EX:
SELECT * FROM COURSE C,STUDENT S WHERE C.CID=S.CID(+);
ansi join:
==========
SQL> SELECT * FROM COURSE C RIGHT OUTER JOIN STUDENT S ON C.CID=S.CID;
non-ansi join:
==============
SQL> SELECT * FROM COURSE C,STUDENT S WHERE C.CID(+)=S.CID;
41
iii) full outer join:
=====================
- retrieving matching & unmatching rows from both tables.
ansi join:
==========
SQL> SELECT * FROM COURSE C FULL OUTER JOIN STUDENT S ON C.CID=S.CID;
non-ansi join:
==============
SQL> SELECT * FROM COURSE C,STUDENT S WHERE C.CID(+)=S.CID
2 UNION
3 SELECT * FROM COURSE C,STUDENT S WHERE C.CID=S.CID(+);
NON-EQUI JOIN:
==============
- when we retrieving data from multiple tables based on any operator except an " = " operator.
- we can use the following operators are ,"<,>,<=,>=,!=,and,between,or,.....etc"
non-ansi:
=========
SQL> SELECT * FROM TEST11 T1,TEST12 T2 WHERE T1.SNO>T2.SNO;
ansi:
=====
SQL> SELECT * FROM TEST11 T1 join TEST12 T2 on T1.SNO>T2.SNO;
EX: waq to display employees whose salary is between low salary and high salary?
non-ansi:
=========
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP,SALGRADE WHERE SAL BETWEEN LOSAL AND HISAL;
(or)
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP,SALGRADE WHERE (SAL>=LOSAL) AND (SAL<=HISAL);
ansi:
=====
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP join SALGRADE on SAL BETWEEN LOSAL AND HISAL;
(or)
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP join SALGRADE on (SAL>=LOSAL) AND (SAL<=HISAL);
CROSS JOIN:
===========
- joining two or more than two tables without any condition.
- each row in a table will joins with each row another tablefor example a table is having (m) no.of rows and
other table is having (n) no.of rows then the result is (mxn) rows.
Ex:
non-ansi:
SQL> SELECT * FROM COURSE,STUDENT;
42
ansi:
SQL> SELECT * FROM COURSE CROSS JOIN STUDENT;
Ex:
non-ansi:
=========
SQL> SELECT I1.INAME,I1.PRICE,I2.INAME,I2.PRICE, I1.PRICE+I2.PRICE TOTAL_AMOUNT FROM ITEMS1
I1,ITEMS2 I2;
ansi:
=====
SQL> SELECT I1.INAME,I1.PRICE,I2.INAME,I2.PRICE, I1.PRICE+I2.PRICE TOTAL_AMOUNT FROM ITEMS1 I1
cross join ITEMS2 I2;
NATURAL JOIN:
============
- is similar to equi join.
- equi join condition - this join condition can be can be written by user. written by system by default.
(explicit condition) (implicit condition)
EX:
ansi:
SQL> SELECT * FROM COURSE C NATURAL JOIN STUDENT S;
non-ansi:
=========
SQL> SELECT S.CID,CNAME,CFEE,STID,SNAME FROM COURSE C,STUDENT S WHERE C.CID=S.CID;
SELF JOIN:
==========
- it can use on a single table operations.
- joining a table by itself is called as "self join".
- when we implement self join we should create alias names on a table otherwise we cannot go for self
join.
- once we created alias name on a table internally system is preparing a virtual table on each alias name.
Ex:
emp e1,emp e2,emp e3
- we can create any no.of alias names on a single table but each alias name should be different.
43
purpose of self join:
======================
case-1:
=======
comparing a single column values by it self with in the table.
case-2:
=======
comparing two different columns values to each other with in the table.
non-ansi:
==========
SQL> SELECT T1.ENAME,T1.LOC FROM TEST T1,TEST T2 WHERE T1.LOC=T2.LOC AND T2.ENAME='SMITH';
ansi:
==========
SQL> SELECT T1.ENAME,T1.LOC FROM TEST T1 join TEST T2 on T1.LOC=T2.LOC AND T2.ENAME='SMITH';
OUTPUT:
ENAME LOC
---------- ----------
SMITH HYD
JONES HYD
EX:
waq to display employees whose salary is same as the employee 'scott'?
non-ansi
===========
SQL> SELECT E1.ENAME,E1.SAL FROM EMP E1,EMP E2 WHERE E1.SAL=E2.SAL AND E2.ENAME='SCOTT';
ansi
===========
SQL> SELECT E1.ENAME,E1.SAL FROM EMP E1 join EMP E2 on E1.SAL=E2.SAL AND E2.ENAME='SCOTT';
ENAME SAL
---------- ----------
SCOTT 3000
FORD 3000
case-2:
=======
comparing two different columns values to each other with in the table.
========================================================================
Ex:
waq to find out managers and their employees from emp table?
44
SQL> SELECT M.ENAME MANAGERS,E.ENAME EMPLOYEES FROM EMP E,EMP M WHERE
M.EMPNO=E.MGR;
EX:
waq to display employees who are joined before their manager?
SQL> SELECT E.ENAME EMPLOYEES,E.HIREDATE E_DOJ, M.ENAME MANAGERS,M.HIREDATE M_DOJ FROM
EMP E,EMP M WHERE M.EMPNO=E.MGR AND E.HIREDATE<M.HIREDATE;
EQUI JOIN:
==========
EX:
SQL> SELECT * FROM COURSE C,STUDENT S,REGISTER R,T4 WHERE C.CID=S.CID AND S.CID=R.CID;
INNER JOIN:
============
SQL> SELECT * FROM COURSE C INNER JOIN STUDENT S ON C.CID=S.CID INNER JOIN REGISTER R ON
S.CID=R.CID;
DATA INTEGRITY:
===============
- to maintain accurate & consistency data in database tables.
1. declarative integrity
45
- pre-defined rules
- by using constraints(sql)
2. procedural integrity
- user-defined rules
- by using triggers(pl/sql)
1. declarative integrity:
==========================
i) entity integrity
ii) referencial integrity
iii) domain integrity
i) entity integrity:
===================
- entity = table
- it ensure that each row in a table should be unique.
- can be implemented by using "unique , primary key".
constraints:
============
- are used to restricted unwanted data/information into a table.
types of constraints:
======================
i) unique
ii) not null
iii) check
iv) primary key
v) foreign key
vi) default
Note:
=====
- it can be defined at two levels.
46
syntax:
=======
create table <tn>
(<column name1> <dt>[size] <constraint type>,
<column name2> <dt>[size] <constraint type>,
...........................................
);
syntax:
========
create table <table name>
(
<column name1> <dt>[size],
<column name2> <dt>[size],
<column name3> <dt>[size],
........................
.........................
<constraint type>(<col1>,<col2>,......)----> composite constraint.
);
Unique:
=======
- to restricted duplicates but allowed nulls.
EX:
column level:
==============
SQL> CREATE TABLE TEST1(SNO INT UNIQUE,NAME VARCHAR2(10) UNIQUE);
TESTING:
INSERT INTO TEST1 VALUES(1,'A');---ALLOWED
INSERT INTO TEST1 VALUES(1,'A');---NOT ALLOWED
INSERT INTO TEST1 VALUES(NULL,NULL);--ALLOWED
table level:
============
SQL> CREATE TABLE TEST2(SNO INT,NAME VARCHAR2(10),UNIQUE(SNO,NAME));
----------------
TESTING: |
SQL> INSERT INTO TEST2 VALUES(1,'A');----ALLOWED composite unique
SQL> INSERT INTO TEST2 VALUES(1,'A');---NO constraint
SQL> INSERT INTO TEST2 VALUES(1,'B');---ALLOWED
NOT NULL:
==========
- to restricted nulls but allowed duplicates.
- it cannot defined at table level.
47
EX:
column level:
=============
SQL> CREATE TABLE TEST3(SNO INT NOT NULL,NAME VARCHAR2(10) NOT NULL);
TESTING:
SQL> INSERT INTO TEST3 VALUES(1,'A');---ALLOWED
SQL> INSERT INTO TEST3 VALUES(1,'A');---ALLOWED
SQL> INSERT INTO TEST3 VALUES(NULL,NULL);----NO
PRIMARY KEY:
============
- to restricted duplicates & nulls.
- is a combination of "unqiue and not null".
- a table is having only one PK.
EX:
column level:
=============
SQL> CREATE TABLE TEST4(EID INT PRIMARY KEY,ENAME VARCHAR2(10));
TESTING:
SQL> INSERT INTO TEST4 VALUES(101,'SMITH');---ALLOWED
SQL> INSERT INTO TEST4 VALUES(101,'ALLEN');---NO
SQL> INSERT INTO TEST4 VALUES(NULL,'ALLEN');---NO
table level:
============
SQL> CREATE TABLE TEST5(EID INT,ENAME VARCHAR2(10),primary key(eid,ename));
-----------------------
TESTING: <composite PK>
SQL> INSERT INTO TEST5 VALUES(101,'SMITH');---ALLOWED
SQL> INSERT INTO TEST5 VALUES(101,'ALLEN');---allowed
SQL> INSERT INTO TEST5 VALUES(101,'ALLEN');---NO
CHECK:
======
- to check values before inserting into a column.
Ex:
column level:
=============
SQL> CREATE TABLE TEST6(ENAME VARCHAR2(10) UNIQUE NOT NULL,
SAL NUMBER(10) CHECK(SAL>8000));
TESTING:
INSERT INTO TEST6 VALUES('SMITH',7500);---NOT ALLOWED
INSERT INTO TEST6 VALUES('SMITH',8001);---ALLOWED
table level:
============
48
SQL> CREATE TABLE TEST7(ENAME VARCHAR2(10),SAL NUMBER(10),
CHECK(ENAME=UPPER(ENAME) AND SAL>=8000));
TESTING:
SQL> INSERT INTO TEST7 VALUES('sai',8500);---NOT
SQL> INSERT INTO TEST7 VALUES('SAI',7500);---NOT
SQL> INSERT INTO TEST7 VALUES('SAI',8500);---ALLOWED
FOREIGN KEY:
============
- to making relationship between tables.
rules:
======
1. common column in both tables.
2. common column datatype must match in both tables.
3. a table should have a PK and another table should have FK.
(PK and FK column should be common column in tables)
4. a PK table is called as parent and a FK table is called as child.
5. a FK column values must be PK column values only.
Ex:
SQL> CREATE TABLE DEPT1(DEPTNO INT PRIMARY KEY,
DNAME VARCHAR2(10));---PARENT TABLE
49
SQL> CREATE TABLE EMP1(EID INT,ENAME VARCHAR2(10),DEPTNO INT REFERENCES DEPT1(DEPTNO));---
CHILD TABLE
NOTE:
=====
- once we created relationship between tables there are two rules are come into picture those are:
rule-1(insertion)
=================
- we cannot insert values into child table those values are not found in parent table.
NO PARENT = NO CHILD
Ex:
INSERT INTO EMP1 VALUES(6,'ADAMS',30);
ERROR at line 1:
ORA-02291: integrity constraint (MYDB4PM.SYS_C007588) violated -
parent key not found.
rule-2(deletion)
=================
- we cannot delete a row from parent table those row values are existing in child table without addressing
to child.
EX:
DELETE FROM DEPT1 WHERE DEPTNO=10;
ERROR at line 1:
ORA-02292: integrity constraint (MYDB4PM.SYS_C007588) violated -
child record found.
Ex:
SQL> CREATE TABLE DEPT2(DEPTNO INT PRIMARY KEY,
DNAME VARCHAR2(10));---PARENT TABLE
50
SQL> INSERT INTO DEPT2 VALUES(10,'JAVA');
SQL> INSERT INTO DEPT2 VALUES(20,'DB');
SQL> COMMIT;
TESTING:
========
DELETE FROM DEPT2 WHERE DEPTNO=10;---ALLOWED
Ex:
SQL> CREATE TABLE DEPT3(DEPTNO INT PRIMARY KEY,
DNAME VARCHAR2(10));---PARENT TABLE
TESTING:
========
DELETE FROM DEPT3 WHERE DEPTNO=10;---ALLOWED
TESTING
SQL> INSERT INTO TEST8 VALUES(1,'A');
51
SQL> INSERT INTO TEST8 VALUES(1,'B');--ERROR
ERROR at line 1:
ORA-00001: unique constraint (MYDB4PM.SYS_C007596) violated
COLUMN_NAME CONSTRAINT_KEY_NAME
=========== ===================
SNO SYS_C007596
NAME SYS_C007597
EX:
SQL> CREATE TABLE TEST9
2 (
3 SNO INT CONSTRAINT SNO_PK PRIMARY KEY,
4 NAME VARCHAR2(10) CONSTRAINT NAME_UQ UNIQUE
5 );
Table created.
COLUMN_NAME CONSTRAINT_KEY_NAME
=========== ===================
SNO SNO_PK
NAME NAME_UQ
52
- if we want to view all datadictionaries in oracle db then
we follow the following syntax is
syntax:
======
select * from dict;
NOTE:
=====
- To view column name along with constraint name of
a particular table in oracle db then we use a datadictionary
is called as "user_cons_columns".
EX:
SQL> DESC USER_CONS_COLUMNS;
SQL> SELECT COLUMN_NAME,CONSTRAINT_NAME
2 FROM USER_CONS_COLUMNS
3 WHERE TABLE_NAME='TEST9';
COLUMN_NAME CONSTRAINT_NAME
------------------ --------------------------------------------------------------------------------------------------------------
SNO SNO_PK
NAME NAME_UQ
NOTE:
=====
if we want to view a check constraint conditional value
of a column in a particular table then we use a data dictionary
is called as "user_constraints".
Ex:
SQL> DESC USER_CONSTRAINTS;
SQL> SELECT SEARCH_CONDITION FROM USER_CONSTRAINTS
2 WHERE TABLE_NAME='PARENT';
53
SEARCH_CONDITION
------------------
SAL>8000
Ex:
SQL> ALTER TABLE PARENT MODIFY ENAME CONSTRAINT ENAME_NN NOT NULL;
EX:
SQL> CREATE TABLE CHILD(DNAME VARCHAR2(10),EID INT);
Table created.
54
HOW TO RENAME CONSTRAINT NAME:
===============================
SYNTAX:
=======
alter table <tn> rename <constraint> <old constraint key name>
to <new constraint key name>;
EX:
SQL> CREATE TABLE TEST10(SNO INT PRIMARY KEY);
COLUMN_NAME CONSTRAINT_NAME
-------------------------- ------------------------------------------------------------------------------------------------------
SNO SYS_C007605
EX:
SQL> ALTER TABLE TEST10 RENAME CONSTRAINT
2 SYS_C007605 TO PK_SNO;
COLUMN_NAME CONSTRAINT_NAME
-------------------------- ------------------------------------------------------------------------------------------------------
SNO PK_SNO
Ex:
SQL> CREATE TABLE TEST11 (ENAME VARCHAR2(10),SAL NUMBER(10) CHECK(SAL>=10000));
TESTING:
SQL> INSERT INTO TEST11 VALUES('SMITH',10000);--allowed
SQL> INSERT INTO TEST11 VALUES('ALLEN',12000);--allowed
SQL> INSERT INTO TEST11 VALUES('WARD',8000);--not allowed
- if we want to insert salary which is less than to 10000 into sal column then we need to disable check
constraint like below,
Ex:
alter table test11 disable constraint SYS_C007606;
TESTING:
SQL> INSERT INTO TEST11 VALUES('WARD',8000);--allowed
- if we want to enable a check constraint on existing column in a table then we must use a keyword is
called as "novalidate".
WHAT IS NOVALIDATE:
55
===================
- it is a default key which will not check existing values in a column but checking new values into a column.
EX:
SQL> ALTER TABLE TEST11 ENABLE NOVALIDATE CONSTRAINT SYS_C007606;
TESTING:
INSERT INTO TEST11 VALUES('SCOTT',5000)---not allowed
INSERT INTO TEST11 VALUES('SCOTT',50000)---allowed
DEFAULT CONSTRAINT:
===================
- it is a special type of constraint which is used to assign a user defined default value to a column.
Ex:
SQL> CREATE TABLE TEST12(SNO INT,LOC VARCHAR2(10) DEFAULT 'HYD');
TESTING:
INSERT INTO TEST12(SNO,LOC) VALUES(1,'MUMBAI');---allowed
INSERT INTO TEST12(SNO)VALUES(2);---allowed
SNO LOC
---------- ----------
1 MUMBAI
2 HYD
EX:
SQL> CREATE TABLE TEST13(ENAME VARCHAR2(10),SAL NUMBER(10));
SQL> ALTER TABLE TEST13 MODIFY SAL DEFAULT 5000;
TESTING:
SQL> INSERT INTO TEST13(ENAME)VALUES('A');
NOTE:
=====
- if we want to view a default value of a column of a particular table then we use a datadictionary is called
as "user_tab_columns".
EX:
SQL> DESC USER_TAB_COLUMNS;
SQL> SELECT COLUMN_NAME,DATA_DEFAULT FROM
2 USER_TAB_COLUMNS WHERE TABLE_NAME='TEST13';
COLUMN_NAME DATA_DEFAULT
---------------------- ----------------------------------------------------------
56
SAL 5000
EX:
SQL> ALTER TABLE TEST13 MODIFY SAL DEFAULT NULL;
COLUMN_NAME DATA_DEFAULT
---------------------- ----------------------------------------------------------
SAL NULL
a) implicit commit:
- these transactions are committed by system by default.
Ex:
DDL commands
b) explicit commit:
- these transaction are committed by user as per requirement.
Ex:
DML commands
syntax:
=======
commit;
Ex:
CREATE TABLE BRANCH(BCODE INT,BNAME VARCHAR2(10),BLOC VARCHAR2(10));
57
SQL> INSERT INTO BRANCH VALUES(1021,'SBI','HYD');
SQL> COMMIT;
2) ROLLBACK:
============
- To cancel a transaction.
syntax:
=======
rollback;
Ex:
insert into branch values(1021,'sbi','hyd');
rollback;
3) SAVEPOINT:
=============
- when we created a save pointer internally system is allocating a special memory for a save pointer and
which will store a transaction which we want to rollback(cancel) in the feature.
ex:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> DELETE FROM BRANCH WHERE BCODE=1025;
case-1:
========
rollback to p1;------> rollback 1023 only
case-2:
=======
rollback / commit
58
ALL TRANSACTIONS:
==================
Atomicity:
==========
- atomic = single
consistency:
============
- accurate information
x (a/c:10000)<------------> y(a/c:3000)
3000 --------------> 3000
====== =======
7000 6000
3000
=======
10000
isolation:
==========
- each transaction is independent
durability:
SUBQUERY:
=========
- A query inside another query is called as "Sub-query / Nested query".
syntax:
=======
select * from <tn> where <condition>(select * from ....(select * from ....));
- as per the execution process of subquery statement it again classified into two types,
1. Non-corelated subquery
59
2. Co-related subquery
1. Non-corelated subquery:
===========================
- first inner query later outer query.
2. Co-related subquery:
=======================
- first outer query later inner query.
1. Non-corelated subquery
=========================
> single row subquery
> multiple row subquery
> multiple column subquery
> inline view
Ex:
waq to display employee details who are earning the first highest salary from emp table?
=======================================
|| subquery statement = outer query + inner query ||
=======================================
step1:inner query:
==================
select max(sal) from emp;------> 5000
step3: subquery=(outer+inner)
=============================
select * from emp where sal=(select max(sal) from emp);
EX:
waq to display the senior most details from emp table?
select * from emp where hiredate=(select min(hiredate) from emp);
Ex:
waq to display employees details whose salary is more than the maximum salary of the job is salesman?
select * from emp where sal >(select max(sal) from emp where job='SALESMAN')
Ex:
waq to find out second highest salary from emp table?
SQL> SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP);
60
Ex:
waq to display employee details who are getting 2nd highest salary?
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP));
Ex:
waq to display employee details who are getting 3rd highest salary?
SELECT * FROM EMP WHERE SAL=
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP)));
Nth N+1
==== ====
1ST 2Q,2ND 3Q,3RD 4Q,30TH 31Q &150TH 151Q
Ex:
waq to display employees whose employees job is same as the employee "smith" or "martin" jobs?
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE ENAME='SMITH'
OR ENAME='MARTIN');
(OR)
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE
ENAME IN('SMITH','MARTIN'));
Ex:
waq to display employees who are earning highest and lowest salary from emp table?
SQL> SELECT * FROM EMP WHERE SAL IN
(SELECT MAX(SAL) FROM EMP UNION SELECT MIN(SAL) FROM EMP);
Ex:
waq to display employees who are getting maximum salary from each job?
SQL> SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL) FROM EMP GROUP BY JOB);
ANY,ALL OPERATORS:
==================
ANY:
====
- it returns true if any one value is satisfied from the given list of values.
EX:
X(25) >ANY(10,20,30)
61
ALL:
====
- it returns true if all values are satisfied from the given list of values.
EX:
X(25) >ALL(10,20,30)
Ex:
waq to display employees whose salary is more than any 'salesman' salary?
SQL> SELECT * FROM EMP WHERE SAL >ANY(SELECT SAL FROM EMP WHERE JOB='SALESMAN');
Ex:
waq to display employees whose salary is more than all 'salesman' salaries?
SQL> SELECT * FROM EMP WHERE SAL >ALL(SELECT SAL FROM EMP WHERE JOB='SALESMAN');
syntax:
=======
select * from <tn> where(<col1>,,col2>,....) in(select <col1>,<col2>,....);
Ex:
waq to display employees whose employee job,mgr are same as the job,mgr of the employee "scott"?
SQL> SELECT * FROM EMP WHERE(JOB,MGR) IN (SELECT JOB,MGR FROM EMP
WHERE ENAME='SCOTT');
PSEUDO COLUMNS:
===============
I) ROWID
II) ROWNUM
- these columns are working just like a table columns.
I) ROWID:
=========
- whenever we insert a new row into a table internally oracle server is creating a unique row
identification / row address to each row wise in a table.
- these rowid's are permanent id's ,stored in database memory.
EX:
SQL> SELECT ENAME,ROWID FROM EMP;
SQL> SELECT ENAME,DEPTNO,ROWID FROM EMP WHERE DEPTNO=10;
HOW TO DELETE MULTIPLE DUPLICATE ROWS EXCEPT ON DUPLICATE ROW FROM A TABLE:
===========================================================================
EX_TABLE:
=========
62
SQL> SELECT * FROM TEST;
SNO NAME
---------- ----------
1A
1A
1A
2B
3C
3C
4D
4D
4D
5E
5E
SOL:
SQL> DELETE FROM TEST WHERE ROWID NOT IN(SELECT MAX(ROWID) FROM TEST
GROUP BY SNO);
II) ROWNUM:
===========
- is used to generate row numbers to each row wise / to each group of rows wise automatically.
- these are temporary numbers , not saved in database memory.
- to perform " top N / Nth operations" over database table.
Ex:
SQL> SELECT ROWNUM,ENAME FROM EMP;
SQL> SELECT ROWNUM,ENAME,DEPTNO FROM EMP WHERE DEPTNO=10;
Ex:
waq to fetch the 1st row from emp table by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM=1;
Ex:
waq to fetch the 2ND ROW from emp table by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM=2;
no rows selected
NOTE:
=====
- generally rownum is always starts with 1 for every selected row in a table. so to overcome this problem
we use the following operators are "<,<=".
SOLUTION:
SQL> SELECT * FROM EMP WHERE ROWNUM<=2
2 MINUS
3 SELECT * FROM EMP WHERE ROWNUM=1;
Ex:
waq tp display top 5 rows from emp by using rownum?
63
SQL> SELECT * FROM EMP WHERE ROWNUM<=5;
Ex:
waq to display 5th row from emp by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM<=5
2 minus
3 SELECT * FROM EMP WHERE ROWNUM<=4;
EX:
waq to fetch from 3rd row to 10th row from emp by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM<=10
2 minus
3 SELECT * FROM EMP WHERE ROWNUM<3;
EX:
waq to fetch the last two rows from emp by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM<=14
2 MINUS
3 SELECT * FROM EMP WHERE ROWNUM<=12;
(OR)
SQL> SELECT * FROM EMP
2 MINUS
3 SELECT * FROM EMP WHERE ROWNUM<=(SELECT COUNT(*)-2 FROM EMP);
INLINE VIEW:
============
- it is special type of subquery.
- providing a select query inplace of table name in select statement is called as "inline view".
- in inline view mechanism the result of inner query will act as a table for outer query.
syntax:
========
SELECT * FROM <SELECT QUERY>;
Ex:
waq to display empno,ename,sal and annual salary of employees whose annual salary is more than 30000?
SOLUTION:
64
SQL> SELECT * FROM (SELECT EMPNO,ENAME,SAL,SAL*12 ANNSAL FROM EMP)
WHERE ANNSAL>30000;
EX:
waq to fetch the first five highest salaries employees from emp table by using rownum along with inline
view?
SQL> SELECT * FROM(SELECT * FROM EMP ORDER BY SAL DESC)
2 WHERE ROWNUM<=5;
EX:
waq to fetch the fifth highest salaries employee from emp table by using rownum along with inline view?
SQL> SELECT * FROM(SELECT * FROM EMP ORDER BY SAL DESC)
2 WHERE ROWNUM<=5
3 minus
4 SELECT * FROM(SELECT * FROM EMP ORDER BY SAL DESC)
5 WHERE ROWNUM<=4;
Ex:
waq to fetch 1st,3rd,5th,10th position rows from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP) WHERE R IN(1,3,5,10);
EX:
waq to fetch the even position rows from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP) WHERE MOD(R,2)=0;
EX:
waq to fetch the first row and the last row from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP)
2 WHERE R=1 OR R=14;
(OR)
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP)
2 WHERE R=1 OR R=(SELECT COUNT(*) FROM EMP);
ANALYTICAL FUNCTIONS:
=====================
I) ROW_NUMBER()
II) RANK()
III) DENSE_RANK()
I) ROW_NUMBER():
=================
- is used to generate row numbers to each row wise / to each group of rows wise in a table automatically.
- is not comparing data in a table.
65
II) RANK():
===========
- is used to assign rank numbers to each row wise / to each group of wise in a table automatically.
- is used to comparing data in a table.
- it will skip the next rank number in order when we have
duplicates.
III) DENSE_RANK():
==================
- is used to assign rank numbers to each row wise / to each group of wise in a table automatically.
- is used to comparing data in a table.
- it will not skip the next rank number in order
when we have duplicates.
syntax:
=======
analytical function name()over([partition by <column name>]
order by <column name> <asc/desc>)
Here,
partition by clause is optional order by clause is mandatory
EX:
66
EX:
waq to display employees who are earning 3rd highest salary from each deptno wise by using dense_rank()
along with inline view?
SQL> SELECT * FROM(SELECT EMPNO,ENAME,DEPTNO,SAL,DENSE_RANK() OVER(PARTITION BY DEPTNO
ORDER BY SAL DESC) RANKS FROM EMP) WHERE RANKS=3;
EX:
waq to display 4th senior most employee from each job wise by using dense_rank() along with inline view?
SQL> SELECT * FROM(SELECT EMPNO,ENAME,JOB,HIREDATE,DENSE_RANK()OVER(PARTITION BY JOB
ORDER BY HIREDATE) RANKS FROM EMP) WHERE RANKS=4;
2) CO-RELATED SUBQUERY:
=======================
- first outer query is executed and later inner query.
Here,
< ---- for lowest salary
> ---- for highest salary
ENAME SAL
---------- ----------
SMITH 45000
ADAMS 37000
JONES 85000
MILLER 12000
WARD 28000
SCOTT 85000
EX:
waq to find out 1st highest salary employee details by using co-related subquery?
SQL> SELECT * FROM TEST T1 WHERE 0=(SELECT COUNT(DISTINCT SAL)
FROM TEST T2 WHERE T2.SAL > T1.SAL);
ENAME SAL
---------- ----------
SCOTT 85000
JONES 85000
EX:
waq to find out 5th highest salary employee details by using co-related subquery?
SQL> SELECT * FROM TEST T1 WHERE 4=(SELECT COUNT(DISTINCT SAL)
FROM TEST T2 WHERE T2.SAL > T1.SAL);
67
EX:
waq to find out 1st lowest salary employee details by using co-related subquery?
SQL> SELECT * FROM TEST T1 WHERE 0=(SELECT COUNT(DISTINCT SAL)
FROM TEST T2 WHERE T2.SAL < T1.SAL);
DB SECURITY:
============
- all databases are supporting the following two types of
security mechanisms those are,
1. Authentication
2. Authorization
1. Authentication:
===================
- to check user credential(username & password) before
connect / login into oracle db server.
- these user credential are created by DBA.
Ex:
create user U1 identified by U1;
2. Authorization:
=================
- to give permissions to user to perform some operations
over database.
- these permissions are also giving by DBA by using
"DCL" commands.
i) grant:
=========
- to give permission to user.
syntax:
=======
68
grant <privilege name> to <username>;
ii) revoke:
===========
- to cancel permission from user.
syntax:
=======
revoke <privilege name> from <username>;
PRIVILEGES:
===========
- is nothing but right giving by DBA only.
i) system privileges
ii) object privileges
i) system privileges:
======================
- these privileges are giving by DBA only.
- system privilege are "connect,create table,unlimited tablespace,
create view,create synonym,create sequence,create materialized view,
create procedure,create index,create cluster,........etc.
syntax:
=======
grant <system privilege name> to <username>;
Ex:
CONN: system/tiger
sql> create user u1 identified by u1;
conn: u1/u1
error
conn: system/tiger
sql> grant connect to u1;
conn: u1/u1
connected
create table test1(sno int,name varchar2(10));
error
conn: system/tiger
sql> grant create table to u1;
sql> insert into test1 values(1,'smith');
error
conn: u1/u1
sql> insert into test1 values(1,'smith');
69
1 row created.
conn : u1/u1
error
2. OBJECT PRIVILEGES:
=====================
- these permissions are giving by DBA and DB developer(user).
- these permissions are nothing "select,insert,update,
delete" (or) "all" keyword.
syntax:
========
grant <object privilege name> on <object name/table name> to <username>;
Case-1: DBA-to-User:
====================
conn : system/tiger
sql> create user u2 identified by u2;
sql> grant connect to u2;
conn : u2/u2
sql> select * from dept;
(or)
sql> select * from system.dept;
error
Note:
=====
- the user "u2" is not having object privileges(permissions)
to perform "select,insert,update,delete" operations on
dept table.so that system admin want to give permissions to
user u2 like below,
conn : system/tiger
sql> grant select,insert,update,delete on dept to u2;
70
(or)
sql> grant all on dept to u2;
conn : u2/u2
sql> select * from system.dept;---allowed
sql> insert into system.dept values(50,'dba','hyd');---allowed
sql> update system.dept set loc='pune' where deptno=30;---allowed
sql> delete from system.dept where deptno=10;----allowed
Case-2: DB developer(User)-to-User:
===================================
- when a user u1 want to give object privileges to another
user u2 then u1 should take permission from DBA with "with
grant option" statement then only user u1 can give object
privileges to another user u2.
EX:
conn: system/tiger
sql> create user u11 identified by u11;
sql> create user u12 identified by u12;
conn : u11/u11
sql> select * from system.dept;
error
conn : u12/u12
sql> select * from system.dept;
error
conn : system/tiger
sql> grant select on dept to u11;(granting without "with grant option")
conn : u11/u11
sql> select * from system.dept;---allowed
conn : u11/u11
71
sql> select * from system.dept;
sql> grant select on system.dept to u12;---->allowed
ROLE:
=====
- a role is nothing but giving group of privileges
to a group of users who are working on same project in real
time.
- created by DBA only.
EX: X-project
|
mod1 | mod2 | mod3
|||
3emp 5emp 2emp
|||
role1
|
create table privilege
EX:
conn : system/tiger
SQL> CREATE USER U1 IDENTIFIED BY U1;
SQL> CREATE USER U2 IDENTIFIED BY U2;
SQL> CREATE USER U3 IDENTIFIED BY U3;
72
CONN : U1/U1
SQL> CREATE TABLE TEST1(SNO INT);
ERROR
CONN : U2/U2
SQL> CREATE TABLE TEST1(SNO INT);
ERROR
CONN : U3/U3
SQL> CREATE TABLE TEST1(SNO INT);
ERROR
CONN : system/tiger
SQL> CREATE ROLE R1;
SQL> GRANT CREATE TABLE TO R1;
SQL> GRANT R1 TO U1,U2,U3;
CONN : U1/U1
SQL> CREATE TABLE TEST1(SNO INT);----allowed
CONN : U2/U2
SQL> CREATE TABLE TEST1(SNO INT);----allowed
CONN : U3/U3
SQL> CREATE TABLE TEST1(SNO INT);---allowed
SQL:
> DDL
> DML
> DRL/DQL ------> any developers(user)
> TCL
purpose:
========
1. to reduce the lengthy table name.
2. to hide username and table name.
types of synonyms:
==================
1. private synonym
2. public synonym
1. private synonym:
73
====================
- these are default synonyms.
- these are created by users who are having permission.
syntax:
=======
create synonym <synonym name> for [username].<table name>;
ex:
conn : system/tiger
sql> create user u1 identified by u1;
sql> grant connect,create table,unlimited tablespace
to u1;
conn : u1/u1
sql> create table college_enrollment_details
(stid int,sname varchar2(10));
conn : system/tiger
sql> grant create synonym to u1;
conn : u1/u1
sql> create synonym s1 for college_enrollment_details;
Note:
=====
- if we want to view private synonyms in oracle
then we use a datadictionary is called as
"user_synonyms".
Ex:
SQL> DESC USER_SYNONYMS;
SQL> SELECT TABLE_OWNER,SYNONYM_NAME,TABLE_NAME
2 FROM USER_SYNONYMS;
74
TABLE_OWNER SYNONYM_NAME TABLE_NAME
------------ ----------------- ---------------------------------------------------
U1 S1 COLLEGE_ENROLLMENT_DETAILS
Ex:
drop synonym s1;
syntax:
=======
create public synonym <synonym name> for [username].<table name>;
EX:
conn : system/tiger
sql> create user u2 identified by u2;
sql> create user u3 identified by u3;
sql> grant connect to u2,u3;
conn : u2/u2
sql> select * from ps11;
conn : u3/u3
sql> select * from ps11;
Note:
=====
- if we want to view public synonyms in oracle
the we use a datadictionary is "all_synonyms".
Ex:
sql> DESC ALL_SYNONYMS;
SQL> SELECT TABLE_OWNER,SYNONYM_NAME,TABLE_NAME
2 FROM ALL_SYNONYMS WHERE TABLE_NAME='DEPT';
75
HOW TO DROP A PUBLIC SYNONYM:
=============================
SYNTAX:
=======
DROP PUBLIC SYNONYM <SYNONYM NAME>;
EX:
DROP PUBLIC SYNONYM PS11;
Ex:
COLLEGE_ENROLLMENT_DETAILS
Ex:
SELECT * FROM S2;
purpose:
========
1. security
> column level
> row level
2. can stored query.
3. to convert complex query into simple query.
4. to check data integrity rules while inserting/ accessing data from a base table.
TYPES OF VIEWS:
===============
1. simple views
2. complex views
1. simple views:
================
- when we created a view to access the required data / information from a single base table is called as
"smiple view".
- by default simple views are supporting dml operations.
76
syntax:
=======
create view <view name> as <select query>;
Ex:
create a view to access data from dept table?
SQL> CREATE VIEW V1 AS SELECT * FROM DEPT;
TESTING:
SQL> INSERT INTO V1 VALUES(50,'DBA','HYD');
SQL> UPDATE V1 SET LOC='PUNE' WHERE DEPTNO=50;
SQL> DELETE FROM V1 WHERE DEPTNO=50;
Ex:
create a view to access empno,ename,sal from emp
table?
SQL> CREATE VIEW V2 AS SELECT EMPNO,ENAME,SAL FROM EMP;
TESTING:
SQL> INSERT INTO V2 VALUES(1122,'YUVIN',4000);
Ex:
create a view to access employees details who are working under deptno
is 20?
SQL> CREATE VIEW V3 AS SELECT * FROM EMP WHERE DEPTNO=20;
VIEW OPTIONS:
=============
i) with check option:
=====================
- it is a constraint which is used to check values with user defined condition was given in the select query at
the time of view creation.
- by using "with check option" statement we can restricted rows on base table through a view.
EX:
create view to display and accept employees details whose
salary is 3000?
SQL> CREATE VIEW V4 AS SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL=3000;
Testing:
SQL> INSERT INTO V4 VALUES(1122,'YUVIN',1500);---allowed
SQL> INSERT INTO V4 VALUES(1123,'BHUVIN',4500);---allowed
SQL> INSERT INTO V4 VALUES(1124,'SUMAN',3000);---allowed
Ex:
SQL> CREATE VIEW V5 AS SELECT EMPNO,ENAME,SAL FROM EMP
2 WHERE SAL=3000 WITH CHECK OPTION;
77
TESTING:
SQL> INSERT INTO V5 VALUES(1125,'WARNER',1200);---not allowed
SQL> INSERT INTO V5 VALUES(1125,'WARNER',5000);---not allowed
SQL> INSERT INTO V5 VALUES(1125,'WARNER',3000);---- allowed
EX:
SQL> CREATE VIEW V6 AS SELECT * FROM DEPT WITH READ ONLY;
TESTING:
INSERT INTO V6 VALUES(50,'SAP','PUNE')
ERROR at line 1:
ORA-42399: cannot perform a DML operation on a read-only view
2) COMPLEX VIEWS:
=================
- when we created a view based on,
> multiple tables
> group by
> having
> distinct
> aggregative / grouping functions
> set operators
> joins
> subquery
- by default complex view is not allowed DML operations.
EX:
SQL> CREATE VIEW V8 AS
2 SELECT DEPTNO,SUM(SAL) SUM_OF_SALARY FROM EMP GROUP BY DEPTNO;
TESTING:
INSERT INTO V8 VALUES(40,4500)
ERROR at line 1:
ORA-01733: virtual column not allowed here
FORCE VIEW:
===========
- when we created a view without base table is called as "force view".
syntax:
=======
create force view <view name> as <select query>;
Ex:
SQL> CREATE FORCE VIEW FV1 AS SELECT * FROM TEST88;
Warning: View created with compilation errors.
78
NOTE:
=====
- here view is created but not working if we want to active a
force view then we should create a base table on the name of
test88.
ex:
SQL> CREATE TABLE TEST88(SNO INT);
SQL> INSERT INTO TEST88 VALUES(1021);
SNO
----------
1021
SNO
----------
1021
MATERIALIZED VIEW:
==================
- it is also created based on a base table just like a view
but view doesnot store data whereas mview can store data.
VIEWS MVIEWS
====== =======
1. not storing data. 1. store data.
syntax:
=======
create materialized view <view name> as <select query>;
EX:
create table test66(sno int,name varchar2(10));
create view v66 as select * from test66;
create materialized view mv66 as select * from test66;
79
select * from v66;
select * from mv66;
REFRESHING METHODS:
===================
I) ON DEMAND:
============
- it is a default refresh method to refreshing a mview in database.
syntax:
=======
execute dbms_mview.refresh('mview name');
Ex:
execute dbms_mview.refresh('mv66');
select * from mv66;
II) ON COMMIT:
===============
SYNTAX:
=======
CREATE MATERIALIZED VIEW <VIEW NAME>
REFRESH ON COMMIT
AS <SELECT QUERY>;
EX:
SQL> CREATE TABLE TEST77(EID INT,ENAME VARCHAR2(10));
Table created.
80
4 SELECT * FROM TEST77;
TESTING:
INSERT INTO TEST77 VALUES(1,'MILLER');
COMMIT;
NOTE:
======
- to view all materialized views in oracle then we use a datadictionary
is called as "user_mviews".
EX:
SQL> DESC USER_MVIEWS;
SQL> SELECT MVIEW_NAME FROM USER_MVIEWS;
MVIEW_NAME
------------
MV77
MV66
EX:
DROP MATERIALIZED VIEW MV66;
SEQUENCE:
=========
- it is db object which is used to generate the sequence numbers
on a particular column automatically.
- it will provide "auto incremental value" facility.
syntax:
======
create sequence <sequence name>
[start with n]
[minvalue n]
[increment by n]
[maxvalue n]
[no cycle / cycle]
[no cache / cache n];
start with n:
=============
81
- it specify starting value of a sequence.
here "n" is number.
minvalue n:
===========
- it shows minimum value in the sequence. here "n" is number.
increment by n:
===============
- it specify the incremental value in between sequence numbers.here "n" is number.
maxvalue n:
===========
- it shows the maximum value in the sequence.here "n" is number.
no cycle:
=========
- it is a default attribute.when we create a sequence object with "no cycle" then the set of sequence
numbers are not repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3;
output:
=======
1
2
3----seq.stop
cycle:
=======
- when we create a sequence object with "cycle" then the set of
sequence numbers are repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3
cycle;
output:
=======
1
2
3
1
2
3
1
2
82
3..............
NO CACHE:
=========
- it is a defult attribute.when we created a sequence
with "no cache" then the set sequence numbers are saved into
database memory.
- so that whenever user want to access the required data
based on sequence number then that user request will to database
each and every time so that the no.of user requests are incresing
the burdon on database and degrade the performance of database.
CAHCE n:
========
- when we created a sequence object with "cache" then
the set sequence numbers are saved in database and also a
copy of sequence numbers are kept into cache memory so that
whenever a user want to access data based on sequence number
then the user request will to cache memory instead of database
memory.so that the no.of user request's will reduce and improve
the performance of database.a cache file size starts with minimum
2kb.
NOTE:
=====
- when we work on sequence object to generate sequence numbers
then we use the following two pseudo columns are
i) nextval: generating next by next value.
ii) currval : can see the current value in the sequence
1
2
3 nextval = 6,currval=5
4
5
EX1:
SQL> CREATE SEQUENCE SQ1
2 START WITH 1
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 3;
TESTING:
========
SQL> CREATE TABLE TEST22(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST22 VALUES(SQ1.NEXTVAL,'&NAME');
Enter value for name: A
/
Enter value for name: B
/
83
Enter value for name: C
/
Enter value for name: D
ERROR at line 1:
ORA-08004: sequence SQ1.NEXTVAL exceeds MAXVALUE and
cannot be instantiated
SNO NAME
---------- ----------
1A
2B
3C
ALTERING A SEQUENCE:
====================
SYNTAX:
=======
ALTER SEQUENCE <SEQUENCE NAME> <ATTRIBUTE NAME> n;
EX:
SQL> ALTER SEQUENCE SQ1 MAXVALUE 5;
Sequence altered.
SNO NAME
---------- ----------
1A
2B
3C
4D
5E
EX2:
SQL> CREATE SEQUENCE SQ2
2 START WITH 1
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 3
6 CYCLE
7 CACHE 2;
Sequence created.
TESTING:
84
SQL> CREATE TABLE TEST23(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST23 VALUES(SQ2.NEXTVAL,'&NAME');
Enter value for name: X
/
.......................
/
........................
EX3:
SQL> CREATE SEQUENCE SQ3
START WITH 3
MINVALUE 1
INCREMENT BY 1
MAXVALUE 5
CYCLE
CACHE 2;
TESTING:
SQL> CREATE TABLE TEST24(SNO INT,NAME VARCHAR2(10));
NOTE:
=====
- if we want to view all sequence objects in oracle then
use a datadictionary is "user_sequences".
EX:
SQL> DESC USER_SEQUENCES;
SQL> SELECT SEQUENCE_NAME FROM USER_SEQUENCES;
EX:
DROP SEQUENCE SQ1;
==============================================================
SEQUENCE:
=========
- it is db object which is used to generate the sequence numbers
on a particular column automatically.
85
- it will provide "auto incremental value" facility.
syntax:
======
create sequence <sequence name>
[start with n]
[minvalue n]
[increment by n]
[maxvalue n]
[no cycle / cycle]
[no cache / cache n];
start with n:
=============
- it specify starting value of a sequence.
here "n" is number.
minvalue n:
===========
- it shows minimum value in the sequence.
here "n" is number.
increment by n:
===============
- it specify the incremental value in between sequence numbers.
here "n" is number.
maxvalue n:
===========
- it shows the maximum value in the sequence.
here "n" is number.
no cycle:
=========
- it is a default attribute.when we create a sequence object
with "no cycle" then the set of sequence numbers are not repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3;
output:
=======
1
2
3----seq.stop
cycle:
=======
- when we create a sequence object with "cycle" then the set of
86
sequence numbers are repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3
cycle;
output:
=======
1
2
3
1
2
3
1
2
3..............
NO CACHE:
=========
- it is a defult attribute.when we created a sequence with "no cache" then the set sequence numbers are
saved into database memory.
- so that whenever user want to access the required data based on sequence number then that user
request will to database each and every time so that the no.of user requests are increasing the burdon on
database and degrade the performance of database.
CAHCE n:
========
- when we created a sequence object with "cache" then the set sequence numbers are saved in database
and also a copy of sequence numbers are kept into cache memory so that whenever a user want to access
data based on sequence number then the user request will to cache memory instead of database memory.
so that the no.of user request's will reduce and improve the performance of database.a cache file size
starts with minimum 2kb.
NOTE:
=====
- when we work on sequence object to generate sequence numbers then we use the following two pseudo
columns are
i) nextval: generating next by next value.
ii) currval : can see the current value in the sequence
1
2
3 nextval = 6,currval=5
4
5
EX1:
CREATE SEQUENCE SQ1 START WITH 1 MINVALUE 1 INCREMENT BY 1 MAXVALUE 3;
87
TESTING:
========
SQL> CREATE TABLE TEST22(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST22 VALUES(SQ1.NEXTVAL,'&NAME');
Enter value for name: A
/
Enter value for name: B
/
Enter value for name: C
/
Enter value for name: D
ERROR at line 1:
ORA-08004: sequence SQ1.NEXTVAL exceeds MAXVALUE and
cannot be instantiated
SNO NAME
---------- ----------
1A
2B
3C
ALTERING A SEQUENCE:
====================
SYNTAX:
=======
ALTER SEQUENCE <SEQUENCE NAME> <ATTRIBUTE NAME> n;
EX:
SQL> ALTER SEQUENCE SQ1 MAXVALUE 5;
Sequence altered.
SNO NAME
---------- ----------
1A
2B
3C
4D
5E
EX2:
SQL> CREATE SEQUENCE SQ2 START WITH 1 MINVALUE 1 INCREMENT BY 1 MAXVALUE 3 CYCLE CACHE 2;
Sequence created.
88
TESTING:
SQL> CREATE TABLE TEST23(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST23 VALUES(SQ2.NEXTVAL,'&NAME');
Enter value for name: X
/
.......................
/
........................
EX3:
SQL> CREATE SEQUENCE SQ3
START WITH 3
MINVALUE 1
INCREMENT BY 1
MAXVALUE 5
CYCLE
CACHE 2;
TESTING:
SQL> CREATE TABLE TEST24(SNO INT,NAME VARCHAR2(10));
NOTE:
=====
- if we want to view all sequence objects in oracle then
use a datadictionary is "user_sequences".
EX:
SQL> DESC USER_SEQUENCES;
SQL> SELECT SEQUENCE_NAME FROM USER_SEQUENCES;
EX:
DROP SEQUENCE SQ1;
==============================================================
PARTITION TABLE:
================
1. RANGE PARTITION
2. LIST PARTITION
3. HASH PARTITION
89
1. RANGE PARTITION
===================
- created partition table based on the given range value.
syntax:
=======
create table <tn>(<col1> <dt>[size],.....................)
partition by range(<key column name>)
(partition <partition name1> values less than(value),
partition <partition name2> values less than(value),
....................................................
....................................................);
Ex:
CREATE TABLE TEST1(EID INT,ENAME VARCHAR2(10),SAL NUMBER(10)) PARTITION BY RANGE(SAL)
(PARTITION P1 VALUES LESS THAN(500),PARTITION P2 VALUES LESS THAN(1000),PARTITION P3 VALUES
LESS THAN(2000));
EX:
SELECT * FROM TEST1 PARTITION(P1);
2. LIST PARTITION:
===================
- created partition table based on the given list of values.
syntax:
=======
create table <tn>(<col1> <dt>[size],............................)
partition by list(<key column name>)
(partition <partition name1> values(v1,v2,......),
partition <partition name2> values(v1,v2,........),
.................................................,
.................................................,
partition others values(default));
90
Ex:
CREATE TABLE TEST2(CID INT,CNAME VARCHAR2(10))PARTITION BY LIST(CNAME)(PARTITION P1
VALUES('ORACLE','MYSQL'),PARTITION P2 VALUES('JAVA','PHP','.NET'),PARTITION OTHERS VALUES
(DEFAULT));
CID CNAME
---------- ----------
1 ORACLE
3) HASH PARTITION:
=================
- CREATED PARTITION TABLE BASED ON HASH ALGORITHM BY ORACLE SERVER
BY DEFUALT.
SYNTAX:
=======
CREATE TABLE <TN>(<COL1> <DT>[SIZE],.......)
PARTITION BY HASH(COLUMN NAME) PARTITIONS <NUMBER>;
EX:
CREATE TABLE TEST3(ENAME VARCHAR2(10),SAL NUMBER(10)) PARTITION BY HASH(SAL) PARTITIONS 5;
NOTE:
=====
- IF WE WANT VIEW ALL PARTITIONS OF A PARTICULAR TABLE THEN WE USE THE FOLLOWING
DATADICTIONARY IS "USER_TAB_PARTITIONS".
EX:
DESC USER_TAB_PARTITIONS;
SELECT PARTITION_NAME FROM USER_TAB_PARTITIONS WHERE TABLE_NAME='TEST3';
91
EX:
SQL> ALTER TABLE TEST1 ADD PARTITION P4 VALUES LESS THAN(3000);
EX:
SQL> ALTER TABLE TEST1 DROP PARTITION P1;
locks:
======
- to prevent unauthorized access for our resource.
1. row level locking
2. table level locking
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm
SQL> UPDATE MYDB4PM.EMP SET SQL> UPDATE EMP SET
SAL=1100 WHERE EMPNO=7369; SAL=2200 WHERE EMPNO=7369;
[ row is locked ] [ we cannot perform update
-operation ]
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm
SQL> SELECT * FROM MYDB4PM.EMP SQL> UPDATE EMP SET WHERE DEPTNO=10 FOR UPDATE; SAL=3300
WHERE DEPTNO=10;
[ rows are locked ] [ we cannot perform update-operation ]
92
SQL> commit / rollback; 3 rows updated.
[ lock is releasing]
DEAD LOCK:
==========
- both users resources are under waiting position is called as dead lock.
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm
SQL> UPDATE MYDB4PM.EMP SET SQL> UPDATE EMP SET SAL=5500 SAL=4400 WHERE EMPNO=7369;
WHERE EMPNO=7788;
[ row is locked ] [ row is locked ]
SQL> UPDATE MYDB4PM.EMP SET SQL> UPDATE EMP SET SAL=7700 SAL=6600 WHERE EMPNO=7788;
WHERE EMPNO=7369;
[ we cannot perform update [ we cannot perform update -operation ] -operation ]
ERROR at line 1:
ORA-00060: deadlock detected while waiting for resource
I) SHARE LOCK:
==============
- IN THIS MECHANISM BOTH USERS CAN LOCK A TABLE.
SYNTAX:
=======
LOCK TABLE <TABLE NAME> IN SHARE MODE;
EX:
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm
SQL> LOCK TABLE MYDB4PM.EMP SQL> LOCK TABLE EMP IN SHARE MODE
IN SHARE MODE;
TABLE(S) LOCKED. TABLE(S) LOCKED.
93
II) EXCLUSIVE LOCK:
===================
- ANY ONE USER CAN LOCK A TABLE.
SYNTAX:
=======
LOCK TABLE <TABLE NAME> IN EXCLUSIVE MODE;
EX:
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm
SQL> LOCK TABLE MYDB4PM.EMP SQL> LOCK TABLE EMP IN EXCLUSIVE MODE;
IN EXCLUSIVE MODE; [ WE CANNOT PERFORM EXCLUSIVE MODE]
TABLE(S) LOCKED.
94