0% found this document useful (0 votes)
4 views75 pages

SQL Notes

The document provides an overview of PL/SQL and Oracle database concepts, including definitions of databases, RDBMS, SQL, and PL/SQL, as well as details on data types, SQL components, and DDL, DML, TCL, and DCL commands. It explains the structure and manipulation of tables, including commands for creating, altering, and deleting tables, as well as data insertion, updating, and deletion. Additionally, it covers transaction control, data access permissions, and querying techniques in Oracle databases.

Uploaded by

varunreddy2427
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views75 pages

SQL Notes

The document provides an overview of PL/SQL and Oracle database concepts, including definitions of databases, RDBMS, SQL, and PL/SQL, as well as details on data types, SQL components, and DDL, DML, TCL, and DCL commands. It explains the structure and manipulation of tables, including commands for creating, altering, and deleting tables, as well as data insertion, updating, and deletion. Additionally, it covers transaction control, data access permissions, and querying techniques in Oracle databases.

Uploaded by

varunreddy2427
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 75

PL/SQL NOTES : (link) Oracle Apps notes: (Link)

Database:
It is a collection of "related and meaningful information" stored centrally at one location.

RDBMS: (Relational Database Management system)


RDBMS is a database management system where data is stored in the form of tables and each table contains rows and columns.
It is a software used to insert,update,delete the records in related tables.

Field :
Each column in a table is called a Field or collection of related data is called a Field.
Record :
Each row in a table is called Record or collection of related fields are called Record.

Components in Oracle Database:


SQL
PL/SQL

SQL→ Structured Query Language


PL/SQL→ Procedural Language using SQL

SQL:
→ SQL stands for structured query language.
→ SQL was initially developed at IBM in 1970's.
→ SQL is an open source anybody can use free of cost.
→ It's pronounced as S.Q.L/sequel
→ It is a language which is used to communicate with the Relational database management systems like ORACLE,MS ACCESS,MS
SQL SERVER,MY SQL,DB2(IBM),SYBASE etc.
→ SQL is a standard language designed for accessing and managing data in relational database management systems.
→ It is used for accessing and manipulating databases such as insert,update,delete and SELECT
→ SQL is a nonprocedural language.
→ SQL is a not case sensitive language.
Query:
→ A query is a request for data or information from a database table or combination of tables.
→ Queries are used to tell what we require from the database.

data dictionaries (or) read only tables:


- whenever we are installing oracle s/w internally oracle server is creating some predefined tables are called as "data
dictionaries".these
Data dictionaries are used to store the information about db objects such as tables,indexes,views,synonyms,..............etc.
- these data dictionaries are supporting "select" and "desc" commands only.so that data dictionaries are also called as "read
only tables" in oracle db.
- if we want to view all data dictionaries in oracle db then we follow the following syntax
select * from dict;

to view all column information of a particular table then we use the "user_tab_columns" data dictionary.

to view a logical condition of check constraint then we need to call the "search_condition" column from "user_constraints"
data dictionary.

- if we want to view the constraint name along with the column name of a particular table then we use the "
user_cons_columns " data dictionary.

base tables for any type of database objects

Dba_objects → Display tables from all different schemas.


all_objects → Display tables with in the schema (including the tables which have grant access to schema).
user_objects → Display tables which are created in the schema.

EX: select * from dba_objects

where object_type='table' and object_name='EMP'; → (always use capital inside single quote to get the data)

base tables for table names


all_tables
User_tables
ALL_tab_columns
user_tab_comments
all_col_comments
user_synonyms
All_synonyms
All_views
User_views
All_sequences
User_indexes
All_indexes
all_ind_columns
ex: select * from all_tables
where table_name='EMP';

COMPONENTS OF SQL:

DDL
DML
DQL/DRL
TCL
DCL

Data Types:
It is used to represent what type of information is stored into the column.(What type of data you need to maintain in a column).

There are two types.

a)Simple data type → Provided by oracle automatically.

NUMERIC DATA TYPES


used to represent number data.
Characters allowed (0-9,.,+,-)

<col_name> NUMBER(P) → store integer values


→ It is used to store Integer values and its range is 1-38.
<col_name> NUMBER(P,S) → store float values
precision(p) counting all digits including left & right sides of given float expression.
scale(s): counting only right digits of a float expression.
PRECISION and SCALE are optional.
But precision is mandatory if we need to select scale we can use number alone without mentioning any size

CHARACTER DATA TYPES/ STRING DATA TYPES


used to represent character information.
Characters allowed a-z,A-Z,0-9,all special characters.

<col_name> CHAR(<SIZE>)
→Maximum size is 2000 byte/2000 char.
→ Default size is one byte.
→ it uses defined size irrespective of the characters we provided.

<col_name> VARCHAR2(<SIZE>)
→ Maximum size is 4000 byte/4000 char.
→ size is mandatory.

LONG DATATYPE
<col_name> long
→ It is used to represent characters or numbers.
→ Max size is 2gb
→ Only one LONG column is allowed per table.
→ LONG columns are not allowed in the WHERE clause.

DATE DATATYPES
<col_name> date
→ It is used to represent date and time information but time is optional.
→ the default date format in oracle is dd-mon-yy/dd-mon-yyyy
→ range of date datatypes is from "01-JAN-4712 BC " TO "31-DEC-9999 AD ".

b)Composite data type → defined by user in pl/sql.


Also known as attributes

%TYPE → table based RECORD

%ROWTYPE → cursor based RECORD

RECORD → user defined record


Type <tn> is record (<V.N> <d.t>);

Interview point

What is Literal? Give an example of where it can be used?

A Literal is a string that can contain a character, a number, or a date that is included in the SELECT list and that is not a column name or a
column alias. Date and character literals must be enclosed within single quotation marks (‘ ‘), number literals need not.

For exp: Select last_name||’ is a’|| job_id As “emp details” from the employee; (Here “is a” is a literal).

What are BLOB and CLOB :


Blob and Clob together are known as LOB(Large Object Type). The following are the major differences between Blob and Clob data
types.

Blob Clob

The full form of Blob is a Binary Large Object. The full form of Clob is Character Large Object.
This is used to store large binary data. This is used to store large textual data.

This stores values in the form of binary This stores values in the form of character streams.
streams.

Using this you can store files like videos, Using this you can store files like text files, PDF
images, gifs, and audio files. documents, word documents etc.

F8 – to get the history of quarries which are executed.

ddl (data definition language)

create:
➢ it is used to create new database objects.
➢ While creating a table we provide the basic information for each column together with their data type and size.

syntax:
*******
create table tablename
(
column_name datatype(size),
column_name datatype(size),
column_name datatype(size),
............................,
.........................,
column name datatype(size)
);
➢ Once the table is created, we will receive a message "table created".
➢ if the same table name already exists in the database, then we will not be allowed to create a table again.
create table EMP(
empno number,
ename varchar2(10),
job varchar2(10),
mgr varchar2(10),
hiredate date,
sal number,
comm number,
deptno number
);

create table DEPT(

deptno number,
dname varchar2(10),
loc varchar2(10)
);

create table <table name> as select * from EMPwhere 1=1; (using select statement)
1=1 – true – to copy data along with table structure
1=0 – false – to copy table structure alone

Table Naming Conventions:


We need to follow the rules below.

→ Table names should not start with numbers.


→ The name must begin with a letter A-Z or a-z,(0-9,or _,$,#)
→ Can contain numbers and underscores.
→ Maximum length it should be 30 characters
→ Can be in upper or lower case
→ Can not use the same name.
→ size of the table need not be specified
→ Names can not be oracle server reserved keywords.
→ Table names are not case sensitive in oracle.
→ The structure of the table can be modified.

What are temporary tables in Oracle?


Global Temporary Tables (GTTs) are the Oracle tables, having data type as private; such that data inserted by a session can be accessed by that
session only.
If we give ON COMMIT DELETE ROWS then the table is transaction-specific but if we give ON COMMIT PRESERVE ROWS then the
table is session-specific.

Syntax :
CREATE GLOBAL TEMPORARY TABLE table_name(
column_1 data type,
Column_2 data type
)
ON COMMIT PRESERVE ROWS / ON COMMIT DELETE ROWS ;

describe/desc:

it is used to retrieve the structure of the table.


desc emp;

alter:
used to change the structure of the table.
once the table is successfully altered then we will receive a message saying "table altered"

add:

it is used to add the new columns to the existing table

syntax:
*******
alter table <table_name> add <column_name> datatype <size>; → single column
alter table <tablename> add (<column_name> data type <size>, <column_name> data type <size>); → multiple columns

modify:

it is used to change or modify the structure of existing column data types and size.
it is used to modify the column in a table.

syntax:

alter table <table_name> modify <column_name> <datatype> <size>; → single column

alter table <table_name> modify (<column_name> <data type> <size>, <column_name> <data type> <size>); → multiple
columns

rename:

it is used to rename a column name in a table.


we can rename only one column at a time.
syntax:
alter table <table_name> rename column <old column name> to <new column name>
alter table <table_name> rename to <newtablename>

drop:

It is used to drop a column in a table.

syntax:
alter table <tablename> drop column <columnname>; → single column

rename:
it is used to rename the table name.

syntax:
rename <old table name> to <new table_name>
drop:
it is used to drop the table permanently in the database.

syntax:
drop table <tablename>

truncate:(delete+commit)
it is used to remove all the records from the table.
data will be removed permanently in the database but not the table itself.
automatically implicit commit will be fired.
it can’t rollback
it works like a delete +commit.

syntax:
truncate table <tablename>

comment:
comment statement to add a comment about a table, view, snapshot, or column into the data dictionary.

syntax:
comment on table <tablename> is 'text'.
comment on column <tablename.columnname> is 'text'.

ex: select *
from user_tab_comments
where table_name='EMP';

select *
from all_col_comments where table_name = 'EMP';

dml (data manipulation language)


it is used to handle the data in a database object.
explicit commit will fire.
it is used to perform manipulations on databases.
dml commands deal with the data only.
we can undo (rollback) the changes.
dml commands are slower compared with ddl commands.

➢ insert
➢ update
➢ delete
➢ merge

insert:
it is used to add new rows of data to an existing database table.
it is used to insert the data into a table.
To insert data,tables should be first available in the database and below are the ways to insert data into a table.

syntax:

insert into <tablename> values (<value1,value2,value3,....>) method 1


insert into <tablename> (<column1>,<column2>,<column3>) values (<value1>,<value2>,<valuen>); method 2
insert into <new table name> select * from <existing table name or old tablename> method 3
insert into <new table name>(<column1>,<column2>,<column3>) select (<column1>,<column2>,<column3>) from <existing
table name or old tablename>

Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left
blank during record creation!

update:
it is used to change the existing information in the database.
it is used to modify the existing table data.

syntax:

update <tablename>
set <column1>=<value1>
[<column2>=<value2>,....,<column>=<value> where <condition>]

Specifying condition is not mandatory and if condition is not defined then the system will consider all records in the table for
update.

delete:
it is used to remove the rows from the table.
it is used to delete the data in a table without touching the table structure.

syntax:
delete from <tablename>[where <condition>];

MERGE:
It is used to transfer the data from source table to destination table.
The MERGE statement allows you to specify a condition to determine whether to update data from or insert data into the target
table.
It is used to compare the 2 table contents and make them equal.
It supports only update and insert.

Rules:
-->New records inserted
-->Old records updated

SYNTAX:
MERGE INTO <DESTINATION TABLE NAME> <ALIAS NAME>
USING <SOURCE TABLE NAME> <ALIAS NAME>
ON (<JOINING CONDITION>)
WHEN MATCHED THEN
UPDATE SET <DEST.TABLE ALIAS NAME>.<COLUMN NAME1>=<SOUR.TABLE ALIAS NAME>.<COLUMN
NAME1>,...........................................................................................
[Delete where <condition>]
WHEN NOT MATCHED THEN
INSERT(<DESTINATION TABLE COLUMNS>)VALUES(<SOURCE TABLE COLUMNS>);

differences between truncate and delete:


=====================================================================
truncate (delete+commit) delete

ddl command dml command

rollback is not applicable rollback is applicable

implcit commit will be fire explicit commit will be fire

where clause is not applicable where clause is applicable

all rows of the table can be truncated all rows of the table can be deleted.

single row of the table can not be truncated single row of the table can be deleted

multiple rows of the table can not be truncated multiple rows of the table can be deleted

performance will be faster performance will be slower

ddl vs dml
ddl all the ddl statements are committed automatically at the end
of statement execution.
ddl statements are used for defining and managing data
structures like table,view,synonym,sequence etc.

ddl statements work on the whole object no where condition dml


can be used along with ddl statements.
dml statements are used to manage the data stored inside
the database.
dml statements work on the selected data of table "where" all changes done by dml's need explicit commit or rollback to
condition can be used to filter and work on selected dataset. make changes permanent or revert back.

tcl(transaction control language)

TCL commands will be dealing with transactions only.within the transaction all the TCL commands are valid.
→ Transaction is nothing but a set of DML operations with COMMIT or ROLLBACK that means a group of DML operations with a
COMMIT or a group of DML operations with a ROLLBACK.
→ Within the database transaction will start with DML write operations.So DML read operations can be a part of the transaction but
DML read operation is not the starting point of the transaction.
SELECT → READ

commit :
to make the changes permanently stored data into the database.
Implicit commit - It is applied by the system (DDL commands)
Explicit commit - It is applied by the user

rollback :
to cancel all the transactions done till previous committed data.
Rollback is applicable for DML statements only.
ROLLBACK is just opposite to COMMIT.
ROLLBACK will undo the DML operation that we perform on a database which is not committed yet.

SYNTAX:
Rollback;
Rollback to <SAVEPOINT NAME>;

SAVEPOINT:
It is used to divide the large transaction into small transactions.
Savepoints store data within the buffer only(not in the database).
→ It is used to create a mark in the current transaction.
→ Using savepoint the transaction can be discarded up to the marked by using the rollback statement.
→ If a second savepoint is created with the same name as an earlier savepoint, the earlier savepoint is deleted.

SYNTAX:
SAVEPOINT <SAVEPOINT NAME>;

FLASHBACK TABLE:
this command is used to restore drop objects from recycle bin
SYNTAX:
FLASHBACK TABLE <TABLENAME> TO BEFORE DROP;

PURGE:
THIS COMMAND IS USED TO DROP OBJECTS FROM RECYCLE BIN PERMANENTLY.
SYNTAX:
PURGE TABLE <TABLENAME>

dcl (data control language)

GRANT:
Used to give access for a table from one schema to different schema
Syntax:
GRANT ALL ON <SCHEMA NAME>.<TABLE NAME> TO <SCHEMA NAME>

We can use DML, DQL commands in place of ALL


dql/drl (data querying/retrieval language )

clauses:
➢ select clause
➢ from clause
➢ where clause
➢ group by clause
➢ having clause
➢ order by clause
➢ distinct clause

syntax:
select <columnlist>
from <table name>
[where <condition>
groupby <condition>
having <condition>
order by <clause>
]
* represents all columns.
<Table Alias Name>.* can also be used

select clause:
it is used to retrieve the data from tables.

from clause:
it is used to retrieve the data from which table.

alias names:
it is used to provide temporary headings for columns or expressions in select statements.
they are valid in that select statement only.
they are only for display purposes.

ex :select empno eno,ename as emp_name,job "desg" from emp;

where clause:
it is used to provide the condition
it is used to filter the data from grouped records
it won't allow group functions and alias names in where condition
eliminates non matching records.
where clause has the highest priority
group functions are not allowed(max,min,count,avg,sum).

ex: select * from EMPwhere emp.deptno=10;

group by clause:
it is used to group the similar data based on the columns.
it is used to group rows based on one or more columns/expressions to calculate aggregates like min,max,sum,avg,count for each
group.
by using this clause select statement to combine a group of rows based on the values as a particular column or expression.
whenever we implement a "group by " clause in a select statement, first grouping similar data based on columns and later an
aggregate function will execute on each group of data to produce an accurate result.
When we use "group by" we must use "aggregate functions" which are sum(),avg(),min(),max(),count().
ex: write a query to calculate department number wise total salary.?

select deptno,sum(sal) from EMPgroup by deptno ;

having clause:
having clause added to sql because the where clause could not be used with aggregate functions.
It is used to specify the conditions on aggregate functons.it is always used along with group by clause.
it is used to filter the data from grouped data based on condition.
filtering rows after grouping data in table.it can be used along with "group by" clause.
it is similar to the where condition but is used with group functions
group functions cannot be used in where clauses.

ex: DEPTwise total salaries and sum of sal>9000?

select deptno,sum(sal)
from emp
group by deptno
having sum(sal)>9000

order by clause:
it is used to make the data in order.
it is used to arrange the select statement output in ascending order or descending order.
By default order by clause arrange values in ascending order but if we want to arrange values in descending order then we use the
"desc" keyword.
must be the last clause in the select statement.
it supports all types of data.

ex: write a query to display employee salaries in ascending and descending order?

select * from EMPorder by sal;


select * from EMPorder by sal desc;

Note: order by clause not only on column names even though we can apply on position of column or by using alias
name in select query.
select * from EMP order by 6 desc;

distinct clause:
it is used to restrict the duplicate records.
ex: select distinct sal from emp;

operators:

→ arithmetic operators
→ logical operators
→ relational operators
→ special operators
→ set operators

what is dual:
→ predefined table in oracle.
→ it has a single row and single column.
→ it is called a dummy table in oracle.
→ testing functions(predefined & user defined) functionalities.

syntax:
select * from dual;
arithmetic operators:
It is used to do the mathematical functions(arithmetical calculations) like addition, subtraction, multiplication and division. (+, -,
*, /)

ex: select sal,sal*12 multiplication,sal+10 addition,sal-100 sub


from emp;

Note: addition or subtraction on null will result in null (EX: 12+null = null - 5 = null) to overcome this issue we will use NVL functions

relational operators:
(=,(!=or <>),<,<=,>,>=)
relation can be build with only one values (it won't support multiple values)

ex: select * from EMPwhere deptno<=20;

logical operators:

and operator:
if both the conditions are true then it returns the result as true.
if both the conditions or if any one condition is false then it returns the result as false.

ex: display the details of employees whose salary is greater than 2000 and also whose salary is less than 5000.
select * from EMPwhere sal>2000 and sal<5000;

or operator:
at least one condition is true then it returns the result as true.
if both the conditions are true then it returns the result as true
if both the conditions are false then it returns the result as false.

ex: select * from EMPwhere job='manager' or deptno=20;

not operator:
specified conditions must be false.
similar to not equal
ex: select * from EMPwhere not deptno=20;
same as
select * from EMPwhere deptno!=20;
special operators:
(in,like,between,is null):

special operators are used to frame the conditions while retrieving or manipulating data.
to improve the performance.
in/not in:
it is used to pick the values within the given list.
it returns true if value is available in a given list of values.
it supports all types of data.

ex: select * from EMPwhere ename in ('king','blake','clark');

not in operator is quite opposite to in operator.


select * from EMPwhere ename not in (7839,7782);

between/not between
it is used to pick the values within the specified range.
returns true if the value specified is within the specified range.
it supports numbers and date values.

ex: all employee records are fetched whose salary is between 1000 and 2000.
select * from EMPwhere sal between 1000 and 2000;

whenever the lower bound value is larger than the upper bound then it shows "no rows selected".

select * from EMPwhere hiredate between '17-dec-81' and '20-jun-83';

always date should be given in single codes ‘ ’.

select *from EMP


where hiredate not between '01-jan-1980' and '31-dec-1982';

like/not like:
it is used to search for a pattern in given input supports with character data only.
It uses two special characters.
a) % represents zero or more characters.
b)_(underscore) --> it represents one character only.

syntax:
select * from <tablename> where <columnname> like '<value>';
select * from <tablename> where <columnname> 2not like '<value>';

ex:
list the objects whose name start with 'c'
select object_name
from all_objects
where object_name like 'c%'
/
list the objects whose name doesn’t end with 's'
select object_name
from all_objects
where object_name not like '%s';
/
list the objects whose name contain 'a'
select object_name
from all_objects
where object_name like '%a%';
/
list the objects whose name starts with 'a' and have at least 2 characters in it
select *
from emp
where ename like 'a_%';

is null/is not null:


it is used to compare null values.
it is used to search for null values in the given input.
supports all types of data.

syntax:
select * from <tablename> where <columnname> is null;
select * from <tablename> where <columnname> is not null;

ex: list the employees who are not having commission.


select * from EMPwhere comm is null;
select * from EMP where mgr is not null;
set operators:
it is used to join the outputs of select statements based on the operator specified.
by using set operators we join more than one query such queries are called compound queries.
set operators are used to combine the result of two or more queries into a single result.
select statements must have an equal number of columns and similar data type columns but must not be the same size.
maximum 32 queries can be joined with set operators.

rules:
*******
→ no of columns should be the same within both select statements.
→ order of the columns should be same
→ data types of the columns must be matched.

1)union all
2)union
3)intersect
4)minus

union all:
it displays all the values along with duplicate values also.
two queries must have the equal number of columns.

syntax:
select * from <table name 1>
union all
select * from<table name 2>;

union:
it is used to combine the results of two or more select statements.
however it will eliminate duplicate rows from its result set.
in case of union, number of columns and datatype must be same in both the tables

syntax:
select * from <table name 1>
union
select * from<table name 2>;

intersect:
intersect operation is used to combine two select statements, but it only returns the records which are common from both select
statements.
In case of intersect the number of columns and datatype must be the same.

syntax:
select * from <table name 1>
intersect
select * from<table name 2>;

minus:
The minus operation eliminates common results of two select statements and returns only those in the final result which
belongs to the first set of the result.

syntax:
select * from <table name 1>
minus
select * from<table name 2>;

Functions:
To perform a task and must return value.
oracle supports two types of functions.they are

Pre-define/built in functions
(use in sql and pl/sql)
single row functions (scalar functions)
These functions return a single row or group of values.

a)numeric or number functions


numeric functions are used to perform operations on numbers.
They accept numeric values as input and return numeric values as output.

power(m,n):
it gives the power of a given expression.
m→ value
n→ exponent
ex : select power(2,4), power(4,8), power(0,0), power(null,null) from dual;

sqrt(m):
it gives the square root of a given number.
input value must be positive.
ex: select sqrt(2), sqrt(8), sqrt(0), sqrt(null) from dual;

mod(m,n):
gives remainder after m/n operation.
M→ value
n→ divisor
ex: select mod(1,5), mod(5,2), mod(0,0), mod(null,null) from dual;

ceil(m):
it displays the next highest value.
it returns a value which is greater than or equal to the given value.
ex: select ceil(2), ceil(2.01), ceil(23.65), ceil(245.21), ceil(4567.78), ceil(-23.1), ceil(-456.90), ceil(-3451.091) from dual;

floor(m):
it displays the next lowest value.
The purpose of the floor function is it returns the integer values which are equal to the specified number or less than the specified
number.
ex : select floor(2), floor(2.90), floor(13.12), floor(45.7), floor(980.213), floor(5678.213), floor(-123), floor(-123.21), floor(-1456.765)
from dual;

round(m,[n]):
it rounds the value up to a given number of positions.
it checks the condition and rounds value to some specified decimal.
n → decimal points

ex: select round(1234.98), round(778.34), round(45.65), round(678.21,1), round(765.989,2), round(6789.7654,3) from dual;

trunc(m,[n]):
→ it works similar to that of round,but it won't check the condition.
→ return a number with some digits truncated.

ex: select trunc(123.4), trunc(123.45,0) ,trunc(123.453,1), trunc(123.453,2), trunc(123.45,-1), trunc(123.45,-2) from dual;

abs(m)
it gives the absolute value of n.
if n is -ve it converts to positive.
ex: select abs(10),abs(-5),abs(0),abs(null) from dual;

sign(n):
→ if n is +ve gives 1
→ if n is -ve gives -1
→ if n is 0 gives 0

ascii(m):
select ascii('a') from dual;
select ascii('a') from dual;
select ascii('0') from dual;

b)string functions

upper(string)
it is used to convert the string into upper characters.
ex: select upper('oracle') from dual;

lower(s):
it is used to convert the string into lower characters.
ex: select lower(oracle) from dual;

initcap(s):
it is used to convert the first character into the upper character in a given string.
ex: select initcap('oracle') from dual;

length(s):
it is used to display the number of characters in a given string.
ex: select length('asdefrgt:%"12343098**') from dual;

reverse(s):
it is used to reverse the given string.
ex: select reverse('oracle') from dual;

concat(s,s):
it is used to merge the two strings
ex: select concat('oracle','pvt limited') from dual;
we have to use '||' symbol while merging more than two strings.
ex: select 'oracle'||'india'||'ltd' from dual;
trim(s from s):
trim is used to remove the characters from both sides of a given string.
to remove unwanted spaces or unwanted characters from both sides of the given string.
ex: select trim('x' from 'xxxxxxoraclexxxx') from dual;

l/r trim(s,[s]):
ltrim is used to remove the character from the left end of the given string, if the character is found.
it is used to remove the character from the right end of the given string,if the character is found.
to remove unwanted spaces or unwanted characters from the left or right side of the given string.

ex:
select ltrim(' oracle') from dual;
select ltrim('oracle','o') from dual;
select rtrim('oracle','cl') from dual;

lpad() / rpad():

it is used to add the character from the left end / right end.
The lpad()/rpad() function pads the left/right side of a string with a specific set of characters.
to fill a string with a specific character on the left/right side of the given string.
syntax:
lpad(string,length,[string])
rpad(string,length,[string])

ex: select lpad('oracle',10,’*’) from dual;


select rpad('oracle',8,'*') from dual;
select rpad(lpad('oracle','15','*'),'25','*') from dual; -->third argument is optional.
requirement
k**g
b***e
m****n
ex: select ename, rpad(substr(ename,1,1), round(length(ename)*2/2)-1,'*') || substr(ename,-1,1) result from emp;

translate(s,s,s):
it is used to translate the character wise in a given string,if the character is found.
to translate a single character with another single character.
it is not possible to translate the entire string.
ex : select translate('prashanth', 'anth', 'pqrs') from dual;

string1 -->source string or input string


string2 -->which we want to replace
string3 -->what we want to replace

replace(s,s,s):
it is used to replace an entire string.
to replace one string with another string.
it is not possible to replace more than one string.
ex : select replace('prashanth', 'anth', 'pqrs') from dual;

substr(s,m,n):
it is used to display the set of characters in a given string.
it is used to extract a particular portion of a string.

s→ string
m-- > position
n→ no.of.characters

ex: select substr('oracle',1,3) from dual;


instr(s,c,m,[n]):
it is used to find the position of a given character.
returns occurrence position of a character in the given string

s→ string
c→ character → which is the character we want find out the position
m→ starting search position (+1 / -1 )
n→ occurrence → we want find out the occurrence(repeated characters) if no such character exists it will return 0.

ex:
select instr('hello welcome','e',1,4) from dual;--> -->-->-->0
select instr('hello welcome','e',-1,3) from dual;--> -->-->-->2

decode():
In Oracle, the DECODE function allows us to add procedural if-then-else logic to the query. DECODE compares the expression to
each search value one by one. If expression is equal to a search, then the corresponding result is returned by the Oracle Database

it is used to replace more than one string.


it works like an if condition but it does not allow the relational operators.

syntax:
decode( col_name, compare_value, return_value, [,compare, return_value] ... [,default_return_value] )

ex:select ename,job,decode(JOB,'PRESIDENT','PRS','MANAGER','MGR','CLERK','CLK','SALESMAN','SALMAN',JOB)res from emp;

Interview point
DECODE VS CASE

DECODE: Its a function, we can't call all operators


CASE: It's a statement, we can call all functions and operators,
Good performance as compared with DECODE
*****case *****
it is used to replace more than one string by using a relational operator.

syntax:
case
when condition1 then result1
when condition2 then result2
when condition then result
else result
end;
ex:
select job,deptno,
case when deptno=10 and job='manager' then 'mgr'
when deptno=20 and job='analyst' then 'als'
when deptno=30 and job='salesman' then 'sman'
else job
end
from emp;

ex:
upper(ename)upper,
lower(job)lower,
initcap(ename) initcap,
length(ename) length,
ename||' its working as a'||job as concat,
reverse(ename) reverse,
ltrim(ename ,'S') ltrim,
rtrim(ename, 'S') rtrim,
trim('S' from ename) trim,
lpad(ename,10,'*')lpad,
rpad(ename,10,'*') rpad,
translate(ename,'K','I') translate,
substr(ename,1,1)||substr(ename,-1,1)substr,
decode(deptno,10,'ten',20,'twenty',deptno) decode_result,
case
when deptno=10 and job='MANAGER' then 'mgr'
when deptno=20 and job='ANALYST' then 'als'
when deptno=30 and job='SALESMAN' then 'sman'
else job
end case_result
from emp;

c)date functions

sysdate:
it is used to display the server system date.
ex: select sysdate+10 from dual;

current date:
it is used to display the client system date.
ex: select current_date from dual;

add_months (date,<no.of months>)


It is used to add or subtract the number of months for a given date.
ex: select add_months(sysdate,-2) from dual;

months_between(date1, date2):
It is used to display the number of months between two dates.
ex: select months_between('05-jan-81','05-jan-80') from dual;

next_day(date,’day’):
it is used to display the upcoming date on which required day falls.
ex: select next_day(sysdate,'sun') from dual;

last_day(date):
It is used to display the last day of the month.
ex: select last_day(sysdate) from dual;

trunc(date,’ ’):
it is used to cutdown the date based on year/mon/day/hh/mi depending on requirement
ex: select to_char(sysdate,'dd-mon-yyyy hh:mi:ss'), to_char(trunc(sysdate,'mi'), 'dd-mon-yyyy hh:mi:ss') from dual;

extract:
it is used to extract a portion of a date value.

syntax:
extract ((year |month |day |hour |minute|second | timezone_hour | timezone_mnute | timezone_region | timezone_abbrevation)
from date)

ex: select extract(minute from timestamp '2021-07-20 17:48:20') from dual;


select to_char(timestamp '2021-07-20 17:48:20', 'MM') from dual;

=============================================================
date formats:
d→ name of day in a week
dd → name of day in a month
ddd→ name of day in a year
dy→ first 3 characters of the day.
day→ complete characters of the day.
mm→ number of the months in the year
mon→ first three characters of the month.
month→ complete characters of the month.
y→ last digit of the year
yy→ last two digits of the year.
yyy→ last three digits of the year.
yyyy→ four digits of the year.
Year → to print year in letters.
hh→ an hour of the day.
hh24→ 24 hours format.
mi→ minutes of the year
ss→ seconds of the year
fs→ fraction of seconds
w→ week of the month
ww→ week of the year
q→ quarter of the year

year formats:
yyyy - 2022
yy - 22
year - twenty twenty two
cc - century 22
ad / bc - ad year / bc year

month format:
mm - month number
mon - first three char from month spelling
month- full name of month

day formats:
ddd - day of the year.
dd - day of the month.
d - day of the week
sun - 1
mon - 2
tue - 3
wen - 4
thu - 5
fri - 6
sat - 7

day - full name of the day


dy - first three chars of day spelling

quarter format:
q - one digit quarter of the year
1 - jan - mar
2 - apr - jun
3 - jul - sep
4 - oct - dec

week format:
ww - week of the year
w - week of month

time format:
hh - hour part
hh24 - 24 hrs format
mi - minute part
ss - seconds part
am / pm - am time (or) pm time
ex:
select empno,ename,job,sal,hiredate,
months_between(sysdate,hiredate),
months_between(sysdate,hiredate)/12,
round(months_between(sysdate,hiredate)/12),
ceil(months_between(sysdate,hiredate)/12) ceil,
floor(months_between(sysdate,hiredate)/12) floor
months_between(hiredate,sysdate),
months_between(hiredate,sysdate)/12,
round(months_between(hiredate,sysdate)/12)
from emp;

d)conversion functions

to_char(date,[<format>]):
it is used to convert system format into user format.
it is used to convert the number into character and also it converts the date into character.

ex:
select to_char(sysdate,'dd-mon-yyyy hh24:mi:ss') from dual;
select to_char(sysdate,'ddd dd d day dy DAY DY DD') from dual;
select to_char(sysdate,'yyyy yy year cc ad') from dual;
select to_char(sysdate,'mm mon month MM MON MONTH') from dual;
select to_char(sysdate,'q') from dual;
select to_char(sysdate,'ww w') from dual;
select to_char(sysdate,'hh:mi:ss am') from dual;
select to_char(12346,'99,99,999.99')from dual;
select 1234,to_char(1234,'9999d99')from dual; → decimal indicator(it return specified position of the decimal character)
select to_char(5634,'9.9eeee') from dual; → (it returns a numeric value using scientific notation)
select to_char(1234567,'99g99g9999') from dual; → (it returns the specified of the group separator)
select to_char(1234,'l9999') from dual; → it returns the specified position of the local currency symbol, after l there should be max
number
select -20000,to_char(-20000,'l99g999d99pr')from dual;
select to_char(2000,'9999s') from dual;

to_date(string,[format]):
it is used to convert user format into system format.
it is used to convert the string into date format.
ex: select to_date('january 22,2021', 'month dd,yyyy') from dual;

to_number:
it is used to translate a value of char or varchar datatype to number format.
ex: select to_number('$4328','$9999') from dual

multiple row functions


These are also known as aggregate functions or group functions.
These functions return either a group of values or a single value.

sum
it returns the sum value of the column.
it is an aggregate function
it ignores null values.
it will give the sum of the values to the specified function.
ex :select sum(comm),sum(distinct comm) from emp;

rollup:
rollup is calculating subtotals and grand totals
rollup extension produces group subtotals from right to left and a grand total
ex:select deptno,job,sum(sal) from emp
group by rollup(deptno, job);

grouping id functionality:
************************
both column values are not null → grouping id it will print 0
one column value is not null and one column value is null → 1
one column value is null and second column value is not null → 2
both columns values is null → 3

ex:
select deptno,job,sum(sal) sumsal,
grouping_id(deptno,job)subtotal
from emp
group by rollup/cube(deptno,job)
order by 1,2;

cube:
cube extension will generate subtotals for all combinations of the dimensions specified.

ex: select deptno,job,sum(sal) from emp


group by cube (deptno, job);

avg:
it will give the average value.
it returns the average value of the column.
it ignores null values.
ex :select avg(comm),avg(distinct comm) from emp;

min():
it will give the minimum of the values of the specified column.
it ignores null values.
ex: select min(sal),min(distinct sql) from emp;

max:
it will give the maximum of the values of the specified column.
it ignores null values.
ex: select max(sal),max(distinct sql) from emp;

count():
it will give the number of rows in the specified column.
if '*' is used to return all rows,including duplicates and nulls.
three types,
i) count(*) →counting all rows (duplicates & nulls) in a table.
ii) count(<column name>) → counting all values including duplicate values but not null values from a column.
iii) count(distinct <column name>) → → counting unique values from a column.here "distinct" keyword is eliminating
duplicate values.

ex: select count(distinct mgr) from emp;

ANALYTICAL FUNCTIONS:
Analytical functions to calculate an aggregate value based on a group of rows and return multiple/all rows of each group.
-->They differ from aggregate functions in that they return multiple rows for each group.
ANALYTICAL FUNCTION NAME() OVER ([PARTITION BY <COLUMN NAME>] ORDER BY <COLUMN NAME><>ASC/DESC]
EX: SELECT EMP.*,SUM(SAL) OVER (PARTITION BY DEPTNO ORDER BY SAL DESC) FROM EMP;

ROW_NUMBER
To assign different rank numbers to the same value.
ROW_NUMBER() OVER ([PARTITION BY <COLUMN NAME>] ORDER BY <COLUMN NAME><>ASC/DESC]

RANK
To assign the same rank number to the same value but skipping the next sequence rank number in the order.

DENSE_RANK
To assign the same rank number to the same value but without skipping the next sequence rank number in the order.

EX:
select empno,
ename,
job,
sal,
deptno,
row_number() OVER (partition by deptno order by sal desc)row_number,
rank() OVER (partition by deptno ORDER BY sal desc) rank,
dense_rank() OVER (partition by deptno ORDER BY sal desc) dense_rank
from emp;

LAG
It is used to access previous row data along with current data.
LAG(expression [,offset[,default_value]]) OVER(ORDER BY columns)

Expression – column
Offset – position of previous data
Default – will return default value if in case offset is out of range.

EX:
SELECT EMPNO,ENAME,SAL,DEPTNO,
LAG(SAL,1,0) OVER (PARTITION BY DEPTNO ORDER BY SAL DESC)PREV_ROW
FROM EMP;

LEAD
It is used to access the subsequent row data along with current row data.
LEAD(expression [,offset[,default_value]]) OVER(ORDER BY columns)
EX:
SELECT EMPNO,ENAME,SAL,DEPTNO,
LEAD(SAL,1,0) OVER (PARTITION BY DEPTNO ORDER BY SAL DESC)PREV_ROW
FROM EMP;

NULLS FIRST AND NULLS LAST:


EX:
SELECT EMPNO,ENAME,SAL,COMM,RANK() OVER(ORDER BY COMM DESC NULLS FIRST)RANK_NULLS_FIRST,
DENSE_RANK() OVER(ORDER BY COMM NULLS LAST) DENSE_RANK_NULLS_LAST
FROM EMP;

general functions:

user:
it will return the name of the present session user(schema).
syntax:
select user from dual;
Or
Show user;
uid:
it returns the user id value for the current session.
syntax:
select uid from dual;

userenv('parameters'):
The parameter list of userenv is shown in the below table.

syntax:
select userenv('lang') from dual; → returns iso abbreviation language name.
select userenv('language') from dual; → returns the language and territory of the current session.
select userenv('sessionid') from dual; → returns the auditing session number.
select userenv('terminal') from dual; → returns the operating system identifier of the current session

greatest:
it is used to find the greatest value in the available or provided expression values.

ex:
select greatest(10,4,9,20) from dual;
select greatest('a','e','i','o','u') from dual;
select greatest (to_date('11-jan-1981','dd-mon-yyyy'), to_date('16-dec-1982','dd-mon-yyyy'), to_date('12-mar-1980','dd-mon-
yyyy')) "greatest" from dual;

least:
it is used to find the least value in the available or provided expression values.
ex:
select least(12,34,77,8,66) "least" from dual;
select least (to_date('11-jan-1981','dd-mon-yyyy'), to_date('16-dec-1982','dd-mon-yyyy'), to_date('12-mar-1980','dd-mon-yyyy'))
"least" from dual;

nvl
it assigns the value to the column if it is null.
The nvl() function accepts two arguments. if e1 evaluates to null, then nvl(e1,e2) function returns e2.
if e1 evaluates to non-null, the nvl() function returns e1.

ex :select empno.ename, job,sal,comm, nvl(sal,0), nvl(comm,0), sal+comm, sal+nvl(comm,0) from emp;

nvl2:
if exp1 is null it returns exp3,if exp1 is not null it returns exp2

ex: select ename,job,nvl2(comm,sal+comm,sal) net from emp;

nullif:
if exp1 and exp2 results are same it returns null value otherwise it returns exp1 result.
ex: select nullif(100,50*2),nullif(200,15*9),nullif(600,300+300) from dual;

coalesce:
it picks the first not null values.
ex: select coalesce(100+null,128-null+1000,12*null,268,2120,3281) from dual;

user defined functions


(use in pl/sql)
constraints:
1.it is used to control the data in a table.
2 constraints are used to restrict unwanted(invalid) data into tables.
3.it is also used to maintain the security of the table.
4.it is used to implement the business rules.
or
The process of enforcing the business rules on database tables is called "data integrity".

select * from all_constraints;

select search_condition from user_constraints where table_name=<’tn’>;

select constraint_name,column_name from user_cons_columns;

there are two types of data integrity:

predefined integrity [constraints]


Whenever we are applying a constraint on a particular column then the db server(system) internally generates an unique id
number (or) an unique constraint key name automatically for identifying a constraint.

ex: unique constraint (scott.sys_c005475) violated


syntax:
<column name> <dt>[size] <constraint type>

user defined integrity [ database triggers]


In place of a pre-defined constraint name we can also create a user defined constraint key name (or) constraint id for identifying a
constraint.

ex: unique constraint (scott.<user defined constraint name>) violated


syntax:
<column name> <dt>[size] constraint <user defined constraint name> <constraint type>

oracle supports 3 types of integrity constraints:


domain integrity constraints:
domain is nothing but columns. it ensures that to check values with user defined conditions before accepting values into a column.

➢ check constraints
it is used to check the condition
allows a valid range of values only.
it is used to validate the data based on the condition.
to check values with user defined conditions before accepting values into a column.
it can be defined at column level or table level.
ex :
create table xx_check(
sno number,
sname varchar2(20),
fee number check(fee>=3000),
marks number constraint chs1 check(marks between 0 and 100),
jdate date
);

ex:
create table xx_check_1(
sname varchar2(20),
sno number(3),
marks number(3),
constraint student_c1_marks_1 check(marks between 0 and 100)
);
how to add constraints to an existing table:
============================================
syntax:
alter table <tn> add constraint <constraint key name> <constraint type> (<column name>);
➢ not null constraints
it is used to allow only not null values.
it does not allow null values.
it can be defined at column level only.
not null constraint does not support "table level".

ex:
create table xx_stu(
sno number not null,
sname varchar2(30)
);

how to add constraints to an existing table:


============================================
syntax:
alter table <tn> modify <column name> constraint <constraint key name> not null;

➢ default constraints
it is used to insert default values when no values are given.
it will accept null values and will display null values.
ex:
create table xx_emp_default
(
empno number,
ename varchar2(20),
sal number default 1000
);

entity integrity constraints:


it ensures that each row is uniquely identified in a table.
➢ primary key constraints
it is used to define the key column of a table.
it can be used only once in table definition
it will not allow null values and duplicate values into key column
it is supported with an index automatically.
numeric columns are preferred as primary keys rather than character columns.

ex:
create table xx_emp_primay_key(
empno number primary key,
ename varchar2(20) ,
sal number
);

ex:
create table xx_cpk_con(
sno number,
sname varchar2(20),
marks number,
primary key(sno,sname)
);
note : when we apply a primary key constraint on a group of columns then we call it a "composite primary key" constraint.
In this mechanism individual columns are accepting duplicate values but duplicate combinations of column data are not allowed.

ALTER TABLE table_name DROP PRIMARY KEY; → to drop a primary key

➢ unique key constraints


it allows only unique values.
it does not allow duplicate records
it accepts more than one null value.
a table allows more than one unique key.
it restricts duplicate values but accepts nulls into a column.
ex:
create table xx_emp_unique(
empno number unique,
ename varchar2(20) not null, unique
sal number check(sal>=5000),
nation varchar2(20) default 'india'
);

ex:
create table xx_unique_con (
sno number,
sname varchar2(10),
marks number,
unique(sno,sname)
);

note:
→ when we apply a unique constraint on a group of columns then we call it a "composite unique" constraint.
→ in this mechanism individual columns are accepting duplicate values but duplicate combinations of column data is not allowed.

how to add constraints to an existing table:


============================================
syntax:
alter table <tn> add constraint <constraint key name> <constraint type> (<column name>);

referential integrity constraints:


it ensures that we create relationships between tables.

➢ foreign key constraints


it is used to maintain a reference from one table to another table.
it is used to create parent child relationships between 2 or many tables.
it always refers to the primary key column / unique key of the parent table.
one table foreign key must belong to another table primary key and primary key & foreign key column must be a common
column.
The primary key table is called "parent table" and foreign key table is called "child table".(i.e parent & child relationship).
Generally the primary key is not allowed duplicate and null values whereas foreign key accepts duplicates and null values.
After creating a relationship, parent table records cannot be deleted.

syntax:
<common column name of child> <dt>[size] references
<parent table name>(<common column name of parent>)

ex:
parent table:
create table dept_parent (
deptno number primary key,
dname varchar2(20),
loc varchar2(20)
);

chaild table:
create table emp_child(
empno number primary key,
ename varchar2(20),
sal number,
deptno number(2) references dept_parent(deptno)
);

create table emp_child(


empno number primary key,
ename varchar2(20),
sal number,
deptno number(2)
constraint dept_c foreign key(deptno) references dept_parent(deptno)
);

Interview point
What is normalization in primary key and foreign key?

Normalization is the process of organizing data in a database in such a way that data redundancy is minimized and data integrity is maximized.

In Oracle, normalization involves organizing data into tables and defining relationships between those tables using primary keys and foreign keys.
The goal of normalization is to eliminate data redundancy, which reduces storage space and improves data consistency.

how to add constraints to an existing table:


============================================
syntax:
alter table <tn> add constraint <constraint key name> <constraint type> (<column name>);

note :
once we establish relationship between tables there are two rules are come into picture.those are

insertion rule:
we cannot insert values into foreign key(references key) columns those values are not existing under the primary key column of
the parent table.
integrity constraint (scott.sys_c005468) violated - parent key not found.

deletion rule:
when we try to delete a record from parent table and those associated records are available in child table then oracle returns an
error
ora-02292: integrity constraint (scott.sys_c005468) violated - child record found.

note:
If we want to delete a record from the parent table when they have corresponding child records in the child table then we provide
some set of rules to perform delete operations on the parent table.those rules are called "cascade rules".

i) on delete cascade
by using on delete cascade, we can delete the rows from the parent table and the corresponding child table rows deleted
automatically.

ex:
create table xx_emp2(
empno number primary key,
ename varchar2(10),
deptno number references dept_parent(deptno) on delete cascade
);

create table xx_emp2(


empno number primary key,
ename varchar2(10),
deptno number ,
constraint dept_c foreign key(deptno) referencesdept_parent(deptno) on delete cascade
);

ii) on delete set null


whenever we are deleting a record from the parent table then that associated child records are set to null in the child table
automatically.

ex:
create table xx_emp3(
eid number primary key,
ename varchar2(10),
deptno int references xx_dept3(deptno) on delete set null
);

how to add constraints to an existing table:


============================================
syntax:
alter table <tn> add constraint <constraint key name>
foreign key(<common column of child table>) references
<parent table>(<common column of parent table>) on delete cascade /
on delete set null;

how to rename constraint name:


******************************
syntax:
alter table <tn> rename constraint < old constraint name> to <new constraint name>;

how to drop constraint from an existing table:


**********************************************
syntax:
alter table <tn> drop constraint <constraint key name>;

how to disable / enable constraint:


*********************************
--> by default constraints are enabled mode.if we want to disable constraint temp. then we use the "disable" keyword.it means
that a constraint is existing in db but does not work till it is made as "enable".
--> whenever we want to copy a huge amount of data from one table to another table there we use the "disable" keyword.

alter table <tn> disable / enable constraint <constraint key name>;

ora-02293: cannot validate (scott.sys_c005492) - check constraint violated

--> to overcome the above problem then we use "novalidate" keyword at the time of enable constraint.once we use "novalidate"
keywordthen constraint is enable with "novalidate" and oracle server will not check existing data in table but checking new data
while inserting time.

ex:
****
alter table <tn>enable novalidate constraint<constraint key name>;

joins:
it is used to retrieve the data from more than 1 table.

when we are retrieving data from multiple tables based on the "where" clause condition then we call the non-ansi format join.
When we are retrieving data from multiple tables with "on" / "using" clause conditions then we call the ansi format join.

syntax:
select * from table name1,table name2 where <join condition>;

select * from <table name1> <join key> <table name2 > on <join condition>;

types of joins:

cross join or cartesian join


used to retrieve the data from multiple tables without any condition is called cross join/cartesian join.
in cross join,each row of the first table will join with each row of the second table.that means a first table is having "m" no.of
rows and a second table is having "n" no.of rows then the result is mxn no.of rows.

ex: select * from EMP,DEPT;

simple join

equi join
retrieving data from multiple tables based on "equal operator(=)" is called equi join.
equi join always retrieves only matching data/matching rows only.
common column or common field data type must be matched.

syntax:
select * from tablename1, tablename2
where <table name1>.<common col> = <table name2>.<common col>;
(or)
where <tn1 alias name>.<common col> = <tn2 alias name>.<common col>;

non -equi join


retrieving data from multiple tables based on any condition except equal operator condition is called a non-equi join.
In this join we can use the following operators: <,>,<=,>=,and,between,.........etc.

ex: select * from EMPe, DEPTd


where e.deptno != d.deptno and d.deptno=10;

natural join
Natural join is similar to equi join. When we use natural join we should have a common column name. this column datatype must be matched.
Whenever we are using natural join there is no need to write a joining condition explicitly because internally the oracle server is preparing a joining
condition based on an "equal operator(=)" with common column name automatically.
By using natural join we avoid duplicate columns while retrieving data from multiple tables.

syntax:
select * from tablename1 natural join tablename2 ;

inner join
inner join is similar to equi join.retrieving data from multiple tables with "on" clause condition.

ansi syntax:
select * from tablename1 inner join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;

select * from tablename1 inner join tablename2 using (common column);

non ansi syntax:


select * from table1,table2 where table1.commoncol=table2.commoncol

outer join
In the above equi/inner join we are retrieving only matching rows but not unmatching rows from multiple tables.
so to overcome this problem then we use "outer joins".

left outer join


it is used to display the full details of the left table and matched records of the right table.
retrieving all rows(matching and unmatching) from the left side table but retrieving matching rows from the right side table.

ansi format:
select * from tablename1 left outer join / left join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;

select * from tablename1 left join tablename2 using (common column);

non - ansi format:


when we write outer joins in non-ansi format then we should use join operator (+)
select * from table1,table2 where table1.commoncol = table2.commoncol (+);

right outer join


it is used to display the full details of the right table and matched records of the left table.
retrieving all rows(matching and unmatching) from the right side table but retrieving matching rows from the left side table.

ansi format:
select * from tablename1 right outer join / right join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;

select * from tablename1 right join tablename2 using (common column);


non - ansi format:
select * from table1,table2 where table1.commoncol(+) = table2.commoncol;

full outer join


if you join left and right outer joins with union operators such joins are called as full outer join.
retrieving matching and unmatching rows from both sides tables.

ansi format:
select * from tablename1 full outer join / full join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;

select * from tablename1 full join tablename2 using (common column);


non - ansi format:
select * from table1,table2 where table1.commoncol(+) = table2.commoncol(+);

self join
joining a table data by itself is called self join.
in self join a row in one table joined with the row of the same table.
we can create any number of alias names on a single table. Each alias name should be a different name when we compare a
column value within the same table.

self join can be implemented at two situations:


1. comparing a single column value by itself in the table.
2. comparing two different column values to each other in the table.

ex: on comparing a single column values by itself:


select e1.ename,e1.sal from EMPe1,EMPe2
where e1.sal=e2.sal and e2.ename = 'ford';

ex.on comparing two diff.columns to each other:


select e.empno,e.ename,m.empno mgr_no,m.ename mgr_name
from EMP e, EMP m
where 1=1 and m.empno(+)=e.mgr;

join more than two tables:

non-ansi syntax:
select * from <tn1>,<tn2>,<tn3>,.........<tn n>
where <condition1> and <condition2> and <conditions>..........;

ansi syntax:
select * from <tn1> <join key> <tn2>
on <condition1> <join key> <tn3> on <condition2> <join key> <tn4> on <condition2> ............;

select * from <tn1> <join key> <tn2>


using<commoncol> <join key> <tn3> using <commoncol> <join key> <tn4> using <commoncol>............;

SUBQUERY / NESTED QUERY:

If you want to fetch multiple data types from multiple tables we can write join queries but unnecessarily don't write any join query. It will degrade your
database performance or it will decrease your query performance that's why we need to write subqueries.
If you want to get data from one table based on the input value of another table we can use subqueries instead of join.
A query inside another query is called a subquery or nested query or child query.
→ Outer query always depends on the result of inner query.
→ The result set returned by the inner query will be used as input to the outer query.
→ A Subquery is having two components those are,
i) INNER / CHILD / SUBQUERY
ii) OUTER / PARENT / MAIN QUERY
Syntax:
SELECT * FROM <TN> WHERE <CONDITION> (SELECT * FROM ..................(SELECT * FROM ..........(SELECT * FROM .....)));

AS PER THE EXECUTION PROCESS OF SUBQUERY IT AGAIN CLASSIFIED INTO TWO CATEGORIES.

Interview point:

NON - CORRELATED SUBQUERIES


FIRST INNER QUERY EXEC and RETURN VALUE LATER OUTER QUERY WILL EXECUTE.
Outer query always depends on the result of inner query.

SINGLE ROW SUBQUERY


When a subquery returns a single value is called a single row subquery.
In single row subquery we can use operators are =,<,>,<=,>=,!=

EX:
Display DNAME for EMPNO 7654.

SELECT DNAME FROM DEPT WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE EMPNO=7654);

If a quarry used in place of a column name that is called scalar quarry. It wont allow more than 1 value
ex :select ename ,(select dname from dept where emp.deptno = dept.deptno) dept from emp ;

MULTIPLE ROW SUBQUERY


When a subquery returns more than one value is called a multiple row subquery.
In this subquery we can use the following operators are:

IN OPERATOR:
The IN operator returns TRUE if the comparison value is contained in the list it accepts multiple values.
EX: SELECT ENAME,SAL FROM EMP WHERE SAL IN (SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO);

ANY
IT IS USED TO COMPARE ANY OF THE VALUES IN THE GIVEN LIST.
A > ANY(10,20,30) accept all values above 10
A < ANY(10,20,30) accept all values below 30
ALL
IS USED TO COMPARE ALL OF THE VALUES IN THE GIVEN LIST.
A > All(10,20,30) accept all values above 30
A < All(10,20,30) accept all values below 10

MULTIPLE COLUMN SUBQUERY


multiple columns values of inner query comparing with multiple columns values of outer query is called as mcsq.
subquery is going to compare multiple columns with the outer query columns.
return more than one column as its result.
syntax:
SELECT * FROM <TN> WHERE(<COL1>,<COL2>,............)
IN(SELECT <COL1>,<COL2>,....... FROM <TN>);

EX: To find the highest sal in each job


SELECT * FROM EMP WHERE(JOB,SAL) IN(SELECT JOB,MAX(SAL) FROM EMP GROUP BY JOB);

INLINE VIEW
It works like a query,which is having the query in from clause or instead of table.
It is a special type of subquery in oracle. Providing a select query in place of table name in select statement.
SELECT * FROM (<SELECT QUERY>); -->-INLINE VIEW

gen. subquery is not allowed to use the "order by" clause. so that we use "inline view".
gen. column alias names are not allowed to be used in "where" clause condition.so that we use "inline view ".
EX:FIRST 5 RECORDS

SELECT * FROM (SELECT ROWNUM R,EMP.* FROM EMP ) WHERE R<=5;

CORRELATED SUBQUERIES:
IN CORRELATED SUBQUERY FIRST OUTER QUERY IS EXECUTED AND LATER INNER QUERY WILL EXECUTE.
→ Generally in non correlated subquery child queries are executed first whereas in correlated subquery parent queries are
executed first.
→ In correlated subquery we must create an alias name in the parent query table and pass that alias name into the child query
where clause.
→ Correlated subqueries are used for row by row processing.
→ Each subquery is executed once for every row of the outer query.
Syntax:
SELECT column1, column2, ....FROM table1 aliasname1
WHERE column1 operator
(SELECT column1, column2 FROM table2 aliasname2
WHERE aliasname2.columnname = aliasname1.columnname);

EX: Write a query to find the highest earning employee in each department?

SELECT DEPTNO, EMPNO, SAL FROM EMP E


WHERE 1 = (SELECT COUNT(DISTINCT SAL)FROM EMP E1
WHERE E.DEPTNO = E1.DEPTNO AND E.SAL <= E1.SAL );

EXISTS OPERATOR:
→ it is a special operator which is used in correlated subquery only.
This operator is used to check whether row / rows exist in the table or not.
→ it returns either true (or) false. if the subquery returns at least one row then returns true or else if the subquery does not return
any row then returns false.
WHERE EXISTS(<SELECT STATEMENT>)

note: when we use the exists operator in where clause condition there is no need to mention a column name explicitly because internally oracle
server will take column name of a table by default.

EX: to display department details in which department employees are working?


SELECT * FROM USER_SYNONYMS / All_synonyms;

SELECT * FROM DEPT D WHERE EXISTS(SELECT DEPTNO FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SYNONYM
Synonym is an alternative name or Permanent alias name given to the table, view, sequence, stored procedure, function or packages for the user's
convenience to use it.
→ Synonyms can be created for the entire object only.
→ It is used to hold the owner of the table.
→ It works like a mirror image of the tables.
→ It does not have its own structure.
→ It depends on the tables.
→ Synonym is a permanent alias name for a single Base table or view.
→ It supports DML and DQL,DCL operations.
→ Synonyms can be PUBLIC or PRIVATE.
→ By default the synonym is PRIVATE.
→ All synonyms are created in user_synonyms, all_synonyms table.

Note :
→ If any changes in the synonym are automatically reflected into the table and vice versa.
→ Synonym is a dependent object whereas table is independent object, which means if a table is dropped then synonym stops its working.
If a table is recalled back then the synonym will start working.
Private Synonym :
→ It is used to create a private synonym in the current schema and accessed within that schema only.

SYNTAX:
CREATE OR REPLACE SYNONYM <SCHEMANAME>.<SYNONYM NAME> FOR <SCHEMANAME>.<TABLENAME>;

Public Synonym:
This synonym is created from a user, which has got DBA privileges.
When a public synonym is created and if the same object gets accessed from another user, table name should not be used as qualifier.

SYNTAX:
CREATE OR REPLACE [PUBLIC]SYNONYM <SCHEMANAME>.<SYNONYM NAME> FOR <SCHEMANAME>.<TABLENAME>;

DROPPING A SYNONYM:
DROP [PUBLIC] SYNONYM <synonym_name>;
PUBLIC synonyms can be dropped from a user, which has got DBA privileges.

Drawbacks of Synonyms:
→ We can't create synonyms on multiple tables.
→ We can't create synonyms on particular columns.
→ We can't create synonyms on a particular record.

VIEWS
We have some drawbacks in synonyms.The drawbacks will be overwritten while using views.

View is nothing but an image table or virtual table, which is created for a base table.
→ It is a virtual table to hide the base table and it works like a mirror image of the table.
→ It doesn't have its own structure.
→ It is not possible to modify the structure of the table by using views.
→ We can define views on synonyms and synonyms on views.
→ View can be created by taking all values from the base table or by taking only selected values from the base table.
→ Any modifications made through a view automatically updates the base table and vice versa.
→ View is a database object , which will store a query in compiled format, hence it is called "Stored Query".
→ View supports only DML And DQL.
→ All views are stored by all_views,user_views

SELECT * FROM all_views / user_views;

NOTE :
When the base table is dropped, the view will stop working.
When the base table is back in the database, the view will start working.

Adding new columns to a table that has an associated view does not update the view's result set, even if the view uses a wildcard (*) to represent all
table columns. To incorporate new columns, you must recreate the view.

Advantages of views:
1. Provides high security
2. Improves performance
3. Network traffic gets reduces
4. Shortens SQL queries
5. Supports to perform summarized calculation fastly
6. Supports to INSERT/UPDATE/DELETE related data
7. We can retrieve the data from many tables (joins)

Type of views

Simple View / Read write view


It is used to define a view on a single table that views are called as simple views.
It can perform all DML & DML operations like select, Insert, Update and Delete.

Syntax:
CREATE [ OR REPLACE ] [ FORCE / NOFORCE ] VIEW view_name
AS SELECT query
[WITH READ ONLY / WITH CHECK OPTION];

Read only views


When a view is created as a Read only view, it will not allow a user to perform DML operations through a view.
A keyword called "WITH READ ONLY" should be associated.
It will allow select and desc commands.

EX:
CREATE OR REPLACE VIEW EMP_RO
AS
SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP
WITH READ ONLY;

Check option views


These views will support inserting the data into the base table only for those records that match with the condition mentioned at SELECT query.
An option called "WITH CHECK OPTION" is used.
It is a constraint which is used to restrict rows on the base table through a view while performing DML operations.

EX:
CREATE OR REPLACE VIEW V4
AS
SELECT EMPNO,ENAME,DEPTNO FROM EMP1 WHERE DEPTNO=20
WITH CHECK OPTION;
Complex View
It is used to define a view on multiple tables that views are called as complex views.
→ We can not perform DML operations(INSERT,UPDATE,DELETE) on complex views but by using instead of triggers we can.
→ A view is created based on a single table using the below clauses.'
Group by clause
Order by clause
Group function/Aggregate function
Joins
Subquery

Duplicate column names will not be accepted by the view while selecting data using join conditions.
when we create a view with a function then we must create an alias name for those functions otherwise oracle returns an error.

EX:
CREATE OR REPLACE VIEW V1
AS
SELECT DEPTNO,SUM(SAL) SUM_SAL,AVG(SAL) AVG_SAL,MAX(SAL) MAX_SAL, MIN(SAL) MIN_SAL
FROM EMP
WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='RESEARCH')
GROUP BY DEPTNO;

Force View
It is used to define a view without a base table.
Generally views are created based on tables but force views are created without base tables.
CREATE FORCE VIEW <VIEW NAME> AS SELECT * FROM <TN>;

Materialized Views
It is one of the views which has its own structure.
→ It does not allow the DML operations on Materialized views.
→ It is used to store the historical data
→ We can define a view on a table which has the primary key.
→ Views don't store any data whereas materialized views are storing data.
→ Even if we drop a base table, a materialized view can be accessible.
CREATE MATERIALIZED VIEW <VIEW NAME> AS SELECT * FROM <TABLENAME>;

When we update data in base table the data will be reflected in view but materialized view will not update.

If we want to perform DML operations on a materialized view we can use the following syntax.

→ ON DEMAND / ON COMMIT:
In oracle we are refreshing materialized views in two ways.

ON DEMAND:
It is a default refreshing method.
In this method we are refreshing the materialized view by using the "DBMS_MVIEW" procedure.

SYNTAX:
EXECUTE DBMS_MVIEW.REFRESH ('<MVIEW NAME>');

ON COMMIT:
→ We can refresh a materialized view without using "DBMS_MVIEW" but using the "ON COMMIT" method.
Syntax:
CREATE MATERIALIZED VIEW <VIEW NAME>
REFRESH ON COMMIT
AS SELECT * FROM <TN>;

HOW TO DROP A VIEW:


DROP VIEW <VIEWNAME>;
DROP MATERIALIZED VIEW <MVIEW NAME>;
SEQUENCES

Sequence is a database object, which is stored in a database server and it is used to generate the sequence of numbers on a particular column of
table automatically.
→ it automatically generates primary key or unique key values.
→ it can be either asc /desc order.
→ It is Used to generate the sequence number on a particular column of table automatically.
→ It is not related to any table.
→ Sequence will start generating values from its min value.
→ Default MIN Value is 1.
→ Default incremental value of sequence is +1.
→ ALL_SEQUENCES --> only sequences will be displayed

SYNTAX:
CREATE [OR REPLACE] SEQUENCE <seq_name>
[START WITH <value>] → Default MIN value is 1
[INCREMENT BY <value>] → Default 1
[MINVALUE <value>] → Default 1
[MAXVALUE <value>] → Default → 10^27 → 999999999999999999999999999
[NOCYCLE / CYCLE] → Default NOCYCLE
[NOCACHE / CACHE <size>]; → Default 20

Increment by 1 / n : by default a sequence is incremented by 1.


when this clause is used it will allow a user to specify the increment either with +ve or -ve value.

any interval can be specified for increment. if +ve value is specified it generates the sequence of numbers in ascending order. if -ve value is specified
it generates the sequence of numbers in descending order.

start with n : this clause is used to specify the start value of a sequence.
it gets executed only for once.
start value should be >=minvalue and <=maxvalue.
minvalue n : it is used to specify the min value of a sequence.
maxvalue n : it is used to specify the max value of a sequence.

nocycle : it is a default option which is set for a sequence and that sequence will be not reusable.

cycle : it is used to make a sequence repeat with respect to generating the numbers between min value to max value and vice versa.

no cache:
It is the default parameter. When we create a sequence with "no cache" parameters then the set of sequence values are stored into database
memory.
Every time we want to access sequence numbers then the oracle server will go to database memory and return to the user. so that it will degrade
the performance of an application.

cache n:
when we create a sequence with a "cache " parameter then the system is allocating temp. memory(cache) and in this memory we will store the set
sequence numbers.whenever user wants to access sequence numbers then oracle server will go to cache memory and return to the user.
accessing data from cache is much faster than accessing data from database.it will increase the performance of an application. here "n" represents
the size of the cache file. minimum size of cache is 2kb and maximum size of cache is 20kb.

It uses 2 pseudo columns:


nextval - It gives the next value generated by the sequence.
currval - It gives the present value provided by the sequence.
They can be used in :
1. at SELECT statement
2. at INSERT,UPDATE statement
3. at Outermost queries

Restriction :
1. Can't be used at DELETE command
2. Can't be used at Inner queries
3. Can't be used with DISTINCT operator
4. Can't be used at Group By Clause

ALTERING A SEQUENCE:
Sequences which are created can be altered w.r.to minvalue, maxvalue, increment by value... etc. It does not support changing the START
value.
Syntax:

ALTER SEQUENCE sequence_name


INCREMENT BY n
MINVALUE n
MAXVALUE n ......;

DROPPING A SEQUENCE:
A sequence which is created can be dropped using DROP SEQUENCE command.
DROP SEQUENCE seq_name;

VIEWING THE SEQUENCES INFORMATION:


SELECT SEQUENCE_NAME,MIN_VALUE,MAX_VALUE,INCREMENT_BY,LAST_NUMBER FROM USER_SEQUENCES;

Pseudo Columns:
A Pseudo column behaves like a table column,but it is not actually stored in the table.
You can select from Pseudo columns, but you can not insert, update and delete their values.

Different types in SQL:


USER,UID
Used to identify the user and user id that we are connected to
SELECT USER,UID FROM DUAL;

SYSDATE
It displays the system date.
SELECT SYSDATE FROM DUAL;

SYSTIMESTAMP
It displays the date and time
SELECT SYSTIMESTAMP FROM DUAL;

CURRVAL
It returns the current value of the sequence.
Sequence_name.CURRVAL → can be used in place of values given for a col.

NEXTVAL
It returns the increment value of the sequence.
Sequence_name.nextval

ROWID
ROWID is a pseudo column in a table which stores and returns row addresses in hexadecimal format In the database, each row has a unique
address.
→ The ROWID pseudocolumn returns the address of the row.
→ Generated automatically while inserting records into a table
→ ROWID is alphanumeric.
→ ROWID is the permanent unique identifier in the database.
→ A user can access a row quickly and easily using its ROWID.
→ ROWID can also be used to delete the duplicate records from a table.
→ It consists of Object id, Data file id, Block id & Record id. It is Reusable.

ROWNUM
Generated sequences for query output.
→ It is a dynamic value automatically retrieved along with Select statement output.
→ ROWNUM is numeric.
→ ROWNUM is temporary.It won't be stored in the database.
EX: SELECT ROWID ROW_ID,ROWNUM,ENAME,SAL FROM EMP;

We can't use rowid or rownum in where clause, we can achieve by using inline view

LEVEL:
It will arrange the select statement output in Inverted tree structure ( Hierarchical Tree ) and gives the position of row in Tree.
( Returns Number )
The Level Pseudocolumn returns 1 for a root row,2 for a child of a root and so on.
A root row is the highest row within an inverted tree.
A parent row is any row that has children.
A child row is any non-rooted row
A leaf row is any row or node without children.

To establish the hierarchical relationship with the level we need.


Start with clause
connect by clause

EX: Selecting Nth highest value from table.


SELECT LEVEL,MAX(COLNAME)
FROM <TABLENAME>
WHERE LEVEL=&LEVELNO
CONNECT BY PRIOR COLNAME>COLNAME GROUP BY LEVEL ;

INDEXES:

index is a database object which is used to retrieve data from a table fastly.
A database index will work as a book index page in a text book. In a text book by using an index page we can retrieve a particular topic from a text
book very quickly. The same as by using database index objects we can retrieve a particular row from a table very fastly.
By using indexes we can save time and improve the performance of databases.
index objects can be created on a particular column (or) columns of a table and these columns are called "index key columns".
index uses rowid to fetch data from the table.

All databases are supporting the following two types of searching mechanisms those are,

table scan(default)
It is a default scanning mechanism for retrieving data from tables. In this mechanism oracle server is scanning entire table(top - bottom)

Index scan
In the index scan mechanism oracle server scans only indexed columns from a table.

TYPES OF INDEXES:

Btree Index
It stands for Balanced Trees.
It is an ordered list of values divided into ranges along with the row id information stored in the index segment.
B-tree indexes are suitable for containing a high number of values.

1)Simple Index
When we create an index on a single column then we call it a simple index.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN>(<COLUMN NAME>);

2)Composite Index
When we create an index on multiple columns then we call it a Composite index.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN>(<COLUMN NAME1>,<COLUMN NAME2>,..........);
3)Unique Index
When we create an index based on a "UNIQUE CONSTRAINT" column, it is called a unique index.
Unique indexes do not allow duplicate values.
SYNTAX:
CREATE UNIQUE INDEX <INDEX NAME> ON <TN>(<COLUMN NAME1>,<COLUMN NAME2>,..........);

4)Function Based Index


When we create an index based on a function then we call it a function based index.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN>(<FUNCTION NAME>(COLUMN NAME))

5)Reverse Key Index


A reverse key index when compared to standard index, reverses each byte of the column being indexed while keeping the column order.

Bitmap Index
It is created on distinct values of a particular column.
→ Generally Bitmap indexes are created on low cardinality of columns.
→ When we create a Bitmap index internally oracle server is preparing a Bitmap indexed table with bit numbers 1 and 0.

cardinality:
it refers to the uniqueness of data values contained in a particular column of table.
cardinality of column = no.of distinct values of a column/ no.of rows in a table

syntax:
create bitmap index <index name> on <tn>(<column name>);

DYNAMIC SQL:
→ DYNAMIC SQL IS A PROGRAMMING TECHNIQUE TO BUILD SQL STATEMENTS AT RUNTIME.
→ Both compilation and execution happens at run time. It will be useful when we don't have the values (of column or table
name)till run time.

EX:
Table_NAME := '&TNAME ' ; → will ask for input where ever it find & symbol
A number := :number ; → will give the same value to all the :number that we used in a single query.(commonly known as bind
parameter)

We can use’ &&Tname’ to store the values permanently into ‘&Tname’ till server disconnects

How to select random record from the data


select * from (select * from emp
order by dbms_random.random)
where rownum =1

how to find out duplicate data


select empno,count(*) from emp
group by empno
having count(*)>1;

how to find out the columns in the base table.


select count(column_name) from all_tab_columns
where table_name='EMP';

How to delete duplicate data


delete from emp1 where rowid not in (select min(rowid) from emp1 group by ename);
Selecting Nth highest value from table.
SELECT LEVEL,MAX(COLNAME)
FROM <TABLENAME>
WHERE LEVEL=&LEVELNO
CONNECT BY PRIOR COLNAME>COLNAME GROUP BY LEVEL ;

Select * from (select Dense_rank()over(order by SALdesc) s_no, emp.* from emp) where s_no = &Highest_values ;

You might also like