SQL Document
SQL Document
1. CHAR
The CHAR datatype stores fixed length character strings, where we must specify the
string length (in characters or bytes) between 1 and 2000 for the CHAR column width.
2. VARCHAR
The VARCHAR datatype stores the variable length character strings with string length
between 1 and 2000 bytes
3. VARCHAR
The VARCHAR2 datatype stores the variable length character strings with string length
between 1 and 4000 bytes.
4. LONG
5. BLOB
The abbreviation is Binary Large Object.
It is used to store images (i.e. .gif, .jpeg, etc.)
6. CLOB
7. DATE
1
8. TIMESTAMP
Timestamp is stored in the database with their respective time zones i.e the value is
adjusted to the user’s session time zone.
9. BFILE
The BFILE datatype stores the unstructured binary data in operating system files outside
the database.
BFILE are read only and cannot be modified.
QUESTIONS
VARCHAR can store up to 2000 bytes. VARCHAR2 can store up to 4000 bytes of
characters.
If we declare datatype as VARCHAR then it will In the case of VARCHAR2 datatype, it will not
occupy space for NULL values. occupy any space for NULL values.
2
DML, DDL, TCL, DCL STATEMENTS
___________________________________________________________________________________
1.1 SELECT
This command is used to retrieve data from the database.
1.2 INSERT
This command is used to insert data into a table.
Example :-
(i) To insert into table with specifying column name.
INSERT INTO T1 (A) VALUES(6);
(ii) To insert into table without specifying column name.
INSERT INTO T1 VALUES(5);
1.3 UPDATE
This command is used to update data in a table.
Example :-
(i) To update entire row in a table.
UPDATE T1 SET A=8;
(ii) To update particular row in a table
UPDATE T1 SET A=7 WHERE A=6;
1.4 DELETE
This command is used to remove one or more rows from a table. It can be rollback.
Example :-
(i) To delete all rows from a table.
DELETE FROM T1;
(ii) To delete one row from a table.
DELETE FROM T1 WHERE A=4;
These commands help you to manage the database structure. When you execute DDL
commands then auto commit takes place at the end of transaction. The lists of DDL Commands are.
2.1 CREATE
This command is used to create database and database objects.
3
Example :-
(i) To create database.
CREATE DATABASE DB1;
(ii) To create objects in the database
CREATE TABLE L1 (ID NUMBER, NAME VARCHAR (0-30));
2.2 DROP
This command is used to drop database and database objects.
Example :-
(i) To drop database.
DROP DATABASE DB1;
(ii) To drop objects in the database.
DROP TABLE L1;
2.3 ALTER
This allows you to rename an existing table and it can also be used to add, rename
modify, and drop a column from an existing table.
Example :-
(i) To add a column to a table
ALTER TABLE L1 ADD A VARCHAR2 (4) NOT NULL;
(ii) To rename a column from a table.
ALTER TABLE L1 RENAME A to B ;
(iii) To drop a column from a table
ALTER TABLE L1 MODIFY B NUMBER (5);
(iv) To modify a column from a table
ALTER TABLE L1 DROP COLUMN B;
2.4 RENAME
→ This command is used to rename object in the database.
→ To rename a database object.
Example :-
RENAME L60 TO T1;
ALTER TABLE L1 RENAME TO L2;
2.5 TRUNCATE
It deletes all data from the table. Actually truncate doesn’t remove data but de-allocates
whole Data pages and pointers to index.
Example :-
TRUNCATE TABLE L1;
It is much faster.
We can’t use condition if a statement contains Truncate.
A trigger doesn’t fire on truncate.
It cannot be rolled back.
4
2.6 COMMENTS
Example :-
(i) To create comment on column.
COMMENT ON COLUMN EMPL.FNAME IS 'MAIDEN NAME';
(ii) To alter comment on column.
COMMENT ON COLUMN EMPL.FNAME IS 'MAIDEN NAME IS FATHER NAME';
(iii)To drop comment on column.
COMMENT ON COLUMN EMPL.FNAME IS '';
3.1 COMMIT
Saves all pending changes permanent.
Example:- COMMIT;
3.2 SAVEPOINT
It is a marker. It is used to identify a point to which you can roll back later. If two save
point have same name then when you rollback will done until the last occurrence of the save point.
Example :- SAVEPOINT A;
3.3 ROLLBACK
Discard all pending changes.
Example :-
(i) To discard all pending changes
ROLLBACK;
(ii) To discard to particular save point
ROLLBACK TO B;
Example 1 :-
SET TRANSACTION READ ONLY NAME 'TORENTO';
Example 2 :-
SET TRANSACTION READ WRITE NAME 'TORENTO';
4.1 GRANT
This command is used to assign a privilege to the user. You can assign SELECT,
INSERT, UPDATE, DELETE, REFERENCES, ALTER and INDEX privilege to user.
5
Syntax :-
GRANT PRIVILEGE ON OBJECT TO USER;
Example :-
(i) To grant single privilege.
GRANT SELECT ON EMPLOYEES TO HR;
(ii) To grant multiple privilege.
GRANT SELECT, INSERT, DELETE ON EMPLOYEES TO HR;
(iii)To grant all privilege.
GRANT ALL ON EMPLOYEES TO HR;
(iv) To grant all privilege to public (all users).
GRANT ALL ON EMPLOYEES TO PUBLIC;
(v) You can give privilege on functions & procedures.
To grant privilege on functions or procedures.
GRANT EXECUTE ON OBJECT TO USER
4.2 REVOKE
This command is used to revoke the privileges assigned to the user.
Syntax :-
REVOKE PRIVILEGE ON OBJECT FROM USER;
Example :-
(i) To revoke single privilege.
REVOKE SELECT ON T1 FROM HR;
(ii) To revoke multiple privilege.
REVOKE SELECT, INSERT, DELETE ON T1 FROM HR;
(iii) To revoke all privilege.
REVOKE ALL ON T1 FROM HR
(iv) To revoke all privilege to public ( all users ).
REVOKE ALL ON EMPLOYEES FROM PUBLIC;
(v) To revoke privilege on functions or procedures.
Syntax :-
REVOKE EXECUTE ON OBJECT FROM USER;
QUESTIONS
COMMIT ROLLBACK
(i) COMMIT validates the modifications made by (i) ROLLBACK erases the modifications made by
the current transaction. the current transaction.
(ii) After execution of COMMIT statement, the (ii) Once ROLLBACK is executed database
transaction can not be ROLLBACK. reaches its previous state, I.e. before the execution
of the first statement of the transaction.
(iii) COMMIT occurs when the transaction gets (iii) ROLLBACK occurs when the transaction is
executed successfully. aborted in middle of the execution.
(iv) Syntax :- COMMIT; (iv) Syntax :- ROLLBACK;
6
2. Difference between Delete and Truncate?
DELETE TRUNCATE
(i) We can Rollback after delete. (i) We can't Rollback after performing
Truncate.
Example:-
Example:-
BEGIN TRAN
DELETE FROM tranTest BEGIN TRAN
SELECT * FROM tranTest TRUNCATE TABLE tranTest
ROLLBACK SELECT * FROM tranTest
SELECT * FROM tranTest ROLLBACK
SELECT * FROM tranTest
(ii) Delete does not reset identity of table. (ii). Truncate reset identity of table.
(iii) It locks the table row (Row Level Lock). (iii). It locks the entire table (Table Level Lock)
(iv) Its DML(Data Manipulation Language) (iv) Its DDL(Data Definition Language)
command. command.
(v) We can use WHERE to filter data to delete. (v) We can't use WHERE clause with it.
(vi) Trigger is fired. (vi) Trigger is not fired while truncate.
(vii) Syntax : (vii) Syntax :
7
PSEUDO COLUMNS
_______________________________________________________________________
PSEUDO COLUMNS:-
1. SYSDATE
This command is used to display current system date in DD-MOM-YY
Example :- SELECT SYSDATE FROM DUAL;
2. SYSTIMESTAMP
This command is used to display current system date & time.
Example :- SELECT SYSTIMESTAMP FROM DUAL;
3. USER
This command shows you the current user you have logged in.
Example :- SELECT USER FROM DUAL;
4. UID
This command shows you the current user id you have logged in.
Example :- SELECT UID FROM DUAL;
5. ROWNUM
This command is used to generate row number starting from 1 and will not be stored in
the database.
Example :- SELECT ROWNUM FROM EMPLOYEES;
6. ROWID
ROWID is unique and generated when the row is inserted.
It has 18 digit characters (contains mixed or character & numbers). This command is
user to display row id.
Example :- SELECT ROWID FROM EMPLOYEES;
7. NEXTVAL
This command is used to show next available value from sequence which can be used.
Example :- SELECT SEQ10.NEXTVAL FROM DUAL;
8. CURRVAL
This command shows the current value from the sequence that has been already used.
Example :- SELECT SEQ10.CURRVAL FROM DUAL;
9. LEVEL
Example :-
SELECT EMPLOYEE_ID, FIRST_NAME, MANAGER_ID, LEVEL AS STAGE
FROM EMPLOYEES START WITH MANAGER_ID IS NULL CONNECT BY
PRIOR EMPLOYEE_ID=MANAGER_ID ORDER BY STAGE ASC;
8
QUESTIONS
ROWID ROWNUM
(i) ROWID is nothing but Physical memory (i) ROWNUM is nothing but the sequence which
allocation. is allocated to that data retrieval bunch.
(ii) ROWID is permanent to that row which (ii) ROWNUM is temporarily allocated sequence
identifies the address of that row. to the rows.
(iii) ROWID is 16 digit Hexadecimal number (iii) ROWNUM is numeric sequence number
which is uniquely identifies the rows. allocated to that row temporarily.
(iv) ROWID returns PHYSICAL ADDRESS of (iv) ROWNUM returns the sequence number to
that row. that row.
(v) ROWID is automatically generated unique id (v) ROWNUM is an dynamic value automatically
of a row and it is generated at the time of insertion retrieved along with select statement output.
of row.
(vi) ROWID is the fastest means of accessing (vi) ROWNUM is not related to access of data.
data.
9
OPERATORS
_______________________________________________________________________
OPERATORS:-
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Lesser than or equal to
< > (or)! = Not equal to
These operators can hold only single values after this conditional
symbol.
Example 1 :-
Example 2 :-
Example 3 :-
Example 4 :-
Example 5 :-
Example 6 :-
Example 7 :-
10
2. LOGICAL OPERATOR
2.1 AND
This command indicates that both the condition must satisfy.
Example :-
2.2 OR
This command indicates that either one of the condition must satisfy.
Example :-
3. RELATIONAL OPERATORS
IN NOT IN LIKE
NOT LIKE BETWEEN NOT BETWEEN
IS NULL IS NOT NULL ANY, ALL
Example 1 :-
Example 2 :-
11
Example 1 :-
Example 2 :-
Example 1 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY BETWEEN 2400 AND 5000 and
SALARY NOT BETWEEN 24000 AND 50000
Example 2 :-
SELECT HIRE_DATE FROM EMPLOYEES WHERE HIRE_DATE BETWEEN '21-SEP-89' AND '21-MAY-91';
Example 3 :-
SELECT HIRE_DATE FROM EMPLOYEES WHERE HIRE_DATE NOT BETWEEN '21-SEP-89' AND '21-MAY-
91';
Example 1 :-
Example 2 :-
3.5 ANY
>ANY (17000, 14000, 13500) || It retrieves salary greater than least number.
<ANY (17000, 14000, 13500) || It retrieves salary lesser than greatest number.
<> (or) != ANY (17000, 14000, 13500) || It retrieves salary lesser than , greater than and equal to value.
>=ANY (17000, 14000, 13500) || It retrieves the salary greater than or equal to the least value.
<=ANY (17000, 14000, 13500) || It retrieves the salary lesser than or equal to the greatest value.
=ANY (17000, 14000, 13500) || It retrieves the salary equal to the value.
12
Example 1 :-
Example 2 :-
Example 3 :-
Example 4 :-
Example 5 :-
Example 6 :-
Example 7 :-
3.6 ALL
>ALL (17000, 14000, 13500) || It retrieves salary greater then greatest number.
<ALL (17000, 14000, 13500) || It retrieves salary lesser then least number.
<>ALL (17000, 14000, 13500) || It retrieves salary lesser then least number in parenthesis and salary
greater then greatest number present in parenthesis.
>=ALL (17000, 14000, 13500) || It retrieves salary greater than or equal to greatest number.
<=ALL (17000, 14000, 13500) || It retrieves salary lesser than or equal to least number.
Example 1 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY >ALL (17000, 14000, 13500);
Example 2 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY <ALL (17000, 14000, 13500);
13
Example 3 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY <>ALL (17000, 14000, 13500);
Example 4 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY ! = ALL (17000, 14000, 13500);
Example 5 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY >=ALL (17000, 14000, 13500);
Example 6 :-
SELECT SALARY FROM EMPLOYEES WHERE SALARY <=ALL (17000, 14000, 13500);
14
SET OPERATORS
______________________________________________________________
RULES :-
→ It works from top to bottom.
→ Both column name and data type should be same.
→ Number of columns in both the query must be same.
TYPES :-
→ There are four set operator in SQL.
→ They are UNION, UNION ALL, INTERSECT and MINUS.
Example :-
Let us take two tables T1 and T2.
T1 T2
1 1
2 2
3 3
4 5
1. UNION
Displays data from both tables eliminating duplicate rows.
Example :-
SELECT A FROM T1 UNION SELECT A FROM T2;
2. UNION ALL
Displays data from both tables without eliminating duplicate rows and it is faster.
Example :-
SELECT A FROM T1 UNION ALL SELECT A FROM T2;
3. INTERSECT
Displays data which is commonly present both the table.
Example :-
SELECT A FROM T1 INTERSECT SELECT A FROM T2;
4. MINUS
Displays data from Table 1 which is not present in Table 2.
Example :-
SELECT A FROM T1 MINUS SELECT A FROM T2;
15
JOINS
_______________________________________________________________________
JOINS:-
Selecting data from two or more table is called joins.
When we use alias it is much faster.
n-1 condition
TYPES OF JOINS :-
1. EQUI JOIN
To select matched rows from two or more table is called equi join.
It can be called as inner join or natural join (natural join find common columns from
both the table).
Example :-
Option 1 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S, COURSE C
WHERE S.CID = C.CID;
Option 2 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S INNER JOIN COURSE C
ON S.CID = C.CID;
Option 3 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S JOIN COURSE C
ON S.CID = C.CID;
Option 4 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S NATURAL JOIN COURSE C;
2. OUTER JOIN
Option1 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S, COURSE C
WHERE S.CID = C.CID (+);
Option2 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S LEFT OUTER JOIN COURSE C
ON S.CID = C.CID;
16
2.2 RIGHT OUTER JOIN
To get matched record from both the table and unmatched record from right table.
Example :-
Option1 :-
SELECT S.SNAME, C.CNAME FROM STUDENT S, COURSE C
WHERE S.CID (+) = C.CID;
Option2 :-
Example :-
3. CROSS JOIN
It is a Cartesian product.
Number of rows in first table is joined with number of rows in the second table.
Cartesian product is formed when user ignores ‘WHERE’ clause.
Cross join is used by developers to perform performance testing.
Example :-
4. SELF JOIN
Joining a table with itself is called self-join.
Example :-
5. SEMI JOIN
→ It returns row from first table when one or more row matched found in second table. →
→ Difference between semi-join and inner join is that row in first table will be returned only
once even if the second table contains two matches from a row in the first table, only one copy of the
row will be returned.
→ Semi-joins are written by using ‘IN’ & ‘EXISTS’ constructs.
17
Example :-
6. ANTI JOIN
→ It returns row from first table when no matches found in second table.
→ Anti-joins are written by using ‘NOT IN’ & ‘NOT EXISTS’ constructs.
Example :-
18
AGGREGATE FUNCTION
___________________________________________________________________________________
1. AVG :-
This command is used to retrieve average.
Example : -
SELECT AVG (SALARY) FROM EMPLOYEES;
2. COUNT :-
This command is used to display the count.
Example :-
SELECT COUNT (SALARY) FROM EMPLOYEES;
3. MAX :-
This command is used to retrieve maximum number or salary.
Example :-
SELECT MAX (SALARY) FROM EMPLOYEES;
4. MIN :-
This command is used to retrieve minimum number or salary.
Example :-
SELECT MIN (SALARY) FROM EMPLOYEES;
5. SUM :-
This command to retrieve by summing up all the rows in particular column. It works
only if the column data type is number.
Example :-
SELECT SUM (SALARY) FROM EMPLOYEES;
Example :-
SELECT DEPARTMENT_ID, SUM (SALARY) AS TOTAL FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20, 30, 40) GROUP BY CUBE (DEPARTMENT_ID);
19
Output:-
- 58400
10 4400
20 19000
30 24900
40 6500
Example 2:-
SELECT DEPARTMENT_ID, SUM (SALARY) AS TOTAL FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20, 30, 40) GROUP BY ROLLUP (DEPARTMENT_ID);
Output:-
10 4400
20 19000
30 24900
40 6500
- 58400
RULES :-
CLAUSES:-
1. WHERE
This clause is used to restrict number of rows to return by a condition, for joining two or
more tables, restricts views and materialized views.
2. GROUP BY
This clause is used to group the results by one or more columns used in group by. It is
most often used when there is aggregate or group functions are used in query. The column you are
specifying in group by clause must be in select list same thing applies to sub query where column name
should be present in the current scope of select list and not in outer query. You can use analytical
function ‘ROLLUP’ and ‘CUBE’ in group by clause.
Example 1:-
SELECT FIRST_NAME, COUNT (*) AS NUM FROM EMPLOYEES GROUP BY FIRST_NAME;
Example 2:-
SELECT DEPARTMENT_ID, SUM (SALARY) AS TOTAL FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20, 30, 40) GROUP BY CUBE (DEPARTMENT_ID);
20
Example 3:-
3. HAVING
4. ORDER BY
This clause is used to specify in which order the result should be displayed either
ascending (this is default) or descending order. You can use one or more columns, functions and
column position (which should be greater than 0) in order by clause. Whenever you use this clause then
‘SORT’ operation takes place. Null comes last in ascending order and first in descending order.
RULES :-
→ If you use distinct or group by clause in select statement, then order by column must be in
select list.
→ If you are using sub-query, order by must be placed at the end of sub query.
→ Order by clause prevents a SELECT statement from being an updatable cursor.
Example 1:-
SELECT COMMISSION_PCT FROM EMPLOYEES ORDER BY COMMISSION_PCT, SALARY;
Example 2:-
SELECT COMMISSION_PCT+SALARY FROM EMPLOYEES ORDER BY
COMMISSION_PCT+SALARY;
Example 3:-
SELECT COMMISSION_PCT FROM EMPLOYEES ORDER BY SALARY DESC;
SELECT DISTINCT (COMMISSION_PCT) FROM EMPLOYEES ORDER BY SALARY DESC;
Example 4:-
SELECT FIRST_NAME, COUNT (*) FROM EMPLOYEES GROUP BY FIRST_NAME ORDER BY
COUNT (*);
Example 5:-
SELECT COMMISSION_PCT FROM EMPLOYEES ORDER BY 1;
Example 6:-
SELECT SALARY FROM EMPLOYEES ORDER BY F2 (SALARY);
5. WITH
It is processed as temporary table and it is used to simplify complex queries.
Example 1 :-
WITH DEPT_COUNT AS (SELECT DEPARTMENT_ID, COUNT (*) AS DEPT_COUNT FROM
EMPLOYEES GROUP BY DEPARTMENT_ID) SELECT E.FIRST_NAME, D.DEPT_COUNT
FROM EMPLOYEES E, DEPT_COUNT D WHERE
E.DEPARTMENT_ID = D.DEPARTMENT_ID
21
QUESTIONS
1. Print the records who are all getting more than average salary?
COUNT(COLUMN_NAME) COUNT(*)
(i) Both are aggregate function or group function. (i) Both are aggregate function or group function.
(ii) Counts the entries in a column - ignoring null (ii) Counts the rows in table - including null
values. values.
GROUP BY ORDER BY
(i) Group By is used to form the Group of the set (i) Order By is used to arrange the data obtained
of the tuples. as a result of a query in Sorted form.
(ii) Attribute under Aggregate function can not be (ii) Attribute under aggregate can be in Order By
in Group By clause. Clause.
(iii) Done on the ground of similarity among (iii) Done on the ground of ascending order and
attribute values. descending order.
WHERE HAVING
(i) Implemented in row operations. (i) Implemented in column operations.
(ii) Applied to Single row. (ii) Applied to summarized row or groups.
(iii) It only fetches the particular data from (iii) At first, complete data is fetched then
particular rows according to the condition. separated according to the condition.
(iv) Cannot appear in WHERE clause. (iv) Can appear in HAVING clause.
(v) SELECT and other statements such as (v) Can't be used without a SELECT statement.
UPDATE, DELETE or either one of them.
(vi) Act as Pre-filter. (vi) Act as Post-filter.
(vii) GROUP BY comes after WHERE. (vii) GROUP BY comes before HAVING.
22
ANALYTICAL FUNCTIONS
___________________________________________________________________________________
ANALYTICAL FUNCTIONS:-
1. RANK()
It provides rank to record based on some column value. In case if a tie of 2 record occurs
at position N then the two record positions will be N and gives N+2 to the next record.
Example :-
SELECT EMPLOYEE_ID, SALARY, RANK () OVER (ORDER BY SALARY
DESC) FROM EMPLOYEES;
2. DENSE_RANK ()
It provides rank to record based on some column value. In case if a tie of 2 record occurs
at position N then the two record positions will be N and gives N+1 to the next record
Example :-
SELECT EMPLOYEE_ID, SALARY, DENSE_RANK () OVER (ORDER BY
SALARY DESC) FROM EMPLOYEES;
3. ROW_NUMBER
It gives a running serial number to a record.
Example :-
SELECT EMPLOYEE_ID, SALARY, ROW_NUMBER () OVER (ORDER BY
SALARY DESC) FROM EMPLOYEES;
4. LEAD
This command computes an expression on next row is return the value to the current
row.
Example :-
SELECT FIRST_NAME, SALARY, LEAD (SALARY, 1, 0) OVER (ORDER
BY SALARY DESC) FROM EMPLOYEES;
5. LAG
This command computes an expression on previous row is return the value to the current
row.
Example :-
SELECT FIRST_NAME, SALARY, LAG (SALARY, 1, 0) OVER (ORDER BY
SALARY DESC) FROM EMPLOYEES;
6. FIRST_VALUE
This command picks the first record from the partition after doing order by and first
record are returned.
23
Example :-
SELECT EMPLOYEE_ID, HIRE_DATE, DEPT_ID, FIRST_VALUE (HIRE_DATE)
OVER (PARTITION BY DEPARTMENT_ID ORDER BY HIRE_DATE) FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (10, 20, 30, 40, 50);
7. LAST_VALUE
This command picks the last record from the partition after doing the order by and last
record are returned.
Example :-
SELECT EMPLOYEE_ID, HIRE_DATE, LAST_VALUE (HIRE_DATE) OVER ()
FROM EMPLOYEES WHERE DEPARTMENT_ID IN (10, 20, 30, 40, 50) ORDER BY HIRE_DATE;
USING PARTITION BY :-
Similar to group by function.
Example :-
SELECT EMPLOYEE_ID, SALARY, RANK () OVER (PARTITIOB BY DEPARTMENT_ID
ORDER BY SALARY DESC) FROM EMPLOYEES;
QUESTIONS
1.Fetch the 1st rank ?
WITH CSK AS
( SELECT EMPLOYEE_ID, SALARY, RANK () OVER ( ORDER BY SALARY DESC) RANKER
FROM EMPLOYEES)
SELECT * FROM CSK WHERE RANKER = 1;
WITH CSK AS
( SELECT EMPLOYEE_ID, SALARY, DENSE_RANK () OVER ( ORDER BY SALARY DESC)
RANKER FROM EMPLOYEES)
SELECT * FROM CSK WHERE RANKER IN (1,2,3);
WITH CSK AS
( SELECT DEPARTMENT_ID , SALARY, RANK () OVER ( PARTITIOB BY DEPARTMENT_ID
ORDER BY SALARY DESC) RANKER FROM EMPLOYEES)
SELECT * FROM CSK WHERE RANKER = 1;
WITH CSK AS
( SELECT DEPARTMENT_ID , SALARY, RANK () OVER ( PARTITIOB BY DEPARTMENT_ID ORDER
BY SALARY DESC) RANKER FROM EMPLOYEES)
SELECT * FROM CSK WHERE RANKER IN (1,2,3);
24
5. Difference between RANK and DENSE_RANK?
RANK DENSE_RANK
(i) Both are analytical function. (i) Both are analytical function.
(ii) If there is any repeated rank it will skip the (ii) If there is any repeated rank it will not skip the
next rank. next rank.
(iii) Example :- (iii) Example :-
Rank Dense_Rank
1 1
1 1
3 2
1 is repeated 2 times so It will skip the 2nd rank It will not skip any values, It will print in the same
and it will print 3 as next rank. order.
LEAD LAG
(i) Both are analytical function. (i) Both are analytical function.
(ii) It will fetch the next value of current row. (ii) It will fetch the previous value of current row.
(iii) Example :- (iii) Example :-
Lead Lag
10000 , 20000 10000 , null
20000 , 30000 20000 , 10000
30000 , null 30000 , 20000
AGGREGATE ANALYTICAL
(i) Aggregate function is Single row output. (i) Analytical function is Multi rows output.
(ii) Here we use group by keyword for grouping. (ii) Here we use partition by keyword for
grouping.
(iii) It will return single value. (iii) It will return more than one value.
(iv) Only one column is specified by using group (iv)All columns is specified by using partition
clause. clause.
(v) Row collapse and number of input as less than (v) No row collapse and number of input is equal
in the number of output. to the number of output.
(vi) Faster than analytical function. (vi) slower comparing aggregate function.
(vii) Here we use Sum, Avg, Count, Min, Max (vii) Here we use Rank, Dense_rank, Lead, Lag,
Row_number, First_value and Last_value.
25
NULL VALUE LOGIC
_______________________________________________________________________
NULL HANDLING FUNCTIONS:-
1. NVL
It accepts exactly two arguments. If the first argument is null then display the second
argument else display the first argument.
Example :-
SELECT NVL (COMMISSION_PCT, 0) FROM EMPLOYEES;
2. NVL2
It accepts exactly three arguments. If the first argument is null then display the third
argument else display the second argument.
Example :-
SELECT NVL2 (COMMISSION_PCT, 2, 1) FROM EMPLOYEES;
3. NULLIF
It accepts exactly two arguments. Display null if both the arguments are same else
display the first argument.
Example :-
SELECT NULLIF (SALARY, 24000) FROM EMPLOYEES;
4. COALESCE
It can contain two or more number of arguments and it returns the first not null from the
arguments list.
Example :-
SELECT COALESCE (COMMISSION_PCT, SALARY) FROM EMPLOYEES;
QUESTIONS
26
SEQUENCE
_______________________________________________________________________
SEQUENCE:-
It automatically generates unique number.
It is a schema object.
It replaces the application code.
It is mainly used for generating primary key column values.
Commit, save point or rollback doesn't work.
Example :-
1. To create sequence :-
Create SEQUENCE seq
START with 10
INCREMENT by 2
MINVALUE 1
MAXVALUE 22;
2. To alter sequence :-
3. To drop sequence
Drop SEQUENCE seq;
1. INCREMENT BY
It specifies the interval between sequence numbers. The value can be either positive
number or negative number but not zero. If the value is positive the sequence ascends and if the value
is negative than sequence descends. If you omit this clause then the default increment value will be 1.
2. MAXVALUE
It is used to specify the maximum value that a sequence can generate. This
MAXVALUE must be greater than or equal to START WITH and must be greater than MINVALUE.
3. START WITH
It specifies first sequence number to be generated. It can be ascending or descending.
4. MINVALUE
It specifies the minimum value of the sequence. This MINVALUE must be lesser than or
equal to START WITH and must be lesser than MINVALUE.
27
5. NOMAXVALUE
It specifies a maximum value of 10 powers 27 for ascending order or -1 for descending
order.
6. NOMINVALUE
It specifies a minimum value of 1 for ascending order and -10 powers 26 for descending
order.
7. CYCLE
It specifies that when the sequence continues to generate when it is reached maximum or
minimum. Once if the sequences value reaches maximum then it generates the minimum value and if
the sequence value reaches minimum then it generates the maximum value.
8. NOCYCLE
It specifies that when the sequence cannot generate more valued if it is reached maximum or minimum
value. This is the default one.
9. CACHE
It indicates that the value of the sequence is pre-allocated and keeps in memory for faster
access. The integer value can have 28 or fewer digit. The minimum value of the parameter is 2.
10. NOCACHE
It indicates that value of sequence is not pre-allocated. If you leave CACHE and
NOCACHE then the database allocated for 20 sequence numbers by default.
11. ORDER
To sequence number are generated in the order of request. This clause is very useful
when you are using sequence numbers as timestamps.
12. NO ORDER
To specify sequence number are not generated in order of request. This is default.
Example 1:-
28
SYNONYMS
_______________________________________________________________________
SYNONYMS:-
A synonym is an alternative name for object such as tables, view, sequences, stored
procedures and other database objects.
You can create synonym for synonym. It is object of a database.
To view list of synonyms and which object does it affect
DICTIONARY TABLE :-
TYPES :-
1. Private Synonym.
2. Public Synonym.
1. Private Synonym
This synonym is accessed within the schema. The default one is private.
Example :-
1.1 To create private synonym
Syntax :-
CREATE SYNONYM STUDENT1 FOR STUDENT;
2. Public Synonym
This synonym is accessed across the schema.
Example :-
1.1 To create public synonym
Syntax :-
CREATE PUBLIC SYNONYM STUDENT1 FOR STUDENT;
29
DUAL – DUMMY TABLE
_______________________________________________________________________
DUAL:-
Dual is a dummy table and it is a data dictionary table.
Example :- 1
Example :- 2
Example :- 3
NULL:-
Null is a unassigned value or unknown value or undefined value.
Null is not equal to zero.
Null is not equal to space.
Null is not equal to underscore.
Null is not equal to Null.
Null is not equal to ‘’
Null is always greater than any number because in ascending order Null comes last and in
descending order it comes first or it is maximum in ascending order & minimum in descending order.
Example :-
1. To insert null values into table :-
INSERT ALL
INTO T99 VALUES ('')
INTO T99 VALUES (NULL);
30
SQL FUNCTIONS
_______________________________________________________________________
SQL FUNCTIONS:-
1. COMPARISON FUNCTIONS
1.1 GREATEST
This command returns the greatest value in the arguments list. This command can
contain one or more arguments.
Example :-
1.2 LEAST
This command returns the least value in the arguments list. This command can contain
one or more arguments.
Example :-
2. NUMBER FUNCTIONS
2.1 ROUND
This command is used to round the decimal values.
If the decimal value is greater than or equal to .5 then it is rounded to next value else
rounded to current value.
Example :-
Output :-
2.2 MOD
Example :-
2.3 TRUNC
Example :-
SELECT TRUNC (157.7), TRUNC (157.5), TRUNC (157.4) FROM DUAL;
Output :-
32
DATE FUNCTION
_______________________________________________________________________
DATE FUNCTIONS:-
1. MONTHS_BETWEEN
This command accepts exactly two arguments and it is used to show difference in
months between two dates. If argument1 is greater than argument 2 then output will be in positive
integer else output will be in negative integer.
Example :-
2. ADD_MONTHS
This command accepts exactly two arguments and it is used for adding months to current
date.
Example :-
SELECT ADD_MONTHS (SYSDATE,12), ADD_MONTHS(SYSDATE,-12) FROM
DUAL;
3. NEXT_DAY
This command accepts exactly two arguments and it is use to show on which date the
next day comes.
Example :-
SELECT NEXT_DAY (SYSDATE,'FRIDAY') FROM DUAL;
4. LAST_DAY
This command accepts exactly two arguments and it is used to show last day of a month.
Example :-
SELECT LAST_DAY (SYSDATE) FROM DUAL;
5. SYSDATE
This command used to find the current date.
Example :-
SELECT SYSDATE FROM DUAL;
6. SYSTIMESTAMP
This command used to find the current date with respective time zone.
Example :-
SELECT SYSTIMESTAMP FROM DUAL;
33
7. TO_TIMESTAMP
The TO_TIMESTAMP function converts a string to a timestamp.
PARAMETER EXPLANATION
YYYY 4-digit year
MM Month (01-12; JAN = 01)
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to
length of 9 characters.
DD Day of month (1-31).
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
QUESTIONS
34
6. First day of Next Year?
8. Find the last day Saturday of each month for a given year?
9. Find the last day Saturday of every month for a given year?
35
CONSTRAINTS
_______________________________________________________________________
CONSTRAINTS:-
1.2 To add a primary key using ‘create’ command without using constraint name :-
36
1.6 To disable a primary key :-
Example :-
2.1 To add unique key using ‘create’ command with constraint name :-
2.2 To add unique key using ‘create’ command without constraint name :-
37
3.1 To create foreign key using ‘create’ command from primary key :-
3.2 To create foreign key using ‘create’ command from unique key :-
NOTES:-
Foreign key always replace the primary key, if you want to delete the parent key directly
oracle do will not allow to delete, throw error like ' CHILD RECORD FOUND'.
While trying to insert child record without parent record means also it will throw error
like 'PARENT RECORD NOT FOUND'.
While using 'ON DELETE CASCADE' it will delete parent record and corresponding
child records also.
While using 'ON DELETE SET NULL' it will delete parent record and corresponding
child record it will set NULL.
38
4.2 To add not null using ‘alter’ command :-
5. CHECK (C)
It is Domain Integrity.
It should satisfy a condition. It is
5.1 To add check constraint using ‘create’ command with constraint name :-
5.2 To add check constraint using ‘create’ command without constraint name :-
CHECK (WLOC='CHENNAI');
X1 CHECK (WMDES IN ('CHENNAI','HYDREBAD'))
To see list of columns names, data type, table name…etc in entire database
SELECT * FROM USER_TAB_COLUMNS;
To see list of constraints names, constraint types, table name…etc in entire database
SELECT * FROM ALL_CONSTRAINTS;
39
DATA DICTIONARY TABLES
_______________________________________________________________________
DATA DICTIONARY TABLES:-
1. DICTIONARY :-
It is used to find list of data dictionary tables available in oracle.
2. USER_OBJECTS :-
It contains list of objects present in the database (i.e., table, index, view, function, type,
trigger, package, package body, lob, procedure, function, materialized view, sequence…etc.)
3. USER_TABLES :-
It contains list of tables and global temporary tables present in the database.
4. USER_VIEWS :-
It contains list of views present in the database.
5. USER_ERRORS :-
It contains the error occurred during creating object like procedure, package body,
function... etc.
6. USER_TAB_COLUMNS :-
It contains list of columns present in the entire table in the database.
7. USER_CONSTRAINTS / USER_CONS_COLUMNS :-
It contains the list of constraints which was created by all users in the database.
8. USER_INDEXES :-
It contains the list of index created by all users in the database.
9. USER_TRIGGERS :-
It contains the list of triggers present in the database.
10. USER_SOURCE :-
It contains the entire script on object like procedure, package, package body,
function, trigger and type.
11.USER_MVIEWS :-
It contains the list of materialized view in the database.
12. USER_SEQUENCES :-
It contains the list of sequence present in the database.
13. ALL_USERS :-
It contains list of users who can login into database.
40
GLOBAL TEMPORARY TABLE
_______________________________________________________________________
GLOBAL TEMPOARY TABLE:-
Data in temporary table is stored in temp segments in the temp table space.
Data in temporary tables is automatically deleted at the end of the database session, even
if it ends abnormally.
Views can be created against temporary tables and combinations of temporary and
permanent tables.
Temporary tables can have triggers associated with them.
Indexes can be created on temporary tables. The content of the index and the scope of
the index is the same as the database session.
SYNTAX :-
TYPES :-
→ ON COMMIT PRESERVE ROWS
This indicates that data should be present till the session ends.
→ ON COMMIT DELETE ROWS
This indicates that data should be deleted at the end of this transaction.
It is the default one.
41
PARSING :-
Oracle needs to execute some task before executing SQL query (which is received from user).
This process is called Parsing.
1. SYNTACTIC CHECK :-
→ Oracle parses the syntax to check for misspelled SQL keywords.
2. SEMANTIC CHECK :-
→ Oracle verifies all table names & column name from the data dictionary table and
check to see if user is authorized to view data.
3. OPTIMIZATION :-
→ Oracle creates an execution plan on schema statistics.
→ If the entire above task performs then it is called hard parsing.
→ If only syntactic check & semantic check perform then it is called soft parsing.
→ Soft parsing occurs when you use ‘cursors’.
QUESTIONS
42
STRING FUNCTION
_______________________________________________________________________
1.1 CONCAT
This command accepts exactly two arguments and displays the result by concatenating
the two arguments.
Example :-
SELECT CONCAT (FIRST_NAME, LAST_NAME) FROM EMPLOYEES;
1.2 LENGTH
This command can accept only one argument and displays the length of the string.
Example :-
SELECT LENGTH (FIRST_NAME) FROM EMPLOYEES;
1.3 REPLACE
This command can accept exactly two or three arguments and helps to replaces the
character.
Syntax :-
REPLACE (FIRST_NAME, 'e', 'x') – Here ‘e’ is replaced with ‘x’.
REPLACE (FIRST_NAME, 'e') – Here ‘e’ is removed.
Example :-
SELECT FIRST_NAME, REPLACE (FIRST_NAME, 'e', 'x') FROM EMPLOYEES;
SELECT FIRST_NAME, REPLACE (FIRST_NAME, 'e') FROM EMPLOYEES;
1.4 REVERSE
This command accepts exactly one argument and display the string in reverse order.
Example :-
SELECT REVERSE (SNAME) FROM STUDENT;
1.5 TRANSALATE
This command replaces sequence of string with another set of character.
For example it replaces 1st character from string to replace with 1st character
from replacement string then 2nd character from string to replace with 2nd
character from replacement string so on.
Example :-
SELECT TRANSLATE ('1ABC23','123','456') FROM DUAL;
43
1.6 LPAD
This command can accept exactly two or three arguments and
LPAD (SNAME,10,'@') – here if the string less than 10 characters then remaining
character is filled by ‘@’ in left hand side and displays exact 10 characters.
LPAD (SNAME, 5) – Here it display the string only up to 5 characters.
Example :-
SELECT LPAD (SNAME, 10,'@') FROM STUDENT;
SELECT LPAD (SNAME, 5) FROM STUDENT;
1.7 RPAD
This command can accept exactly two or three arguments and
RPAD (SNAME,10,'@') – here if the string less than 10 characters then remaining
character is filled by ‘@’ in right hand side and displays exact 10 characters.
RPAD (SNAME, 5) – Here it display the string only up to 5 characters.
Example :-
SELECT RPAD (SNAME, 10,'@') FROM STUDENT;
SELECT RPAD (SNAME, 5) FROM STUDENT;
1.8 LTRIM
This command is used to remove special character or character on left hand side.
Example :-
SELECT LTRIM ('****HELLO**WORLD****','*') FROM DUAL;
1.9 RTRIM
This command is used to remove special character or character on right hand side.
Example :-
SELECT RTRIM ('****HELLO**WORLD****','*') FROM DUAL;
1.10 TRIM
This command is used to remove special character or character on both L&R hand side.
Example :-
SELECT TRIM ('*' FROM '****HELLO**WORLD****') FROM DUAL;
1.11 SUBSTR
This command is used to get the string of particular length from particular starting position.
Syntax :-
SUBSTR (SNAME, 1, 3) – It is used to print 3 character starting from position 1.
SUBSTR (SNAME,-3) – it is used to print 3 character starting from last position.
Example :-
SELECT SUBSTR (SNAME, 1, 3) FROM STUDENT;
SELECT SUBSTR (SNAME,-3) FROM STUDENT;
44
1.12 INSTR
This command can accept two to four arguments. It is used find the position of
occurrence of a specified character.
Syntax :-
INSTR (STRING1, STRING 2, STARTING POSITION, Nth APPERANCE)
Example :-
SELECT INSTR ('TECH ON THE NET','E') FROM DUAL;
SELECT INSTR ('TECH ON THE NET','E', 1, 2) FROM DUAL;
1.13 ASCII
This command returns ASCII values for specified character. If you declare a word then it
returns the ASCII values for 1st character.
Example :-
SELECT ASCII ('C') FROM DUAL;
2.1 UPPER
This command can accept only one argument and displays in upper case format.
Example :-
SELECT UPPER (FIRST_NAME) FROM EMPLOYEES;
2.2 LOWER
This command can accept only one argument and displays in lower case format.
Example :-
SELECT LOWER (FIRST_NAME) FROM EMPLOYEES;
2.3 INITCAP
This command can accept one argument and display first character in capital.
Example :-
SELECT INITCAP (SNAME) FROM STUDENT;
45
QUESTIONS
REPLACE TRANSALATE
(i) Replaces entire string at a time. (i) Replaces character one-to-one basis.
(ii) Returns string if no match found. (ii) Returns null if no match found.
(iii) Syntax :- Replace ('Oracle','Ora',123 ) (iii) Syntax:- Translate ('Oracle','Oae',123 )
INSTR SUBSTR
(i) The INSTR function provides character (i) The SUBSTR function returns a specific
position in a pattern of string. portion of a string.
(ii) SUBSTR is used to extract a set of characters (ii) INSTR is used to find the position of any
from a string by specificing the character starting particular character in a word which returns
position and end position and length of characters numeric value.
to be fetched.
(iii) INSTR returns numeric. (iii) SUBSTR returns string.
(iv) Syntax :- INSTR('HELLO','E') (iv) Syntax :- SUBSTR('HELLO',2,3)
46
VIEWS
_______________________________________________________________________
VIEWS:-
View is virtual table.
It logically represents a subset of data from one or more table.
We can create a view from another view
We will get the updated data from view.
Only queries save in data dictionary table.
ADVANTAGES :-
To make more complex query look simple.
To restrict data access.
TYPES
1. SIMPLE VIEW
There is only one table.
Base table is must.
If there are any changes made in either view or table it will affect both.
DML operations can be done in simple view.
Syntax :-
CREATE VIEW V1 AS SELECT * FROM EMPLOYEES;
2. COMPLEX VIEW
When the select has a group by clause, having clause, joins, aggregate function,
analytical function.. etc it called complex view.
DML operations cannot be done in complex view.
Can't able do DML operations in complex view until go for INSTEAD OF TRIGGER.
Syntax :-
CREATE VIEW V1 AS SELECT S.SNAME, C.CNAME, F.FNAME FROM
COURSE C, STUDENT S, FACULTY F WHERE S.CID=C.CID AND C.CID=F.CID;
Drop View :-
DROP VIEW V1;
View Table :-
SELECT * FROM USER_VIEWS;
47
3. FORCE VIEW
We can create a view with a dummy base table which does not exist in a database.
This view will be having errors.
Mainly using for application code test.
Example :-
CREATE OR REPLACE FORCE VIEW V1 AS
SELECT * FROM GREENS;
1. READ ONLY
This can be used when you don’t want to manipulate data in view.
Example :-
CREATE OR REPLACE VIEW V1 AS
SELECT A FROM T1 WHERE A=1 WITH READ ONLY;
2. UPDATABLE VIEW
Here you can insert, update & delete records but this action only be performed on base
table or a table from which the view is created.
Example :-
CREATE OR REPLACE VIEW V1 AS
SELECT SNAME FROM STUDENT WHERE CID = 10;
3. CHECK OPTION
This is used when you want to insert data in views by checking condition from where
clause.
If it true then insert operation takes place.
Example :-
CREATE OR REPLACE VIEW V1 AS
SELECT A FROM T1 WHERE A IN (1,3) WITH CHECK OPTION;
RULES : -
If you are using pseudo column like ROWNUM, ROWID and LEVEL then you must
use alias.
If you are using group functions then you must use alias.
For updatable view :
You can’t use ORDER BY and GROUP BY.
You should not use analytical and aggregate function.
Sub query in SELECT list
48
MATERIALIZED VIEWS
_______________________________________________________________________
MATERIALIZED VIEWS:-
Materialized view is a database objects that store the result of a query.
It is a schema object.
It can be called as snapshots.
Materialized view occupies space in database.
It will save the result set of the query in data dictionary table.
We will not get updated data from Materialized view until we go for REFRESH
ADVANTAGES :
You can create materialized view on another materialized view. So that it reduces more
network traffic.
It can be either read only, writable or updatable.
You can create materialized view for join queries and quires that contain aggregate
functions.
It reduces network traffic.
Example :-
Create Materialized View :-
CREATE MATERIALIZED VIEW M1 AS
SELECT EMPLOYEE_ID, FIRST_NAME, SALARY FROM EMPL WHERE
EMPLOYEE_ID BETWEEN 100 AND 150;
Refresh Syntax :-
EXECUTE DBMS_MVIEW. REFRESH ('M1');
(or)
BEGIN
DBMS_MVIEW. REFRESH (M1,'C');
END;
/
To refresh entire materialized view
TYPES :-
49
2. Object Materialized View
This is based on object table and created by using ‘OF TYPE’ clause.
Example :-
CREATE MATERIALIZED VIEW M30 REFRESH WITH ROWID AS
SELECT * FROM T5;
Example :-
CREATE MATERIALIZED VIEW M30 AS
SELECT A, B FROM T1;
Example :-
CREATE MATERIALIZED VIEW M30 FOR UPDATE AS
SELECT A, B FROM T1;
1. ON COMMIT
Whenever you save pending changes then you materialized view will be
refreshed automatically for this we use ‘ON COMMIT’.
50
CREATE MATERIALIZED VIEW M5 REFRESH FAST ON COMMIT AS
SELECT * FROM COURSE;
2. ON DEMAND
When you use ‘ON DEMAND’ then materialized view must be refreshed every
time by user.
This is default one.
Example :-
3. REFRESH FAST
This check for any changed made in log if yes then it refreshes a materialized
view or else it doesn’t refresh
Example :-
CREATE MATERIALIZED VIEW LOG ON S1;
4. REFRESH COMPLETE
In this when you update materialized view after updating base table; the entire
data in materialized view are deleted and then insert operation starts in
materialized view.
Example :-
CREATE MATERIALIZED VIEW M22 REFRESH COMPLETE AS
SELECT ROWID AS R, CNAME FROM S1;
5. REFRESH FULL
This method performs full refresh if possible otherwise it performs complete
refresh.
Example :-
CREATE MATERIALIZED VIEW LOG ON S1;
51
6. NEVER REFRESH
If you don’t want to refresh materialized view then use ‘NEVER REFRESH’
Example :-
CREATE MATERIALIZED VIEW M8 NEVER REFRESH AS
SELECT * FROM COURSE;
Materialized view logs are used to track changes (insert, update and delete) to a table.
Purging materialized view logs.
It show no of changes made to a table.
If you refresh materialized view then this gets to zero.
This is used when more number of user visit particular table repeatedly which will make
network traffic.
In this scenario materialized view will be created from where user can get data.
QUESTIONS
52
2. Difference between Simple view and Complex View.
Complete Refresh means you truncate entire materialized view and insert new data.
Fast Refresh means you update (or insert/delete) only the rows which have been
changed on master tables.
And just as information Force Refresh mean, Oracle tries to make a Fast Refresh and if
this is not possible then do Complete Refresh.
Usually Fast Refresh is much faster than Complete Refresh but it has restrictions. You
have to define MATERIALIZED VIEW LOG on master tables.
53
CASE AND DECODE
_______________________________________________________________________
1. CASE
Example :-
SELECT DEPARTMENT_ID,
CASE
WHEN DEPARTMENT_ID IN (10,20,30) THEN 'A'
WHEN DEPARTMENT_ID BETWEEN 40 AND 60 THEN 'B'
ELSE 'X' END
FROM DEPARTMENTS;
2. DECODE
This command is similar to if.. then.. else.. Statement. If the default statement is omitted
then null will be used if no matches found.
Syntax :-
DECODE (COLUMN NAME, SERACH, RESULT, SEARCH, RESULT, DEFAULT)
Example :-
1. CASE :-
SELECT CASE NULL
WHEN NULL
THEN 'NULL'
ELSE 'NOT NULL'
END NULL_TEST
FROM DUAL;
NULL_TES
--------
NOT NULL
54
2. DECODE :-
SELECT
DECODE(NULL, NULL, 'NULL',
'NOT NULL' ) NULL_TEST
FROM DUAL;
NULL
----
NULL
QUESTIONS
CASE DECODE
(i) Complies with ANSII SQL (i) Oracle proprietary.
(ii) Can works with logical operators other than (ii) Works only in ' = ' like operator
' = ' operator.
(iii) Can works with predicates and searchable (iii) Expressions are scalar values only.
queries.
(iv) Needs data consistency. (iv) Data consistency no needed.
(v) NULL = NULL, returns FALSE (v) NULL = NULL, returns TRUE
(vi) Can be used in PL/SQL block and SQL (vi) Can be used in SQL Statements.
statements.
(vii) Can be Used in parameters while calling a (vii) Cannot be Used in parameters while calling
procedure. a procedure.
55
SUB QUERIES
_______________________________________________________________________
SUB QUERIES:-
A query embedded within another query is called sub query.
There are two types of sub query they are
Example :-
Example :-
TYPES :-
Example :-
2. INLINE VIEW
Whenever a ‘From’ clause followed by sub query is called Inline view or named sub
query in a from clause is called Inline view.
Example :-
Whenever a ‘Where’ clause followed by sub query is called nested sub query. Here first
inner query is executed then outer query will be executed.
It doesn’t have any reference between inner query and outer query. Inner query runs
only once for outer query.
56
Example :-
Example :-
RULES :-
→ Sub query must be enclosed in brackets
→ Sub query cannot be used after order by
→ When we use multi-row sub query then we need to use relational operators like
IN, ALL & ANY.
QUESTIONS
57
INDEX
_______________________________________________________________________
INDEX:-
It is used to improve the performance of query retrieval.
Index can be either Unique or Non-Unique index
1. UNIQUE INDEX :
It is created automatically when a user defines a primary/unique constraint for a column.
TYPES :-
1. BITMAP INDEX :-
Created for low cardinality column that contains less than 100 unique records.
Create it when you have lot of duplicates.
Example :-
1.1 To create a bitmap index :-
2. B-TREE INDEX
Created for high cardinality column that contains more than 100 unique records.
58
Example :-
Example :-
4. Composite Index
Example :-
This is used to force the query to run particular index or full table scan.
Example :-
59
TABLE PARTITION
_______________________________________________________________________
TABLE PATITIONING:-
Table partition is a method of splitting an object (table or index) into separate partitions
based on some criteria. The criteria can be date, number or character.
If table contains more number of rows then queries takes more time to execute a query
and table becomes harder to manager. So in that case we use table partitioning to
overcome those issues. We can partition Table, Index & Materialized View.
TYPES :-
1. Range
2. List
3. Hash
4. Composite
1. RANGE
Segmenting the data date wise.
Example 1 :-
2. LIST
Segmenting the data location wise.
Partitioned on character
Example :-
60
CREATE TABLE SALES_LIST (SALESMAN_ID NUMBER (5), SALESMAN_NAME VARCHAR2
(30), SALES_STATE VARCHAR2 (20), SALES_DATE DATE)
PARTITION BY LIST(SALES_STATE)(PARTITION SALES_WEST VALUES
('MUMBAI','PUNE','GOA','NAGPUR','SURAT'),
PARTITION SALES_EAST VALUES
('KOLKATA','PATNA','RANCHI','JORHAT','AGARTALA'),
PARTITION SALES_NORTH VALUES
('DELHI','KANPUR','LUCKNOW','AGRA','MERUT'),
PARTITION SALES_SOUTH VALUES
('CHENNAI','HYDREBAD','COCHIN','BANGALORE','NELLORE')
);
3. HASH
Example :-
4. COMPOSITE PARTITION
Any combination of two.
Example :-
61
4.2 RANGE – LIST
Example :-
62