Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

CONTENTS

TOPIC NAME PAGE NO

DDL - DATA DEFINITION LANGUAGE 1-4


DML – DATA MANIPULATION LANGUAGE 5-6
TCL – TRANSACTION CONTROL LANGUAGE 7-8
SINGLE ROW FUNCTIONS 9-16
GROUP FUNCTIONS 17-18
SET OPERATORS 19-20
ANALYTICAL FUNCTIONS 21-22
PSEUDO COLUMNS 23-25
JOINS 26-27
SUB QUERIES 28-31
INDEX 32
SYNONYM 33
VIEWS 34
MATERIALIZED VIEWS 35
SQL LOADER 36-38

1
DATA DEFINITION LANGUAGE
DATA DEFINITION LANGUAGE:

DDL is Auto Commit, it is Data Definition Language which is used to define the data structures.
It is used to create and modify the structure of database objects in a database. These database objects
include views, schemas, tables, indexes, etc.
A schema is the collection of multiple database objects, which are known as schema objects. These objects
have direct access by their owner schema
DDL STATEMENTS:

 CREATE
 ALTER
 RENAME
 DROP
 TRUNCATE
CREATE:
It is used to create tables in the database.
CREATE TABLE STUDENTS (SID NUMBER (4), SNAME VARCHAR2 (30), RESUME LONG, EMAIL VARCHAR2(30),
DOB DATE);
ALTER:
It is used to add, drop, rename and modify a column in a table.

ADD COLUMN:
ALTER TABLE STUDENTS ADD ADDRESS VARCHAR (100);

 Address column added to students table


DROP COLUMN:
ALTER TABLE STUDENTS DROP COLUMN RESUME;

 Column resume dropped


MODIFY DATATYPE:
ALTER TABLE STUDENTS MODIFY DOB TIMESTAMP;

 Modify DOB datatype


RENAME COLUMN:

ALTER TABLE STUDENTS RENAME COLUMN EMAIL TO EMAILID;

 Column email renamed to emailed


DROP TABLE:
DROP TABLE STUDENTS;

 Student Table dropped

2
RENAME TABLE:
RENAME COURSES TO SUBJECT;

 Rename table courses to subject


TRUNCATE:
To delete all rows from a table and also all clears the memory space.
TRUNCATE TABLE EMP;
BASIC SYNTAX:
To find the database name:
SELECT NAME FROM V$DATABASE;
To find how many users:
SELECT * FROM ALL_USERS;
To find how many tables created by user:
SELECT * FROM USER_TABLES;
To find table structure:
DESC T1;
DATA TYPES:

A datatype associates a fixed set of properties with the values that can be used in a column of a table or in
an argument of a procedure or function. It also specifies the possible values for that type, the operations
that can be performed on that type and the way the values of that type are stored.

 Number
 Char
 Varchar
 Long
 Clob
 Blob
 Date
 Timestamp
 Bfile
 XML type
Number:
Maximum length up to 38 spaces (Default length)
Char:
Maximum length up to 2000 spaces (Alpha, Numbers, Special characters), Unused spaces will not get
released.
Varchar:
Maximum length up to 4000, Unused spaces will get released.
3
Long:
Maximum length up to 2 GB. In a table only one Long datatype can be used

Clob:
Character large object, Maximum length up to 4 GB.
Blob:
Binary large object, Maximum capacity up to 8 GB.
Date:
Date can be stored in this datatype in the format ‘DD-MON-YY’.
Timestamp:
Both Date & Time can be stored in this datatype.
Bfile:
To store the file path in the server
Xml type:
To store the XML type of files

4
DATA MANIPULATION LANGUAGE
Data manipulation Language:

DML is Manual Commit. A data manipulation language (DML) is a computer programming language used for
adding inserting, deleting, and modifying (updating) data in a database and permitting users to manipulate
data in a database.

 Insert
 Update
 Delete
 Merge

INSERT:

INSERT statement inserts rows into an existing table.

UPDATE:

UPDATE statement updates (changes the values of) a set of existing table rows.

DELETE:

DELETE statement deletes rows from a table.

Insert:
Insert into course(cid,cname) values(10,’SQL’);
To check:
Select * from course;
Insert ALL:
Insert all into course(cid,cname) values(20,’PLSQL’)
Into course(cid,cname) values(30,’SAS’)

Into course(cid,cname) values(40,’AWS’)


Select * from dual;
 Insert 3 rows
 Select dual should be used

Modify the data:


Update course set cname=’oracle’ where cname=’SAS’;
 Data change from SAS to Oracle

Update course set cname=’devops’;


 All rows updated without where clause

5
Delete the row:
Delete from course where cid=40;

 cid=40 row deleted

Delete from course, All rows deleted


Merge:
Update + Insert or UPSERT
It selects data from one or more source tables and updates or inserts into target table.
Both can be done

Merge into t2 usimg t1 on(t1.a=t2.a)


When matched then update set t2.b=t1.b
When not matched then
Insert(t2.a,t2.b values (t1.a,t1.b);

6
TRANSACTION CONTROL LANGUAGE
TCL stands for Transaction Control Languages. These commands are used for maintaining consistency of
the database and for the management of transactions made by the DML commands.

 Commit
 Rollback
 Save point

The basic transaction control statements are:


 SAVEPOINT, which marks a savepoint in a transaction—a point to which we can later roll back.
Savepoints are optional, and a transaction can have multiple savepoints.

 COMMIT, which ends the current transaction, makes its changes permanent, erases its savepoints,
and releases its locks.

 ROLLBACK, which rolls back (undoes) either the entire current transaction or only the changes
made after the specified savepoint.

Commit:
Committing a transaction makes its changes permanent, erases its savepoints, and releases its locks.

 It saves all pending changes permanently

Syntax : Commit;

 To save all transactions

Rollback:
Rolling back a transaction undoes its changes. We can roll back the entire current transaction, or you can
roll it back only to a specified savepoint.

 Undo the transaction before commit


 To discard all pending transaction

Syntax : Rollback;

 While inserting records commit to save records permanently


 Rollback will undo all pending transaction

Savepoint:
The SAVEPOINT statement marks a savepoint in a transaction—a point to which you can later roll back.
Savepoints are optional, and a transaction can have multiple savepoints.

 Savepoint is a marker
 Partial rollback

Syntax : Savepoint X;

7
Table T1
Column A
1
2
Savepoint x;
3
4
Savepoint y;
5
6
Rollback to y;
Commit;

8
SINGLE ROW FUNCTIONS
Single-row functions return a single result row for every row of a queried table or view.

TYPES OF SINGLE ROW FUNCTIONS

 CASE MANIPULATION FUNCTIONS


 CHARACTER MANIPULATION FUNCTIONS
 NUMBER FUNCTIONS
 DATE FUNCTIONS
 CONTROL STATEMENTS
 GENERAL FUNCTIONS
 NULL STATEMENTS

CASE MANIPULATION FUNCTIONS

 UPPER CASE
 LOWER CASE
 INITIAL CHARACTER UPPERCASE

SELECT UPPER(FIRST_NAME), LOWER(FIRST_NAME), INITCAP(FIRST_NAME)


FROM EMPLOYEES;
Upper – Uppercase

Lower – Lowercase
Initcap - 1st character capital
CHARACTER MANIPULATION FUNCTIONS
Length:
To find LENGTH Of the string
SELECT FIRST_NAME, LENGTH(FIRST_NAME) FROM EMPLOYEES;
Length displays no of characters in each row for that column
Sub string:
FIRST 3 CHARACTERS IN O/P, STARTING POSITION, LENGTH
SELECT FIRST_NAME, SUBSTR(FIRST_NAME,1,3) FROM EMPLOYEES;

FIRST 3 CHARACTERS IN O/P, STARTING POSITION, LENGTH


SELECT FIRST_NAME, SUBSTR(FIRST_NAME,2,3) FROM EMPLOYEES;
2nd arguments is starting position
3rd argument is length to be displayed from the column
In string:
Displays position of ‘e’ (character)
Starting position from 1
9
Occurrence on 1
1.SEARCH CHARACTER 'e', STARTING POSITION, FIRST OCCURANCE

SELECT FIRST_NAME, INSTR(FIRST_NAME,'e',1,1) FROM EMPLOYEES;


2.SEARCH CHARACTER 'e', STARTING POSITION, SECOND OCCURANCE
SELECT FIRST_NAME, INSTR(FIRST_NAME,'e',1,2) FROM EMPLOYEES;
Replace:
Replaces the selected string with another string
06. FIND 'e', REPLACE WITH 'X'
SELECT FIRST_NAME, REPLACE(FIRST_NAME,'e','X') FROM EMPLOYEES;
07. FIND 'e'
SELECT FIRST_NAME, REPLACE(FIRST_NAME,'e') FROM EMPLOYEES;
08. FIND 'St', REPLACE WITH 'XY'
SELECT FIRST_NAME, REPLACE(FIRST_NAME,'St','XY') FROM EMPLOYEES;
Translate:
ONE-TO-ONE REPLACEMENT (S=X, N=Y)
SELECT FIRST_NAME, TRANSLATE(FIRST_NAME,'Sn''XY') FROM EMPLOYEES;
Replaces character by character if value not given , it is left blank
Reverse:
SELECT FIRST_NAME, REVERSE(FIRST_NAME) FROM EMPLOYEES;
Reverses the string for the given column
Concatenate:
SELECT CONCAT (FIRST_NAME, LAST_NAME) FROM EMPLOYEES;
- JOINING any two column values without any space.
RPAD and LPAD:
LPAD and RPAD functions pad the given string up to a specific length with a given character.
RPAD:
All Names will be padded with asterisk (*) for 10 Characters in RHS
SELECT FIRST_NAME, RPAD(FIRST_NAME,10,'*') FROM EMPLOYEES;
LPAD:
All names will print with asterisk (*) for 10 characters in LHS
SELECT FIRST_NAME, LPAD(FIRST_NAME,10,'*') FROM EMPLOYEES;

10
TRIM:
TRIM function trims the string input from the start or end.

TO TRIM RHS ****


SELECT RTRIM('******HEL****LO****','*') FROM DUAL;
Returns : ******HEL****LO
TO TRIM LHS ****
SELECT LTRIM('******HEL****LO****','*') FROM DUAL;
Returns : HEL****LO*****
TO REMOVE ALL ****
SELECT REPLACE('******HEL****LO****','*') FROM DUAL;
Returns: HELLO
TO REMOVE LEADING AND TRAILING ****
SELECT TRIM('*'FROM'*****HEL****LO*****') FROM DUAL;
Returns: Hel****lo
NUMBER FUNCTIONS:

 ROUND
 TRUNC
 MOD
 SIGN
 ABS

ROUND:
TO ROUNDOFF THE GIVEN VALUE
0.5 and above .5 rounded to next digit
SELECT ROUND(1.9) FROM DUAL;
Returns : 2

TRUNC:
TO REMOVE THE VALUES AFTER DECIMAL
SELECT TRUNC(1.9) FROM DUAL;
MOD:
TO FIND THE REMINDER
SELECT MOD(5,2) FROM DUAL;

11
SIGN:
It gives -1 for less than 0 value, It gives 1 for greater than 0 value

SELECT SIGN(-5) FROM DUAL;


Returns: 0
SELECT SIGN(NULL) FROM DUAL;
Returns: Null
SIGN:
TO REMOVE MINUS SYMBOL
SELECT ABS(-5) FROM DUAL;
DATE FUNCTIONS:

 Months_between
 Add_months
 Next_day
 Last_day

TO DISPLAY SYSTEM DATE


SELECT SYSDATE FROM DUAL;
MONTHS_BETWEEN
TO FIND DIFFERENCE BETWEEN MONTHS
SELECT MONTHS_BETWEEN(SYSDATE,'10-AUG-20')FROM DUAL;
TO FIND DIFFERENCE BETWEEN MONTHS
SELECT MONTHS_BETWEEN(SYSDATE,'10-AUG-20')/12 FROM DUAL;
ADD DAYS:
TO ADD DAYS FROM SYSTEM DATE
SELECT SYSDATE+10 FROM DUAL;
SUBTRACT DAYS:
TO SUBTRACT DAYS FROM SYSTEM DATE
SELECT SYSDATE-10 FROM DUAL;
ADD_MONTHS:
TO ADD MONTHS FROM SYSTEM DATE
SELECT ADD_MONTHS(SYSDATE,2) FROM DUAL;
TO SUBTRACT MONTHS FROM SYSTEM DATE
SELECT ADD_MONTHS(SYSDATE,-2) FROM DUAL;

12
NEXT DAY:
TO FIND SOME NEXT DAY

SELECT NEXT_DAY(SYSDATE,'FRIDAY') FROM DUAL;


SELECT NEXT_DAY(SYSDATE,6) FROM DUAL;
LAST DAY:
TO FIND LAST DAY OF CURRENT MONTH
SELECT LAST_DAY(SYSDATE) FROM DUAL;
TO FIND LAST DAY OF SOME MONTH
SELECT LAST_DAY('05-FEB-20') FROM DUAL;
CONTROL STATEMENTS:
DECODING THE CHARACTERS:
SELECT DEPARTMENT_ID, DECODE(DEPARTMENT_ID,10,'A',20,'B',30,'C','X')
FROM DEPARTMENTS;
Creates the column and replace 10 to A and 20 to B
Rest is replaced as X
Decode = IF
CASE STATEMENT:
The CASE statement goes through conditions and returns a value when the first condition is met (like an if-
then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions
are true, it returns the value in the ELSE clause.
SELECT DEPARTMENT_ID,
CASE
WHEN DEPARTMENT_ID = 10 THEN 'A'

WHEN DEPARTMENT_ID = 20 THEN 'B'


WHEN DEPARTMENT_ID = 30 THEN 'C'
ELSE 'X' END
FROM DEPARTMENTS;
GENERAL FUNCTIONS:
TO FIND GREATEST VALUE
SELECT GREATEST (4,1,2) FROM DUAL;
Finds the greatest number

13
TO FIND LEAST VALUE
SELECT LEAST (4,1,2) FROM DUAL;

Find least value


NULL STATEMENTS:
TO REPLACE NULL VALUE
SELECT A, NVL(A,0) FROM T1;
Null value in the column A replaced by 0.
NVL2:
TO REPLACE BOTH NULL & NOT NULL
If first value is null in column a replaced by 0 else replaced by 1.
SELECT A, NVL2(A,1,0) FROM T1;
NULLIF:
Null if accepts 2 arguments, returns null if both arguments are equal,
Else the first argument
SELECT NULLIF (4,4) FROM DUAL;
SELECT NULLIF (7,4) FROM DUAL;
COALSECE:
Coalesce accepts n number of arguments,
Returns the first not null value from the argument list
If all values are null, returns null
SELECT COALESCE (NULL, NULL,4, NULL,2) FROM DUAL;
SELECT COALESCE (NULL, NULL, NULL, NULL) FROM DUAL;
Returns 1st not Null Value
IF all are null returns null value
Conversion Functions:
Conversions functions are used to convert one data type to another type. In some cases, oracle server
automatically converts the data to the required type. This is called implicit conversion. Explicit conversions
are done by using the conversion functions. You have to take care of explicit conversions.
Implicit Data Type Conversion:
A VARCHAR2 or CHAR value can be implicitly converted to NUMBER or DATE type value by Oracle.
Similarly, a NUMBER or DATA type value can be automatically converted to character data by Oracle
server. Note that the implicit interconversion happens only when the character represents a valid number
or date type value respectively.

14
For example, examine the below SELECT queries. Both the queries will give the same result because Oracle
internally treats 15000 and '15000' as same.
Query-1
SELECT employee_id,first_name,salary
FROM employees
WHERE salary > 15000;
Query-2
SELECT employee_id,first_name,salary FROM employees WHERE salary > '15000';
Explicit conversions
You can explicitly specify datatype conversions using SQL conversion functions. SQL functions that
explicitly convert a value from one datatype to another.
Oracle provides three functions to covert from one data type to another.
1. To_CHAR ( number | date, [fmt], [nlsparams] )

The TO_CHAR function converts the number or date to VARCHAR2 data type in the specified format (fmt).
The nlsparams parameter is used for number conversions. The nlsparams specifies the following number
format elements decimal character

 Group separator

 Local currency symbol

 International currency symbol

If the parameters are omitted, then it uses the default formats specified in the session.

Converting Dates to Character Type Examples

The Date format models are:

 YYYY: Four digit representation of year

 YEAR: Year spelled out

 MM: Two digit value of month

 MONTH: Full name of month

 MON: Three letter representation of month

15
 DY: Three letter representation of the day of the week

 DAY: Full name of the day

 DD: Numeric day of the month

 fm: used to remove any padded blanks or leading zeros.

SELECT TO_CHAR(hire_date, 'DD-MON-YYYY') FROM EMPLOYEES;


SELECT TO_CHAR(hire_date, 'fmYYYY') FROM EMPLOYEES;
SELECT TO_CHAR(hire_date, 'MON') FROM EMPLOYEES;
SELECT TO_CHAR(hire_date, 'YYYY/MM/DD') FROM EMPLOYEES;

Converting Numbers to Character type Examples


The Number format models are:

 9: Specifies numeric position. The number of 9's determine the display width.

 0: Specifies leading zeros.

 $: Floating dollar sign

 .: Decimal position

 ,: Comma position in the number

SELECT TO_CHAR(price, '$99,999') FROM SALES;


SELECT TO_CHAR(price, '99.99') FROM SALES;
SELECT TO_CHAR(price, '99,00') FROM SALES;

TO_NUMBER (char, ['fmt'] )

The TO_NUMBER function converts the characters to a number format.


SELECT TO_NUMBER('1028','9999') FROM DUAL;
SELECT TO_NUMBER('12,345','99,999') FROM DUAL;

16
GROUP FUNCTIONS
Group Functions:

Group functions are also known as multiple row functions or aggregate functions. It performs the calculation
on set of values and return a single value.
Commonly used functions:
 MIN
 MAX
 AVG
 SUM
 COUNT
Conditions to use group functions:
 Group function accepts only one argument, Error occurs if we give more than one argument
 Group function ignores null values
 MIN, MAX & COUNT - These functions accept all data types like string, number & date
 AVG & SUM – These functions accept numbers only
 We can use (*) symbol with count function only, so that the result will come with all null values
 Group by clause need to used when using multiple columns with group function
 Having clause need to be used when using conditions with group function
Basic Syntax:
To find max, min, avg, sum, count salary in a table
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY), SUM(SALARY), COUNT(SALARY) FROM EMPLOYEES;

 Returns max, min,avg,sum,count of employees


SELECT SUM(1,2,3) FROM DUAL;

 Throws error accepts only one: error.


Group gunction ignore null values.
Select count(a) from t1;

 Out of rows ignores null value


 Result is 3
 Ignores null value
AVG:
SELECT AVG(A) FROM T1;

 Total 4 value of 3 and Null


 Avg is 1
 Ignores Null

17
Total Count:
SELECT COUNT(*) FROM T1;

 Returns total row count including Null


 * can be used only in count.
To find min, max, count of first name
SELECT MIN(FIRST_NAME), MAX(FIRST_NAME), COUNT(FIRST_NAME) FROM EMPLOYEES;

 Returns min – 1st row value


 Max returns last row data
 Count –Total row count.
 Min,Max,count can be used in all data types including string, numbers and date.
 AVG and SUM can be used only on numbers.
Group BY:
To find count of first_name under department_id
SELECT DEPARTMENT_ID, COUNT(FIRST_NAME) FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;

 Returns no of employees from first_name grouped by department_id


To find max & min salary under department_id
SELECT DEPARTMENT_ID, MAX(SALARY), MIN(SALARY) FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;

 Returns max and min salary grouped by department_id


To find more than 10 employees under department_id
SELECT DEPARTMENT_ID, COUNT(FIRST_NAME) FROM EMPLOYEES GROUP BY DEPARTMENT_ID
HAVING COUNT(FIRST_NAME) > 10;

 Returns count of employees>10 & grouped by dept_id


 Having clause is used in group by condition
To find the count of repeated names more than once in first_name & order by ascending
SELECT FIRST_NAME, COUNT(FIRST_NAME) FROM EMPLOYEES
GROUP BY FIRST_NAME
HAVING COUNT(FIRST_NAME) > 1
ORDER BY FIRST_NAME ASC

 Returns total no of first_name>1 and grouped by first_name


 All duplicates are listed

18
SET OPERATORS
Set Operators:

Set operators are used to join the results of two or more SELECT statements.

 Union
 Union all
 Intersect
 Minus
Conditions for using set operators:

 Column data type must be same in queries, otherwise result will be in error.
 Number of columns used in query must be same.
 Order by columns must be used in last select statement only.
 It can't be used in SELECT statements containing TABLE collection expressions.
 Column heading can be change using alias ‘AS’.
 The LONG, BLOB, CLOB, BFILE, VARRAY or nested table are not permitted for use in Set operators.
For update clause is not allowed with the set operators.
 We can use more than 2 select statements, Then the order of execution will be from top to bottom
only. We can use parentheses to change the order of execution.
UNION:
When multiple SELECT queries are joined using UNION operator, It displays the data from the both queries
and eliminates the duplicate rows and display data in ascending order by default.
Syntax:
SELECT A FROM T1
UNION
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 1,2,3,4,5 and displays under the column A.
UNION ALL:
When multiple SELECT queries are joined using UNION ALL operator, It displays the data from the both
queries and including the duplicate rows and display data in same order as like in the table.
Syntax:
SELECT A FROM T1
UNION ALL
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 1,2,3,4,1,2,3,5 and displays under the column A.

19
INTERSECT:
Using INTERSECT operator, It displays the common rows from both the SELECT statements, Eliminating the
duplicate rows and data arranged in ascending order by default.
Syntax:
SELECT A FROM T1
UNION ALL
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 1,2,3 and displays under the column A.
MINUS:
Using MINUS operator, It displays all values from first query which is not in second query and eliminates the
duplicate rows and display the data in ascending order.
Syntax:
SELECT A FROM T1
UNION ALL
SELECT B FROM T2;
If A column contains values 1,2,3,4 in T1 table and B column contains values 1,2,3,5.
Returns output 4 and displays under the column A.

20
ANALYTICAL FUNCTIONS
Analytical Functions:

Analytic functions calculate an aggregate value based on a group of rows and it return multiple rows for
each group.
List of Analytical Function:

 Rank
 Dense Rank
 Row_Number
 Lead
 Lag
 Listagg()

RANK:
It is used to calculate the rank of a value in an ordered set of values.

SELECT FIRST_NAME, SALARY, RANK () OVER (ORDER BY SALARY DESC) FROM EMPLOYEES;

 Display salary in desc first


 Add rank column
 If salary has duplicates, Rank skips next rank.

DENSE_RANK:
It is used to calculate the rank of a row. Unlike the RANK function this function returns rank as consecutive
integers.
SELECT FIRST_NAME, SALARY, DENSE_RANK () OVER (ORDER BY SALARY DESC) FROM EMPLOYEES;

 Dense rank will not skip the rank for duplicates.


 Display same rank for duplicates.

ROW NUMBER:
SELECT FIRST_NAME, ROW_NUMBER () OVER (ORDER BY FIRST_NAME ASC) FROM EMPLOYEES;

 Display row number for first_name


 First_name 1st sorted in ascending then row number displays.

LEAD:
To pick next row data
Select first_name, lead(first_name,1,'B') over(order by first_name asc) from employees;

 Order by executes 1st


 Lead picks next row data of first_name with interval or level 1
 For Last row there is no next row data. So it is replaced by B.
 If not Null
 If Level 2 is mentioned. It picks the value after 2 rows
21
LAG:
Select previous row

Select first_name, lag(first_name,1,’A’) over(order by first_name asc) from employees

 Select previous row dale


 For first row A is added. If not Null value is added.

LISTAGG():

 Comma separated values

SELECT LISTAGG(FIRST_NAME,’,’) WITHIN GROUP (ORDER BY FIRST_NAME ASC) FROM EMPLOYEES

 Returns: Alexander, Bruce, Lex, N, Steven

22
PSEUDO COLUMNS
PSEUDO COLUMNS:

 Pseudo columns are basically oracle predefined columns.


 Pseudo columns are columns that can be recovered by using queries but do not exist on the table
physically. It behaves like a table column, but is not actually stored in the table.
 We can select from pseudo columns. But we cannot insert, update, or delete their values.
 It is also similar to a function without arguments.
SYSDATE:
SELECT SYSDATE FROM DUAL;

 It returns the current date of our system.


SYSTIMESTAMP:
SELECT SYSTIMESTAMP FROM DUAL;
It returns the system date, including fractional seconds and time zone.
USER:
SELECT USER FROM DUAL;
Return the User name of a database user.
UID:
SELECT UID FROM DUAL;
Return the User ID of a database user.

ROWNUM:
SELECT FIRST_NAME, SALARY, DEPARTMENT_ID, ROWNUM
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 60;

 Returns dept_id= 60 matching rows


 Rownum displays the row number for results
 Temporarily created row number not stored in DB.
ROWID:
SELECT ROWID, EMPLOYEES.* FROM EMPLOYEES;
Rowid is address of each row, it returns the row id (binary address) of a row in a database table.
It will get generated automatically when we insert a new row, it will store in the database permanently.
SEQUENCE:
Sequence automatically generates unique numbers, it is a schema and sharable object, it replaces the
application code. It is mainly used for generating primary key column values.
Nextval and Currval are sequence attributes, both can be used in sequence only.

23
NEXTVAL:
It increments the value in sequence and returns the next value.

CURRVAL:
It returns the current value in a specified sequence
To Create Sequence
CREATE SEQUENCE S1
START WITH 5
INCREMENT BY 1
MAXVALUE 10;
To Generate The Nextval For Sequence
SELECT S1.NEXTVAL FROM DUAL;

 Nextval displays next sequence number.


To Generate The Currval For Sequence
SELECT S1.CURRVAL FROM DUAL;
Alter The Sequence
ALTER SEQUENCE S1

INCREMENT BY 2
MAXVALUE 30;
SELECT S1.NEXTVAL FROM DUAL;
10
SELECT S1.CURRVAL FROM DUAL;
12

 Displays sequence increment by 2


 Stop at 30

To Display The All Sequences:


SELECT * FROM USER_SEQUENCES;
To Drop The Sequence:
DROP SEQUENCE S1;
To Display The Structure Of A Table
DESC T1;
To Insert New Row In A Table

24
INSERT INTO T1(A) VALUES (1);
1 row created

SELECT ROWID, T1.* FROM T1;

 Displays rowed and existing column


 Rowid is stored permanently in DB
LEVEL:

 It returns the level number of a node in a tree structure, to organize rows from a database table
into a tree structure.
To Find The Hierarchy Levels:
SELECT EMPLOYEE_ID, FIRST_NAME, MANAGER_ID, LEVEL
FROM EMP
START WITH MANAGER_ID IS NULL
CONNECT BY PRIOR EMPLOYEE_ID = MANAGER_ID;

 Displays level of reporting


 Null as level
 Then matches emp_id=man_id to display next level.
SELECT EMPLOYEE_ID, FIRST_NAME, MANAGER_ID, LEVEL
FROM EMP
START WITH FIRST_NAME = 'ALEXANDER'
CONNECT BY PRIOR EMPLOYEE_ID = MANAGER_ID;

 Level 1 starts with alexander


 Next level is matched with emp=man with increment in levels
 Keywords ‘Starts with’ connect by prior.

25
JOINS
Joins:

Join statement basically used for selecting data from two or more tables.
It performs a join whenever multiple tables appear in the FROM clause of the query. The select list of the
query can select any columns from any of these tables
Join condition:
Most join queries contain at least one join condition, either in the FROM clause or in the WHERE clause.
The join condition compares two columns, each from a different table.
Where s.cid=c.cid
Types
 Equi Join
 Outer join
-Left Outer Joins
-Right outer Join
- Full outer Join
 Cross Join
 Self-join

Equi Join/Inner Join:


An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that
have equivalent values for the specified columns.
SELECT STUDENTS.NAME, COURSE.CNAME FROM STUDENTS , COURSE WHERE
STUDENTS.CID=COURSE.CID;
Select s.name, c.name from from students s, course c where s.cid=c.cid
-Combines both tables
Returns s.name,c.name

 To select only matching records

Left Outer Joins:


To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer
join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all
columns of B in the join condition in the WHERE clause.
Select s.Name, c.name from students, course c where s.cid=c.cid(+);
Returns Left unmatched records as well
Right Outer Join:

 To write a query that performs an outer join of tables A and B and returns all rows from B (a right
outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator
(+) to all columns of A in the join condition in the WHERE clause

26
Select s.sname, c.cname from students s, course c where s.cid(+)=c.cid;
Returns unmatched records of right-side table

Full outer Join:


To write a query that performs an outer join and returns all rows from A and B, extended with nulls if they
do not satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.

Select s.name, c.name from students full outer join course c on s.cid=c.cid;
-Returns all values with Null value
-Returns match and unmatched records.
Cross Join:

 Cross join is a Cartesian product


 No of rows in first table joined with no of rows in 2nd table
 Cartesian product is formed when user ignores where clause or valid join conditions

Select s.name, c.name from student s, course c;

 3*3 row result in 9 rows


 5*3 row result in 15 rows
 3*0 row result in 0 rows
 Joins without where clause results in cross join or Cartesian product.

Self join:
Joining a table with itself.
Select e1.first_name as ename, e2.first_name as mname
From emp e1, emp e2
Where e1.manager_id=e2.employee_id(+);
 Considering 1 table as two tables self joining
 + symbol returns employee id without manager_id or manager

27
SUB QUERIES
Subquery is a query within a query, we can create subqueries within the SQL statements. These subqueries
can reside in the WHERE clause, the FROM clause, or the SELECT clause.

 Query embedded within another query is called sub query,


 Query declared inside bracket is called sub query,
 In one query, we can use multiple sub queries,
 Subquery will execute first,
 Output of sub query will take by outer query and give the final output.

TYPES OF SUB QUERIES:


SINGLE ROW SUB QUERY
When a sub query written single row
MULTIPLE ROW SUB QUERY
When a sub query written more than one row
SCALAR SUB QUERY
When a sub query written in select clauses
INLINE VIEW
When a sub query written in from clauses
NESTED SUB QUERY
When a sub query is independent to give result
CORRELATED SUB QUERY
When a sub query is dependent with outer query
MULTIPLE COLUMN SUB QUERY
If there are multiple columns in a result for the query
SINGLE ROW SUB QUERY:
TO FIND WHO GETTING THE MAXIMUM SALARY
SELECT FIRST_NAME, SALARY FROM EMPLOYEES
WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES);
 Subquery executes 1st
 Subquery output is used in outer query
 Returns first_name with max salary

28
TO FIND WHO GETTING THE MNIMUM SALARY
SELECT FIRST_NAME, SALARY

FROM EMPLOYEES WHERE SALARY = (SELECT MN(SALARY) FROM EMPLOYEES);


 Select min salary from sub query
 Sub query output is used in outer query
 First_name, min salary displayed.

TO FIND WHO GETTING THE MAXIMUM & MNIMUM SALARY


SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES)
OR SALARY = (SELECT MN(SALARY) FROM EMPLOYEES);
TO FIND WHO GETTING HIGHER SALARY COMPARING WITH OTHER NAME
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY > (SELECT SALARY FROM EMPLOYEES
WHERE FIRST_NAME = 'Lex');
ALL, ANY, IN -----> TO BE USED FOR MULTIPLE ROW SUB QUERY
>ALL ---> GREATER THAN THE GREATEST VALUE
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY >ALL (4800, 13000, 9000);
 Returns greater than 13000. And it is greatest number among the values

ANY ---> GREATER THAN THE LEAST VALUE


SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY >ANY (4800, 13000, 9000);
 Returns greater than 4800. It is least number among the values.

SELECT FIRST_NAME, SALARY FROM EMPLOYEE WHERE SALARY> ALL (SELECT SALARYFROM EMPLOYEE
WHERE FIRST_NAME =’DAVID’;

 Returns David salary from sub query.


 Then choose greatest among and return all greater salary from outer query

IN ----> EQUAL TO THE VALUE


SELECT FIRST_NAME, SALARY FROM EMPLOYEES WHERE SALARY IN (4800, 13000, 9000);
29
 Returns salary equal to 3 number above
 In acts as = Equal
 If right side has multiple value, we can use all any IN

Any
Select first_name, salary from employees where salary>any (select salary from employees
Whwre first_name=’David’;
 Choose least among Davis salary
 Then returns all greatest from main query

SCALAR SUB QUERY (USING SELECT CLAUSES)


SELECT 1+2+(SELECT 2+3 FROM DUAL)
FROM DUAL;
 Returns 8
 Sub query used in select clause is called scalar sub query

Scalar Sub-query example


If user want to find out the Department name and Number_of_Departments using scalar query you can
use following expression:
Query:
Select D.Department_name(Select Count(E.Department_name) From Employee E Where
E.Department_no=D.Department_no;
INLINE VIEW (USING FROM CLAUSES)
SELECT MAX(SALARY)
(SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 60);
NESTED SUB QUERY
If inner query is independent to give result and then it calls the outer query
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM DEPARTMENTS);
CORRELATED SUB QUERY

(If inner query dependent with the outer query)


SELECT FIRST_NAME, SALARY
FROM EMPLOYEES E

30
WHERE DEPARTMENT_ID IN (SELECT D.DEPARTMENT_ID FROM DEPARTMENTS D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID);

MULTIPLE COLUMN SUB QUERY


No of columns in sub query = No of columns in where clause
(If there is more than one column in the result)
SELECT DEPARTMENT_ID, SALARY, FIRST_NAME
FROM EMPLOYEESWHERE (DEPARTMENT_ID, SALARY) IN (
SELECT DEPARTMENT_ID, MAX(SALARY)
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID);

31
INDEX
Index:

Index used to improve the performance of a query.

 1st it check for syntactic check – Keyword errors


 Then checks for Semantic check – Checks column & tables etc.

SELECT FIRST_NAME, SLARY FROM EMPLOYEES WHERE FIRST_NAME=’DAVID’;

 Access full table to find ‘David’


 To check cost of the query- check in Explain Tab- %CPU utilization

Index Creating:
CREATE INDEX IDEX1 ON EMPLOYEES(FIRST_NAME ASC);

 It will create a copy of index table


 Using index query will be faster and cost will be lesser

To check index created on table name:


SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = 'EMPLOYEES';
CREATE INDEX IDX1 ON EMP(FIRST_NAME ASC);
Types of INDEX:

 B * Tree Index
 Bitmap Index

B Tree index:
 B Tree index created on High cardinality column
 Columns that contain large number of unique values

Low cardinality columns – Low number of unique values


High cardinality columns- High number of unique values
Bitmap Indexes:
 It is created on low cardinality columns
 Columns that contain large number of duplicate values

Composite Index:
It is created with multiple columns
Function based Index:
It is created with based upon the functions
Unique Index:

It is created columns without duplicates

32
SYNONYM
Synonym:

Synonym is an alternative name for an object.


Syntax:
To create synonym for a table:
CREATE SYNONYM STAFF FOR EMPLOYEES;
To view the all user created synonyms:
SELECT * FROM USER_SYNONYMS;
To view the synonym created:
SELECT * FROM STAFF;

 Short name or alternative name for employees


 If the object name already exits, we cannot create the synonym in the same name.
 Multiple synonyms can be created for a table.
 Synonym can be created for synonym

To drop the synonym:


CREATE SYNONYM EMP FOR EMPLOYEES;
DROP SYNONYM EMP;

 If synonym is dropped, table will not be dropped.


 Vice versa if table is dropped synonym won’t be dropped
 It shows synonym exits is no longer valid if executed.

33
VIEWS
View is a virtual table that does not physically exist, it is stored in Oracle data dictionary and do not store
any data.
It can be executed when called, A view is created by a query joining one or more tables.
Types of views:
Simple View - Simple views can only contain a single base table
Complex View - Complex views can be constructed on more than one base table
Advantages:
To make complex query looks simply,
To restrict data access
Basic Syntax:
To save the query result in view:
CREATE OR REPLACE VIEW V1

AS
SELECT FIRST_NAME, SALARY, DEPARTMENT_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 60;
To check the views created by the user:
SELECT * FROM USER_VIEWS;
To call the created views:
SELECT * FROM V1;
To drop the created views:
DROP VIEW V1;

To display all the tables & columns created by the user:


SELECT * FROM USER_TAB_COLUMNS;
To insert a new row in a table:
INSERT INTO T1 (A) VALUES (1);
To restrict inserting rows in views:
CREATE OR REPLACE VIEW V1
AS SELECT FIRST_NAME, SALARY, DEPARTMENT_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 60 WITH READ ONLY

34
MATERIALIZED VIEWS
MATERIALIZED VIEWS:

 Materialized view is a database object that stores query output and precomputed result
 It is used to maintain a local copy for remote database object.
 It is used to improve the performance of complex group by & complex aggregate operations.
 Select statement output will be stored in MV1.
 If base table data is modified, we need to update the materialized view, which means it need to get
refresh.
 MV can be refreshed in different ways. REFRESH ON DEMAND, REFRESH ON COMMIT & REFRESH
PERIOICALLY
BASIC SYNTAX:
TO CREATE MV:
CREATE MATERIALIZED VIEW MV1
AS
SELECT STATEMENT<> ;
TO REFRESH MV:
EXECUTE DBMS_MVIEW.REFRESH(‘MV1);
TO VIEW MV:
SELECT * FROM MV1;

VIEWS MATERIALIZED VIEWS

View is a virtual table that does not physically Materialized view is a database object that
exist stores query output and precomputed result

Triggers can be created Triggers cannot be created

Index cannot be created Index can be created

35
SQL LOADER

 SQL Loader is a bulk loader utility to load data from a flat file to an oracle table.
 It is used for high performance data loads.

Example:

 We have a table in oracle with Two columns and rows.


 We are going to add data from a file a flat file.

Stored in Desktop/course.csv - Comma separated value file


Another file created in notepad

Load data infile ‘/desktop/course.csv’


Append into table course fields terminated by ‘,’
(CID,CNAME)

Explanation:
Load – Specifies the location of the file
Append – To add up with the existing rows
Into – table name
Fields- Separated by ‘,’
Columns - (CID,CNAME)
Saved in Desktop as course.ctl - control file
Next Step
Open cmd
Sqlldr hr
C:\users\raj\desktop\course.ctl

36
SQL*loader
Commit point reached – Logical record count 4
Commit point reached-Logical record count 5

Load data infile ‘c:\users\raj\desktop\course.csv\


TRUNCATE INTO TABLE COURSE
FIELDS TERMINATED BY ‘,’
(CID,CNAME)

 Old records gets deleted in the table using truncate


 New records are added in oracle table

C:\USERS\DINESH\SQLLDR HR/ADMIN
CONTROL = C:\USERS\RAJ\DESTOP\COURSE.CTL

 Rows with different data types won’t be inserted

37
BAD = C:\USERS\RAJ\DESKTOP\1.BAD
LOG= C:\USERS\RAJ\DESKTOP\2.LOG

SKIP = 1

 .Bad file stores missing data or data that are not loaded
 .Log stores the reason for not loading the data and rows that are not loaded.
 Skip 1 refers to 1st row of .csv file which skips the column name so that only data are uploaded.

38

You might also like