You are on page 1of 29

POINTS

• SQL is not case sensitive but Data is case sensitive


• Column name in the tables are always displayed in CAPS.
• Truncate and renameare not DDL but mostly associated to DDL Group
• A variable is a space associated with some value for temporary period of time.
• All the statements are executed by SQL Engine.
• Table name cannot be more than 30 characters.
• Dual is a dummy table provided by oracle DB. It holds single value.
• NULL is not a value

GROUP COMMAND USE


DDL CREATE, ALTER, DROP Use to build and modify the structure of the
table and other objects in DB.
DML INSERT, UPDATE, DELETE, SELECT Used to maintain and manage data in the
table.
TCL COMMIT, ROLLBACK Used for transaction control in the DB
DCL GRANT, REVOKE Used for access control in the DB

Data Type Description


Number Accepts numeric value. If size not mentioned, by default take 37
Varchar2 Accepts char+number. Variable length. Size needs to be specified
Char Accepts char+number. Fixed length. If size not mentioned, by default 1.
Date Accepts Date in the format dd-mon-yyyy

Varchar2 (Variable length)


Example: Name Varchar2 (10)
S H I V A
From 10 arrays 5 arrays are allocated and unused arrays are release after allocation in DB.

Char (Fixed length)


Example: Name Char (10)
S H I V A
From 10 arrays 5 arrays are allocated and unused arrays are not release after allocation in DB.
Rest 5 arrays (space) are wasted / blocked.

When to use Varchar2 and Char?


✓ When we are definite about the value use Char like M/F, Y/N, T/F etc.
✓ Try using char reason been – in term of binary format char takes less space as compared
to varchar2.

Clear the screen cl scr


View the structure of the table desc<table_name>
Show the current logged in user show user
How to view the last query Ed
CREATE
CREATE TABLE <TABLE_NAME> (Col_name<Data Type><Size), Col_name2 <Data Type><Size),
…….);
CREATE TABLE Customer (ID number(5), Name varchar2(10), Address varchar2(10));

What all can be done using ALTER command?


➢ Add New Column
➢ Remove existing column
➢ Change Data Type
➢ Increase Size
➢ Decrease Size

ALTER
ALTER TABLE <Existing Table_name>ADD<New_Column_name><Data Type><Size>;
ALTER TABLE Customer ADD Mob number(10);
Note: in case of multiple column use ().

ALTER TABLE Customer DROP column email;

Modify the data type of column ID from number to varchar2(7).


ALTER TABLE Customer MODIFY (ID varchar2(7));

DROP
The complete structure of the table can be deleted using DROP command.
DROP TABLE <Table_name>;

Note: when the table is dropped it make a copy of it but same can be retrieved by DBA.
Select * from tab; (this would return 10 table)
Drop table emp; (emp is one of the table, after using drop command we could still see 10 table)

To drop the table permanently use “PURGE”.


DROP TABLE <Table_name>PURGE;

RENAME
Rename the table_name.
RENAME <Existing_table_name> to <New_table_name>;

INSERT
INSERT INTO <Table_name> VALUES (value1, value2,…..);

INSERT INTO Customer VALUES (1, ‘GURU’,’BANG’); ----- insert single record.
INSERT INTO Customer VALUES (&ID, ‘&NAME’,’&LOC’); ----- multiple record use back slash “/”
How to insert blank value?
INSERT INTO Customer VALUES(NULL, ‘PAR’, ‘BNG’);
INSERT INTO Customer VALUES(“ “, ‘PAR’, ‘BNG’);
insert into customer2 values(1, AAA', 'BTM');
ORA-01756: quoted string not properly terminated
insert into customer2 values(1, '"AAA"', 'BTM');
1 "AAA" BTM
insert into customer2 values(1, 'BBB' 'BTM','BNG');
ORA-00917: missing comma
insert into customer2 values(1, 'BBB', 'BTM','BNG');
ORA-00913: too many value
insert into customer2 values(&id, &name', '&address);
7 'HHHH JC ROAD'
Entering value for specific column say id and name only?
insert into customer2(id, name) values (9, 'kkk');
INSERT INTO Z VALUES ( , 'R');
ORA-00936: missing expression

DB design / Architecture/TCL commands:


✓ Any DB architecture will have minimum of 2 Redolog and one Data file. Redologs can be
more than 2 depends upon the sensitivity of data.
✓ Redolog2 is a backup for redolog1, in case of any issue/corrupt the data can be retrieved
from Redolog2.
✓ Whenever a statement /command is entered in the SQL, the data will get stored in the
Redolog1 and Redolog2
✓ Commit (Save) and Rollback (Undo).
✓ Commit: Transforming the data from Redolog to Datafile.
✓ Rollback: Will delete the data from Redolog file (buffer).
✓ Once commit the data will be deleted from Redolog (1 & 2). The same will be copied to
the datafile.
✓ Redolog data can be rollback.
✓ SQL *Plus Buffer store the SQL statements.

Temporary storage
RedoLog1

RedoLog2

Permanent storage Data file


UPDATE
Modify data of table – single/multiple/all records of the table.
UPDATE <Table_name> SET <Col_name> = <New_Col_Name>;
UPDATE Customer SET Address=’BNG’, name=’Deepak’ where ID=2;

Change the address and name of ID 1 and 3 in customer2 table?


UPDATE CUSTOMER2 SET ADDRESS='WF', NAME='CCC' WHERE ID IN(1, 3)

DELETE
We can delete the data from the table.
DELETE FROM <Table_name>;
DELETE <Table_name>;
Delete the data from table customer2 where id is 1 and 3?
delete customer2 where id in(1,3);

Delete Vs Rollback
Delete: delete the data from the table, after commit.
Rollback: delete the data from buffer, before commit.

Why Select is a DML command?


By functionality SELECT do not manipulate data. It is used before/after manipulation of data
using DML statements, that’s the reason classified as DML>

select 8 from customer1;


suppose the table has 11 rows, then the above will display 11 times 8 with column name also
as 8.
select 1 from customer1;
suppose the table has 11 rows, then the above will display 11 times 1 with column name also
as 1.
select a from customer1;
ORA-00904: "A": invalid identified
Select the records detail where name is ram?
select * from customer1 where name='RAM'; (no row selected)
select * from customer1 where name='ram'; (will display the records details, reason been the
data is case sensitive)
Get the value of letter 'M','m', 'Meghana?
select ascii('m') from dual; [109]
select ascii('M') from dual; [77]
select ascii('Meghana') from dual; [77,the dual return the single value]
select the data from emp where comm is blank?
select * from emp where comm is null;
select the data from emp where comm is not blank?
select * from emp where comm is not null;
Will this work: select * from emp where empno=7369, 7499;
No. ORA-00933: SQL command not properly ended
Will this work: select * from emp where empno in (7369, 7499); (YES)

TRUNCATE
Removes the data from the table.
TRUNCATE TABLE <table_name>;

DELETE VS TRUNCATE

SNO DELETE TRUNCATE


Delete data from table, but table structure Delete data from table, but table structure
1 remains remains
Delete specific selective data using 'where' Delete the entire data as 'where' clause cannot be
2 clause used with this.
3 Can be rollback Cannot be rollback. Auto Commit.
4 Delete row by row Delete whole data at once
5 Low performance High performance
6 Data will be deleted but arrays still remains Data will be deleted along with arrays.
Important:
Truncate is a combination of Drop and Create command. The table will be DROP first and then
the structure would be created.

Aggregate/group function
These are used to summarize the detailed data.
Count the number of records in a table.
Select count (emp) from emp;
select count(*) from emp;
count() will not count the NULL values. Count(*) will count all the columns count
and display the highest count.
Count() Select count(1) from emp; //count the records using first column
summarize the detailed value of specified column
Sum() select sum(sal) from emp where deptno=10;
returns max/highest value from the specified column
Max() select max(sal) from emp;
returns min/lowest value from the specified column
Min() select min(sal) from emp;
returns the average value of the specified column
Avg() select avg(sal) from emp;
Character function

select empno, INITCAP(ename), INITCAP(job) from emp;


INITCAP() will display the column ename and job with first letter as capital
selectempno, ename, LTRIM(ename) from emp;
LTRIM() in case of any space on the left side the space will get trimmed.
selectempno, ename, RTRIM(ename) from emp;
in case of any space on the left side the space will get trimmed.
Select empno, LTRIM(RTRIM(ename)) ENAME from emp;
RTRIM() First right and then left trim or we can use TRIM function.
select empno, TRIM(ename) ENAME from emp;
select empno, INITCAP(LTRIM(RTRIM(ename))) ENAME from emp;
TRIM() first right, left trim and then Initial cap letter
UPPER() select empno, UPPER(ename) ENAME from emp;
LOWER() select LOWER(ename) ENAME from emp where deptno=10;
Stands for Null Value. Its replacing null value with value provided by the user. It
takes two parameter(column name, value to be inserted for blank/null)
Select empno, NVL (ename, 'NSR') ENAME from emp;

select empno, NVL(comm, 100) COMM from emp


this will display value as 100 where the commision is null

select empno, NVL(comm, 'NO COMM') COMM from emp


NVL() ORA-01722: invalid number

Alias
It basically gives the name to the column for display purpose.
Select count(empno) ENO from emp;
Select count(empno) as ENO from emp;

Select count(empno) ENO, sum(sal) ‘TOTAL SAL’, max(sal) HIGH_SAL, min(sal) LOW_SAL,
avg(sal) AVG_SAL from emp;
Note: while defining the alias, in case of space it should be into single inverted commas (‘ ‘).

“AND”, “OR” & “BETWEEN” conditions


AND = both the condition should be true. Used in select, update and delete statement.
OR = any of the condition to be true. Used in select, update and delete statement.
BETWEEN = retrieve the value within the range.

Select * from emp where job=’Manager’ AND Dept=20;


Select * from emp where job=’Manager’ OR Dept=20;

Select * from emp where SAL BETWEEN 2000 AND 3000;


Select * from emp where SAL BETWEEN 2000 AND 3000 OR SAL BETWEEN 4000 AND 5000;
DECODE
We can decode the value from one format to another.
- (column_name, ‘Seach Value’, ‘Replace Value’) ---- three parameter
- (column_name, ‘Seach Value’, ‘Replace Value’, default) ---- four parameter
Select ID, name DECODE (city, ‘HYD’,’HYDERABAD’, ‘CHN’, ‘CHENNAI’, ‘BNG’, ‘BANGALORE’)
from Customer;
Note: if city column having any other value apart from mentioned in the command it will make
it as ‘NULL’.
- In case we want to display the city as it is then perform:
Select ID, name DECODE (city, ‘HYD’,’HYDERABAD’, ‘CHN’, ‘CHENNAI’, ‘BNG’, ‘BANGALORE’,
city) from Customer;
- In case of we want to display the not mentioned city as a single value (INDIA) do.
Select ID, name DECODE (city, ‘HYD’,’HYDERABAD’, ‘CHN’, ‘CHENNAI’, ‘BNG’, ‘BANGALORE’,
‘INDIA’) from Customer;

The decode query will exit after first match.

CONSTRAINTS

Does not accept NULL value but accept duplicate value.


create table NSR_emp(eno number(5) NOT NULL, name varchar2(10), city
NOT NULL varchar2(10));
Does not accept duplicate but accept NULL values
create table NSR-emp1(eno number(5) UNIQUE, name varchar2(10), city
UNIQUE varchar2(10));
Does not accept NULL and Duplicate value. Each table can have only one primary key.
create table NSR_emp3(ID number(5) primary key, name varchar2(10), city
PRIMARY varchar2(10));
The value in one table must also appear in another table. The reference table is
called the parent while the table with the foreign key is called the child table. The
foreign key in the child table will generally reference a primay key in the parent table.
create table products(pid number(10) not null, sid number(10) not null, CONSTRAINT
FOREIGN fk_suplier FOREIGN KEY(sid) REFERENCES supplier(sid));
This is used to limit the value range that can be placed in a column
create table Customer2(eno number(5), enamevarchar(10), sal number(10)
CHECK CHECK(sal between 3000 and 5000);
It prevents users or applications from entering inconsistent data.
Create table dept(dno number(5) primary key, dname varchar2(10), loc varchar2(10);
REFERENTIAL Create table emp(eno number(5) primary key, ename varchar2(10), sal number(3),
INTEGRITY dno number(5) REFERENCES dept(dno));
Note: we can have many unique constraint per table but only one primary key constraint per
table.
NOT NULL
create table customer(id number NOT NULL, name varchar2(10), loc varchar2(10));
insert into customer values(1,'SIVA', 'BNG');
insert into customer values(1,'SIVA', 'BNG');
insert into customer values(NULL,'SIVA', 'BNG');
ORA-01400: cannot insert NULL into ("SCOTT"."CUSTOMER"."ID")
insert into customer values( ,'SIVA', 'BNG')
ORA-00936: missing expression

UNIQUE
create table customer(id number, name varchar2(10) UNIQUE, loc varchar2(10));
insert into customer values(1,'SIVA', 'BNG');
insert into customer values( NULL,'RAM', 'BNG')
insert into customer values(1,'SIVA', 'BNG');
ORA-00001: unique constraint (SCOTT.SYS_C005988) violated
insert into customer values( ,'SURESH', 'BNG');
ORA-00936: missing expression
CREATE TABLE WELL1(
WNO NUMBER(5) CONSTRAINT PK PRIMARY KEY,
WNAME VARCHAR2(10),
WLOC VARCHAR2(10))
CREATE TABLE WELL(
ID NUMBER(5) CONSTRAINT PK PRIMARY KEY,
NAME VARCHAR2(10) CONSTRAINT NN NOT NULL,
PASSPORT VARCHAR(10) CONSTRAINT UNQ UNIQUE,
SAL NUMBER(7),
CONSTRAINT CHK CHECK (SAL BETWEEN 2000 AND 5000),
WNO NUMBER(5) CONSTRAINT REF REFERENCES WELL1(WNO))

NOT NULL UNIQUE PRIMARY


NULL N Y N
DUPLICATE Y N N

BANK
EMPNO ENAME ADDRESS SAL DNO DNAME PAN PASSPORT A/C PF MOBILE
No
PK NN NN NN NN NN UNQ UNQ UNQ UNQ Constraint
Composite primary key
- 32 columns can be assigned to composite key.
- In a composite key the combination of the column should be unique
- In the flight reservation table it is difficult to put the primary key on a particular column
so we combine the column and make it unique. (FNO, SEAT, JDATE, TRIP NO)
TABLE: Flight reservation
FNO SEAT JDATE FRM DESTINATION TRIP NO
J001 5 1-Jun-14 BNG CHN 1
J001 5 1-Jun-14 CHN BNG 2

Create table flight_reservation(


FNO varchar2(5),
SEAT number(3),
JDATE date,
FRM varchar2(10),
DESTINATION varchar2(10),
“TRIP NO”number(2),
PRIMARY KEY (FNO, SEAT, JDATE, “TRIP NO”));
INSERT INTO FLIGHT_RESERVATION VALUES('J001', 5, '1-JUN-2014', 'BNG', 'DEL', 1);
INSERT INTO FLIGHT_RESERVATION VALUES('J001', 5, '1-JUN-2014', 'DEL', 'BNG', 2)
INSERT INTO FLIGHT_RESERVATION VALUES('J001', 5, '1-JUN-2014', 'DEL', 'BNG', 2)
ORA-00001: unique constraint (SCOTT.SYS_C005989) violated

Column level constraints: constraint applied for more than one column is called column level
constraint. Ex: NOT NULL
Table level constraints:constraints applied to the table are called table level constraints. Ex:
primary key, unique.

User_constraint: it’s displays the constraint applied for a particular table/column.


Select * from user_constraints where table_name=’Customer2’;

How to add and delete the constraints?


ALTER table Customer2 ADD primary key(ID);
ALTER table Customer2 DROP constraint SYS_C005733;

What if the report says the PK is there but still able to insert the duplicate and null values?
- Check the constraint on table
- Check the status of the constraint - ENABLE/DISABLED
There might be possibility the developer would have disabled the constraint because:
he might have forgot to enable it OR when he created the table at that time it would not be
used
Referential integrity:

- Master table should have primary key. Master table should be created first with data.
- Reference column may or may not be same (dno-dno, deptno-dno)
- Relational column – data type should be same.
- Child table column should not be primary key.
- Reference will check the data and display
- It helps to avoid the inconsistency of data
- Referential integrity is defined on Child/detailed table.
- Relationship is created with referential integrity but not with foreign key.
Create table dept(dno number(5) primary key, dname varchar2(10), loc varchar2(10);
Create table emp(eno number(5) primary key, ename varchar2(10), sal number(3), dno
number(5) REFERENCES dept(dno));
Description constraint name Alias C Search condition
NOT NULL SYS_C005998 NN2 C "NAME" IS NOT NULL
CHECK SYS_C005999 CHK C SAL BETWEEN 2000 AND 5000
PRIMARY SYS_C006000 PK_ID P
UNIQUE SYS_C006001 UNQ U
REFERENTIAL SYS_C006002 REF R

On delete cascade
Used to delete the records from the parent table even though records exist in the child table.
Create table emp(eno number(5) primary key, ename varchar2(10), sal number(3), dno
number(5) REFERENCES dept(dno) on delete cascade);

SET OPERATOR
There are four SET operators: Point to considered using SET operators:
1) UNION ➢ The column count should be same.
2) UNION ALL ➢ The column data type should be same
3) MINUS ➢ The column order should be same
4) INTERSECT
UNION
Combine the query result set (not the table), do sorting, remove duplicate and return unique
result set.
Table removing
A Table B Combining sorting duplicate result
X Y 1 1 1 1
1 6 2 1 2 2
2 7 3 2 3 3
3 1 4 2 4 4
4 8 5 2 5 5
5 2 SELECT X FROM A 6 3 6 6
3 UNION 7 3 7 7
9 SELECT Y FROM B 1 4 8 8
2 8 5 9 9
2 6
3 7
9 8
2 9

UNION ALL
Combine the query result set with no sorting and not removing duplicate. This is faster than
UNION as sorting and removing of duplicate activity does not happen.
Table
A Table B Combining result
X Y 1 1
1 6 2 2
2 7 3 3
3 1 4 4
4 8 SELECT X FROM A 5 5
5 2 UNION ALL 6 6
3 SELECT Y FROM B 7 7
9 1 1
2 8 8
2 2
3 3
9 9
2 2
MINUS
Returns all the rows in the first query that are not returned in the second query. The data is
sorted.

Table
A Table B Combining Remove result
X Y 1 Y 4
1 6 SELECT X FROM A 2 Y 5
2 7 MINUS 3 Y
3 1 SELECT Y FROM B 4 N
4 8 5 N
5 2
3
9
2

INTERSECT
Returns rows/records common in both the query set. Sort the data before displaying.

Table
A Table B result
X Y SELECT X FROM A 1
1 6 INTERSECT 2
2 7 SELECT Y FROM B 3
3 1
4 8
5 2
3
9
2

COMMANDS UNION UNION ALL MINUS INTERSECT


select x from A X X X X
<> 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 4, 5 1, 2, 3
select y from B 6, 7, 8, 9 7, 1, 8, 2, 3, 9,
2
Select x from B Y Y Y Y
<> 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 4, 5 1, 2, 3
Select y from A; 6, 7, 8, 9 7, 1, 8, 2, 3, 9,
2
Select empno, ename, job from emp ORA-01789: query block has incorrect number of
<> result columns
Select dept, dname from dept;
Select * from emp ORA-01789: query block has incorrect number of
<> result columns
Select * from dept;
Select empno, ename, sal from emp ORA-01790: expression must have same data types as
<> corresponding expression
Select empno, sal, ename from emp1;
Select * from C X| 1, 1, 2, X| 1, 2, 3, 4, 5, X| 1, 3, X| 2
<> 2, 3, 3, 4, 6, 7, 1, 8, 2, 3, 4, 5 Y| B
Select * from D; 5, 6, 7, 8, 9, 2 Y|A, C,
9 Y|A, B, C, D, E, D, E
Y| A, Z, B, B, C, Z, X, B, D,
Y, C, D, D, X, Y
E, B, C, X,
X
Select * from D X| 1, 1, 2, X| 6, 7, 1, 8, 2, X| 1, 2, X| 2
<> 2, 3, 3, 4, 3, 9, 2, 1, 2, 3, 3, 6, 7, Y| B
Select * from C; 5, 6, 7, 8, 4, 5 8, 9
9 Y| B, C, Z, X, B, Y| Z, Y,
Y| A, Z, B, D, X, Y, A, B, C, D, B, C,
Y, C, D, D, D, E X, X
E, B, C, X,
X
select empno, ename from emp
<>
select deptno, dname from dept; 18 rows 18 rows 18 rows no rows
select deptno, dname from dept
<>
select empno, ename from emp; 18 rows 18 rows 18 rows no rows
Select * from emp
<>
Select * from emp1; 14 rows 28 rows no rows 14 rows
Select empno, ename, sal from emp
<>
Select mgr, ename, comm from emp1; 28 rows 28 rows 14 rows no rows

DISTINCT CLAUSE
Removes the duplicate from the result set.Applied on columns. Used with SELECT statement.
select DISTINCT JOB from emp;
select DISTINCT JOB, DEPTNO from emp;
ORDER BY CLAUSE
Sort the records in the result set.Used with select statement.Should be used at the last of the
query.- By default ASC
Select * from <table> order by <column> ASC OR DESC.
Select * from emp order by sal; OR select EMPNO, ENAME, SAL from emp order by sal ASC;
Select * from emp order by saldesc;

LIKE CLAUSE
Allow to use wildcard (%,_). Used for pattern matching ('%h', '_i%a', '____',). Used with select,
update and delete statement
select * from emp where name like '%r%';

GROUP BY CLAUSE
Used with select statement to collect data across mutliple records and group the results by one
or more particular field and apply an aggregate function to the subset.- Normally used with
aggregate expressions (like sum, count, avgetc). while group by (by deptno), the deptno should
be in selection also, otherwise error.
selectdeptno, sum(sal) from emp group by deptno;

HAVING CLAUSE
Used in combination with GROUP BY clause. Used for filtering the data.Used in select
statement. This was introduced because WHERE clause does not works with aggregate
functions. WHERE clause can be used by group by clause but it has to be used before the group
by clause.
selectdeptno, sum(sal) SALARY from emp group by deptno having sum(sal)>9000;
selectdeptno, sum(sal) SALARY from emp group by deptno having SALARY>9000;
ORA-00904: "SALARY": invalid identifier
Select deptno, sum(sal) SALARY from emp where deptno not in 30 group by deptno
having sum(sal)>9000;

Clause sequence
Clause Order
ORDER
BY 7
FROM 3
WHERE 4
DISTINCT 2
HAVING 6
GROUP
BY 5
SELECT 1
Using clause sequence
SELECT DISTINCT JOB, SUM(SAL) FROM EMP WHERE SAL > 1000 GROUP BY JOB, SAL HAVING
SUM(SAL)>2000 ORDER BY SUM(SAL)

JOINS
It is a query that combines rows from two or more tables, based on a relationship between
certain columns in the table.
If no relationship between the tables, still we can join the table.
Joins are faster than sub-queries.

There are five types of joins:


1) Equi/inner/simple/default join
2) Non-equi join
3) Cross/cartesian product join
4) Self join
5) Outer join
- Left outer join
- Right outer join
- Full outer join

Join query can be written without joins.

EMP1 DEPT1
ENO ENAME SAL DNO DNO DNAME LOC
1 PADMAJA 30000 10 10 IT BNG
2 LAKSHMI 25000 20 20 HR CHN
3 ANAND 25000 30 30 FINANCE HYD
4 ASHWINI 40000 10
5 RUDRA 90000 40

select emp1.eno, emp1.ename, emp1.sal, emp1.dno, dept1.dname, dept1.loc from emp1,


dept1 where emp1.dno=dept1.dno;
OR
selecte.eno, e.ename, e.sal, e.dno, d.dname, d.loc from emp1 e, dept1 d where e.dno=d.dno
SELECT G.X, H.Y FROM G, H WHERE G.X=H.Y; G H
X Y
X Y 1 1
--------- ---------- 2 2
1 1 3 3
2 2
4 5
3 3

EQUI/INNER/SIMPLE/DEFAULT JOIN
- A join with a join condition containing an equality operator (=).
- It combines rows that have equivalent values for the specified columns.

selecte.empno, e.ename, e.job, e.sal, e.deptno, d.dname, d.loc from emp e, dept d where
e.deptno=d.deptno;

CROSS JOIN OR CARTESIAN PRODUCT


It returns the Cartesian product of rows from table in the join.
In other words, it will produce rows which combine each row from the first table with each row
from second table.
SYNTAX: SELECT * FROM EMP,DEPT;
If EMP table has 14 records and DEPT table has 4 records ,it will fetch total (14*4) = 56 records.
It is not used in project, but tester should test without fail.
SELF JOIN
Fetches the two different records from same table with two different column of the same
table.In other words, joining 2 rows and 2 column of the same table.

SQL> select e.empno, e.ename, e.job, m.ename manager from emp e, emp m where
e.mgr=m.empno;

OUTER JOIN G H
(+) Operator is used for outer joins in oracle. X Y
1 1
2 2
3 3
4 5
LEFT OUTER JOIN
Return all rows from the left table, even if there is no matches in the right table.

SQL> SELECT G.X, H.Y FROM G, H WHERE G.X=H.Y(+); ---- (by oracle db)
or
SELECT * FROM G g LEFT OUTER JOIN H h on g.X=h.Y; ---- (by all db)
SELECT * FROM G g LEFT JOIN H h on g.X=h.Y;
X Y
---------- ----------
1 1
2 2
3 3
4
RIGHT OUTER JOIN
Return all rows from the right table, even if there are no matches in the left table.
SQL> SELECT G.X, H.Y FROM G, H WHERE G.X (+) =H.Y; ---- (by oracle db)
SELECT * FROM G g RIGHT OUTER JOIN H h on g.X=h.Y; ---- (by all db)
SELECT * FROM G g RIGHT JOIN H h on g.X=h.Y;

X Y
---------- ----------
1 1
2 2
3 3
5

FULL OUTER JOIN

SQL> SELECT * FROM G g FULL OUTER JOIN H h ON g.X=h.Y;

X Y
---------- ----------
1 1
2 2
3 3
4
5

IMP TABLE FOR JOINS

A B EQUI JOIN LEFT OUTER RIGHT FULL OUTER


JOIN OUTER JOIN JOIN
X Y

A A A A A A A A A A

B B B B B B B B B B

C C C C C C C C C C

D E D _ _ E D _

_ E
SUB-QUERIES
- Sub query or inner query or nested query is a query in a query.
- Usually added in the WHERE clause.
- Used when we know how to search for a value using a SELECT statement, but do not
know the exact value.
- Its an alternate way of returning data from multiple tables.
- Operators used like, =, <, >, >=, <= etc.

Employees located in CHICAGO?


select * from emp where deptno=(select deptno from dept where loc='CHICAGO');

Employee located in CHICAGO and BOSTON?


select * from emp where deptno IN (select deptno from dept where loc IN
('CHICAGO','BOSTON'));

Second highest salary?


select max(sal) from emp where sal< (select max(sal) from emp);
select * from emp where sal= (select max(sal) from emp where sal< (select max(sal) from emp))

Second lowest salary?


select min(sal) from emp where sal> (select min(sal) from emp);
select * from emp where sal = (select min(sal) from emp where sal> (select min(sal) from
emp));

Display max salary of an employee department wise?


SELECT * FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY DEPTNO);
Difference between highest and current sal?
SELECT EMPNO,ENAME,SAL,(SELECT MAX(SAL) FROM EMP) HIGH_SAL ,((SELECT MAX(SAL)
FROM EMP) - SAL) DIFF_SAL FROM EMP;

CO-RELATED SUB QUERY


In this both the inner query and the outer query are interdependent. For every row processed
by the inner query, the outer query is processed as well. The inner query depends on the outer
query before it can be processed.

selectename,sal,deptno from emp a where a.sal< (select avg(sal) from emp b where
a.deptno=b.deptno);
Difference between sub-query and co-related sub-query
In sub-query the inner query can be executed separated. The inner query is not dependent on
main/outer query. Hence it is independent.
In co-related sub-query inner query is dependent on the outer query. Hence both the
dependent on each other.

PSEUDO COLUMNS
There are two pseudo columns:
1) ROWNUM
2) ROWID

ROWNUM
- Can be used in any column
- ROWNUM will support “=” only for first record not for other records.
- ROWNUM will support <, =, <= only.
- ROWNUM does not support “>”.

select ROWNUM slno, empno, ename, job, sal from emp;


 This will display a column by name slno.

select * from emp where ROWNUM <=5;


 Display the first five records.

ROWID
- Will add a unique id for each row. This is the provided by ORACLE DB.

select ROWID, empno, ename, job, sal from emp;


How to find the number of duplicate values? DUPLICATE
ID
select id, count(id) from duplicate group by id having count(id) > 1; // 3 rows 1
select id, count(id) from duplicate group by id having count(id) > 2; // 2 rows 1
select id, count(id) from duplicate group by id having count(id) > 3; // 1 row
4
4
6
6
6
6

select ROWID, id from duplicate;

Delete all the duplicate records and keeping the original ones
selectrowid, id from duplicate a where a.rowid>(select min(rowid ) from duplicate b where
b.id=a.id; //6 rows
delete from duplicate a where a.rowid>(select min(rowid ) from duplicate b where b.id=a.id);

Delete all the original records and keeping the duplicate ones
selectrowid, id from duplicate a where a.rowid< (select max(rowid ) from duplicate b where
b.id=a.id); //6 rows
delete from duplicate a where a.rowid< (select max(rowid ) from duplicate b where b.id=a.id);
Write a single statement with using ROWNUM and ROWID
select ROWNUM, ROWID, EMPNO, ENAME from EMP;

Select all the negative and positive values from the Table?
Select * from emp where sal< 0;//negative
Select * from emp where sal> 0;//positive

CAST FUNCTION
- Use to convert the one data type to another data type.
- Used in SELECT statement.
- It’s for temporary for display purpose only (temporary DB / Buffer).
- Varchar2 can be converted to Char whereas Char cannot be converted to Varchar2.

NSR1 NSR2
NO
ID (number) NAME (varchar2) (number) NAME (char)
1 RAM 1 RAM
2 SIVA 2 SIVA

Select ID, NAME, LENGTH(NAME) from NSR1; //3, 4


Select NO, NAME, LENGTH(NAME) from NSR2; // 10, 10

Select ID, NAME from NSR1


MINUS
Select NO, NAME from NSR2;
 1 RAM , 2 SIVA
Select ID, CAST(NAME as CHAR(10)) NAME from NSR1
MINUS
Select NO, NAME from NSR2;
 No rows fetched
Select ID, NAME from NSR1
MINUS
Select NO,CAST(NAME as VARCHAR2(10)) from NSR2;
 1 RAM , 2 SIVA
VIEWS
A view is a virtual table. A view can derive its data from one or more table. An output of query
can be stored as a view. View act like a table but it does not physically take any space. View is
good way to present data from one user to another user instead of accessing the table directly.
A view in oracle is nothing but a stored sql scripts. View does not contain any data.
Create view <view_name> as Select * from <table_name>;
Create view emp_v as select * from emp;
Drop view <view_name>;

How to see view in the schema?


Select * from tab;
 Check the TABLE TYPE, it should be VIEW.

DCL
Two command:
1) Grant
2) Revoke

Two type of permission:


User Level Permission Table Level Permission
CONNECT INSERT
RESOURCE UPDATE
DBA DELETE
SELECT

Login as
username = sys/admin as sysdba
password and host string =blank or nothing

• create user <user_name> identified by <pwd>;


create user nsr_fin identified by etl;
• login as username = nsr_fin and password = etl
ORA-01045: user nsr_fin lacks create session privileges: logon denied
• grant connect to nsr_fin;
• try relog on. Connected successfully.
• Try creating a table:
ORA-01031: insufficient privileges
• Grant permission for creating the table
grant resource to nsr_fin; //successful
• Relogin: nsr_fin/etl and create the table. Now it should allow to create the table.
• Grant dba to nsr_fin
• Grant select, insert, delete, update on <table_name> to <user>;
Grant select, insert, delete, update on emp1 to nsr_fin;

• Grant select, insert, delete, update on <table_name> to <user>;


Grant select, insert, delete, update on emp1 to nsr_fin;
• revoke select, insert, delete, update on <table_name> to <user>;
revoke select, insert, delete, update on emp1 to nsr_fin;
• revoke Resource from <table_name>;

DATE FUNCTIONS

Select sysdate from dual;


 12-JUL-14
Select to_char(sysdate,’mm-dd-yy’) from dual;
 07-12-14
Select to_char(sysdate, ‘dd/mm/yy/’) from dual;
 12/07/14
Select to_char(sysdate,’day-month-yyyy’) from dual;
 SATURDAY-JULY-TWENTY FOURTEEN
Select to_char(sysdate,’dd-mm-yyyy hh:mm:ss’) from dual;
 12-07-2014 08:07:00
Note: if crossed checked with system time the hh:mm:ss,the mm would display month
instead minutes. In order to display minutes use mi
Select to_char(sysdate,’dd-mm-yyyy hh:mi:ss’) from dual;
 12-07-2014 08:48:51
Select to_char(sysdate,’dd/month/yyyy’) from dual;
 12/JULY/2014
Select sysdate+1 from dual;
 13-JUL-14
Select sysdate-1 from dual;
 11-JUL-14
Select next_day(sysdate,’SUNDAY’) from dual;
 13-JUL-14
Select add_months(sysdate,1) from dual;
 12-AUG-14
Select add_months(sysdate,3) from dual;
 12-OCT-14
Select last_day(’02-FEB-14’) from dual;
 28-FEB-14
Select last_day(’03-JAN-`15’) from dual;
 31-JAN-15
Select sysdate, last_day(sysdate) “LASTDAY” from dual;
 12-JUL-14 31-JUL-14
Select months_between(’10-JUL-14’, ’10-JAN-13’) “months” from dual;
 18
Display the employee joining date and number of years of experience:
Select empno, ename, sal, to_char(hiredate, ‘yyyy’) DOJ, tochar(sysdate, ‘yyyy’) –
to_char(hiredate,’yyyy’) from emp;

CASE STATEMENT
It uses WHEN and THEN. Can be used for select, update and delete statement.
SELECT EMPNO, ENAME, SAL,
CASE
WHEN SAL > 4000 THEN ‘GRADE-A’
WHEN SAL > 2000 AND SAL < 4000 THEN ‘GRADE-B’
ELSE
‘GRADE-C’
END
GRADE
FROM EMP ORDER BY SAL DESC;

Note: The Grade after END is the alias. The case statement starts from beginning and check for
matched record, if matched then exit.

STRING FUNCTION

INSTR() FUNCTION
✓ By using the INSTR FUNCTION we will get the position of char from a string.
✓ If the start position is not mentioned in query, By default, it will consider 1st position.
✓ If the start position is negative, the function counts back start position number of
characters from end of string and then searches towards the beginning of string.

SELECT INSTR('NSR TECHNOLOGIES','E') "POSITION CHECK" FROM DUAL;


 6
SELECT INSTR('NSR TECHNOLOGIES','E',2) "POSITION CHECK" FROM DUAL
 6
SELECT INSTR('NSR TECHNOLOGIES','E',8) "POSITION CHECK" FROM DUAL;
 15
SELECT INSTR('NSR TECHNOLOGIES','E', -8) "POSITION CHECK" FROM DUAL;
 6
SELECT INSTR('NSR TECHNOLOGIES','E',-10) "POSITION CHECK" FROM DUAL;
 6
SELECT INSTR('NSR TECHNOLOGIES','E',-11) "POSITION CHECK" FROM DUAL;
 6
SELECT INSTR('NSE TECHNOLOGIES','E',-12) "POSITION CHECK" FROM DUAL
 3
SELECT INSTR('NSR TECHNOLOGIES','E',-12) "POSITION CHECK" FROM DUAL;
 0

SUBSTR() FUNCTION
✓ We can get piece of char from string or substring of a string.
✓ Substr() has three parameters:
SUBSTR(<string>,<start position>,<length>);
- <string> is the source string
- <start position> is the position for extraction
- <length> number of character to extract

Select substr(‘nsr technologies’, 5, 4) from dual;


 TECH
Select substr(‘nsr technologies’, 5, 5) from dual;
 TECHNOLOGIES

Write a query to separate Name and Domain?


ID NAME EMAIL
1 RAM ram@gmail.com
2 SHIVA shiva@hotmail.com
3 HARI hari@yahoo.com
4 RUDRA rudra@gmail.com
To display column names ==
Select ‘Name|Domain’ from dual;
select substr(email, 1, (instr(email,'@')-1)) || '|' || substr(email,(instr(email,'@')+1)) as
NameDomain from test;

INLINE QUERY
Any query that start after the FROM clause is an inline query where as the query that starts
after WHERE clause is sub-query.
Inline == after FROM
Sub-query == after WHERE
SELECT EMPNO,ENAME,SAL,HIGH_SAL ,HIGH_SAL-SAL AS DIFF_SAL FROM (SELECT
EMPNO,ENAME,SAL,(SELECT MAX(SAL) FROM EMP) AS HIGH_SAL FROM EMP);
DENSE_RANK()
SQL>SELECT EMPNO,ENAME,SAL,DENSE_RANK() OVER (ORDER BY SAL) AS RANK FROM EMP;

RANK()
SQL>SELECT EMPNO,ENAME,SAL,RANK() OVER (ORDER BY SAL) AS RANK FROM EMP;
Nth HIGEST SALARY:
SELECT * FROM (SELECT EMP.*,DENSE_RANK() OVER (ORDER BY SAL DESC) AS RANK FROM
EMP) WHERE RANK = &RANK

Nth LOWEST SALARY:


SELECT * FROM (SELECT EMP.*,DENSE_RANK() OVER (ORDER BY SAL) AS RANK FROM EMP)
WHERE RANK = &RANK;

You might also like