0 - Oracle Full & SQL Topic
0 - Oracle Full & SQL Topic
ORACLE
Dedicating to M.Rajasekhar Sir
3 Tablespace 8-8
4 Schema 9-9
D UGA PGA
P
DATA Online redo log files
O DICTIONARY
O CKPT
ARWR
L
DBWR
1. Hard parse
Without plan ID;
Syntactical
Symmetrical Archive Files
2. Soft parse
With plan ID PMON SMON
EXPLANATION:
When we installed the oracle it occupies some space from hard disk and some space from RAM.
The space occupied from RAM (750MB) - SYSTEM GLOBAL AREAR (SGA).
The space occupied from hard disk - ORACLE DATA BASE.
If we run any query for the 1st time two checking’s will be applied for that query in LIBRARY CACHE.
1. Syntactical - it will check the syntax of the query
2. Symmetrical - it will check whether the tables, columns are existing or not.
These two checking’s are done in hard parse only.
Again if we run same query it does not goes for these two checking’s because when we
are executing the query for 1st time system will generate some plan id for that query.
2nd time if we run same query it will go for soft parse by using that plan id.
Whether the query will go for the hard parse/soft parse will be decided by the plan id.
NOTE: If we write any query system will plan how to execute this query that process is called
optimization.
DATA DICTIONARY:
Objects list exists in this data dictionary, Data dictionary nothing but SELECT * FROM
ALL_OBJECTS etc..,
BUFFER CACHE:
Recent data will be exists in buffer cache (insert, update), all :NEW records will be present in this
buffer cache only.
o UGA: When we are connecting to the schema and we executing any select statement or update
statement etc., for that we need some memory that memory is User Global Area (UGA). When
we are calling any packaged program that entire package will store in UGA in the RAM. If we
are joining any tables and that join is nested loop join then those leading, probing table’s data
will be store in this UGA.
o PGA: When we executing bigger programs those are done in Program Global Area (PGA).
Mostly all the hash join operations are done in the PGA because we are joining the tables which
are having huge data. Sometimes UGA will be exists in the PGA when PGA need memory.
o LARGER POOL: Which operations need larger memory those are done in larger pool.
o JAVA POOL: When we call any java related programs from the data base those are store in
this JAVA POOL.
LGWR is log writer it moves the data from redo log buffer to online redo log files.
AKWR is archive writer it moves the data from online redo log files to archive files.
Both are used for backup and recovery which records are deleted and committed.
We have number of background processor in oracle, to see all those background processors
we should go for ‘SELECT * FROM V$BGPROCESS’.
ORACLE INSTANCE:
Oracle Instance = Background Processor + Temporary Memory + Permanent Memory
o Background processor (DBWR, CKPT, LGWR, ARWR etc..,).
o Temporary Memory (SGA).
o Permanent Memory (DATABASE).
Database File: Database files information exist in this means it contains information about (No.
of blocks, block size, total size, total size occupied by all blocks) in a tablespace.
SELECT * FROM V$DATAFILE;
On line redo log file: LGWR will export the data from redo log buffer to on line redo log file.
It works in five conditions 1/3rd of buffer is filled or 1MB of buffer is filled or 25secs
completed in red log buffer or when you give commit the when you write any DML.
In these five conditions if anyone is satisfied LGWR will move the data from redo log
buffer.
Archive files: It contains backup and recovery files exported by ARWR.
Control file: Control file contain timestamp of the database when oracle is installed and also it
will contain remaining files location address (database file, redo log file etc..,).
ORACLE DATABASE
(SYSDBA is warden for this) PHYSICAL COMPONENT
DATABASE FILES
PHYSICAL COMPONENT
(Tables, Functions, Procedures, Indexes etc...,)
TABLESPACE CREATION:
CREATE TABLESPACE RAMANA_DEFAULT DATAFILE
'E:\ORACLE\ORADATA\ORCL\RAMANA_DEFAULT.DBF' SIZE 300M;
To extend tablespace:
ALTER TABLESPACE RAMANA_DEFAULT ADD DATAFILE
'E:\ORACLE\ORADATA\ORCL\RAMANA_DEFAULT2.DBF' SIZE 50M;
In every project we have to maintain different tablespace’s for different type of objects. If you
want to store the object in particular tablespace you have to write that table space name at the time of
creation of that object. If you don’t write the tablespace name then it is go and store in the default
tablespace which you have given at the time of schema creation.
NOTE: If you create any global temporary table that data will be stored in temporary tablespace by
default. And if you want to do order by, group by operations in separate tablespace then you
should go for temporary tablespace.
SCHEMA CREATION:
Schema Permissions:
CREATE USER AR_MURTHY IDENTIFIED BY ACR143 DEFAULT TABLESPACE
RAMANA_DEFAULT TEMPORARY TABLESPACE RAMANA_TEMPORARY;
GRANT CONNECT,DBA TO AR_MURTHY;
GRANT READ, WRITE ON DIRECTORY DATA_PUMP_DIR TO AR_MURTHY;
REVOKE READ, WRITE ON DIRECTORY DATA_PUMP_DIR FROM AR_MURTHY;
Schema Permissions:
CREATE ROLE EQUITAS_MERCHANT;
GRANT CONNECT,CREATE TABLE,CREATE SYNONYM,CREATE PUBLIC
SYNONYM,CREATE PROCEDURE,CREATE TRIGGER TO EQUITAS_MERCHANT;
GRANT EQUITAS_MERCHANT TO RBL_PROJECT;
NOTE: 1. If you want to give permission for any schema you should give from SYSDBA only.
2. CREATE PROCEDURE is enough for procedure, function, packages, view but for
triggers we have mention separately.
EXPLANATION:
INITRANS, MAXTRANS:
Initial transaction by default 1 for tables and 2 for constraints
Maximum transaction by default 255
Means you able to make maximum 255 transactions without applying commit if you
done 256th transaction without commit previous transactions its leads to get system hang.
PCTFREE: pctfree means percentage free. It useful for any changes happens in the table in
future by using update that space is useful for that extended data. System takes percentage free
by default ‘10’ if we not mentioned, means every block contain 0.7kb of pctfree by default.
HEADER -1KB
HEADER
Ramana
Prasuna
PCT USED Lucky
Anjali
EMPTY SPACE
PCT FREE
INITIAL 64KB: If create a table then initially one extend will be created. 1 extend contain 8 blocks
each block size 8kb.
EXTEND = 8 BLOCKS * 8 KB
= 64KB
Note: when we creating a table it occupies 1MB space.
1. Transaction Level: In transaction level global temporary table data will be present in the
table until you give the commit.
CREATE GLOBAL TEMPORARY TABLE STUDENT_NEW (ROLLNO NUMBER, NAME
VARCHAR2(30), MARKS NUMBER) ON COMMIT DELETE ROWS;
2. Session Level: In session level global temporary table data will be present in the table until
session end (logout).
CREATE GLOBAL TEMPORARY TABLE GTT_STUDENT (ROLLNO NUMBER, NAME
VARCHAR2(30),MARKS NUMBER) ON COMMIT PRESERVE ROWS;
PREDEFINED TABLES:
o PLAN_TABLE;
o PLSQL_PROFILER_DATA;
o V$DATAFILE;
o DUAL;
ROWID:
ROWID= DB_FILE_ID + SEGMENT_ID +BLOCK_ID + ROW_NUMBER
o ROWID is combination database file_id, segement_id, block_id and row number
o ROWID is a static value means always same row contain same value.
o ROWID is a hexadecimal value. Contains 18 numbers.
o It will be store in database. Oracle automatically provides rowid when user inserts the
new row into the table.
ROW NUMBER:
o It is numeric value, based on the select statement output row number will generate
o Row number is not a static value based on the output of the select statement it will
change dynamically.
o Row number won’t store in data base temporarily it will generate for select statement
output.
DDL COMMANDS:
DDL: Data Definition Language
1. CREATE
2. ALTER
ADD
MODIFY
DROP
3. DROP
CREATE: This command is used create objects
CREATE TABLE STUDENT_INFO (ROLL_NO NUMBER(10), NAME
VARCHAR2(30),MARKS NUMBER (5,2));
If we want that table back when by mistake we have dropped that table we should write
FLASHBACK TABLE DEPT TO BEFORE DROP;
When one user is updating some records in one table at the same time another user trying
to do for update on same table it won’t allow because some records are locked in that table. In
this kind of situations you want to use for update you should go for skip locked concept.
USER_1: UPDATE EMP SET COMM=500 WHERE DEPTNO=30; it will lock all the
records from 30th department.
USER_2: SELECT * FROM EMP FOR UPDATE SKIP LOCKED; it won’t bring any
record from 30th department.
If we want that data back when by mistake we have deleted and committed that data we
should write
INSERT INTO EMP SELECT * FROM EMP AS OF TIMESTAMP SYSDATE-
10/24/60;
DCL COMMANDS:
DCL: Data Control Language
GRANT: To give permissions to another user/schema.
GRANT READ, WRITE ON DIRECTORY DATA_PUMP_DIR TO AR_MURTHY;
GRANT SELECT, INSERT, UPDATE ON SYN_EMP TO AR_MURTHY
GRANT ALL ON SYN_DEPT TO AR_MURTHY
GRANT EXECUTE ON SYN_SP_COMM_UPDATE TO AR_MURTHY
GRANT EXECUTE ON PKG.P1 TO AR_MURTHY
REVOKE: To cancel the permissions for any user/schema
REVOKE READ, WRITE ON DIRECTORY DATA_PUMP_DIR FROM AR_MURTHY;
REVOKE EXECUTE ON PKG.P1 FROM AR_MURTHY
WHERE: Where clause is used to put a condition on rows data and where clause will
filter the rows data
SELECT COUNT(*) FROM EMP WHERE DEPTNO=10;
TCL COMMANDS:
TCL: Transaction Control Language.
It will control complete action of a transaction by either we give commit or
rollback means every transaction completely under control of TCL (commit, rollback)
Note: Transaction means insert or update or delete.
SPECIAL CLAUSES:
GROUP BY: Group by clause is used to group the rows data
SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO
SELECT DEPTNO,JOB, COUNT(*) FROM EMP GROUP BY DEPTNO,JOB ORDER
BY DEPTNO
HAVING: Having clause is used to put a condition on grouped data. Having clause always
follow by ‘Group by’ clause. Means having clause filters the grouped data only.
SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO HAVING
DEPTNO=20;
ORDER BY: Order by clause is used bring the data order wise on which column based you
want to bring the order.
o Oder by will support to both WHERE and HAVING clauses.
o ASC for ascending order.
o DESC for descending order.
DISTINCT: To avoid duplicate values in the column. Means it is useful to know how
many types of values in the column.
SELECT DISTINCT JOB FROM EMP;
LIKE / NOTLIKE:
o It is only useful for characters
o Used to search for character values with a pattern.
o It uses 2 meta characters
1) Under Score : _ : represents single character;
2) Percentage : % : represents zero or more characters;
SELECT * FROM EMP WHERE ENAME LIKE 'J%'; (NAME’S START WITH ‘J’)
SELECT * FROM EMP WHERE ENAME LIKE '%S'; (NAME’S ENDS WITH ‘S’)
SELECT * FROM EMP WHERE ENAME LIKE '%A%’; (WHICH NAME’S HAVING
‘A’ IN THEIR SELVES);
IN & NOT IN: If you want to put two or more records in filter condition then better to go for
IN, NOT IN operators.
o Picks one by one value from list of values.
o Supports with all data types.
o We can use this to retrieve/manipulate data fast.
o NOT IN won’t support to NULL.
WITH: It will store one query result and provides one alias name for that.
DUAL TABLE:
It is system defined table. It supports to retrieve general information from select statement. It is
useful to do calculations with numbers and dates also useful to bring days by using dates calculations.
We can’t make any changes in this table means we are not able to do insert, update or delete any
information in this dual table
SELECT TO_CHAR(TO_DATE('15/8/1947','DD/MM/YYYY'),'DAY')FROM DUAL;
SELECT TO_CHAR(SYSDATE,'DD')||'TH '||TO_CHAR (SYSDATE,'MONTH') ||'
'||TO_CHAR(SYSDATE,'DAY')||' ' ||TO_CHAR(SYSDATE,'YYYYSP') QUARIE_75
FROM DUAL;
SELECT TRUNC((SYSDATE-TO_DATE('15/8/1947','DD/MM/YYYY'))/365) FROM
DUAL;
AGGREGATE FUNCTIONS:
Oracle provides some predefined aggregate functions like SUM, AVG, MAX/MIN, COUNT
etc.., to make calculations easier.
Aggregate functions always gives output in single row only
We can’t write normal columns along with aggregate functions without using ‘GROUP BY’
clause;
NOTE: COUNT gives that no of values stored in the normal column or grouped column;
MINUS:
SELECT EMPNO FROM EMP WHERE DEPTNO=20
MINUS
SELECT EMPNO FROM EMP WHERE SAL>1000
o It works like opposite ‘AND’ condition.
o It gives not matched data between the results.
INTERSECT:
SELECT EMPNO FROM EMP WHERE DEPTNO=20
INTERSECT
SELECT EMPNO FROM EMP WHERE SAL>1000
o It works like ‘AND’ condition
o It gives matched data between the results.
UNION ALL:
SELECT EMPNO FROM EMP WHERE DEPTNO=20
UNION ALL
SELECT EMPNO FROM EMP WHERE SAL>1000
o It will merge the two results
o And it gives duplicate values.
MERGE TABLE:
If you want to merge the data from any table by importing data from another table then you will
go for table merge. It will do two actions at a time they are updating and inserting.
Updating by modifying data which are existing in source table.
Inserting the data remaining data which are not found in target table.
MERGE INTO EMP_NEW T USING EMP S ON (T.EMPNO = S.EMPNO) WHEN MATCHED
THEN UPDATE SET T.SAL=S.SAL, T.COMM=S.COMM WHEN NOT MATCHED THEN
INSERT VALUES (S.EMPNO,S.ENAME,S.JOB,S.MGR,S.SAL,S.COMM,S.DEPTNO);
Note: For example in employee tables data always there is a chance to get changes in salary,
commission, job etc., columns only, mostly id number, name, hire date, always in same position
so better to mention only columns which are getting changes in update statement.
o TO_CHAR: This function converts any date value to a char value in the specified format.
o TO_DATE: It converts string into date value.
o MONTHS_BETWEEN: This function is used to find the number of months between the given
two dates.
o ADD_MONTHS: This function is used to add specific number of months to given date.
o LAST_DAY: This function is used to find out the last day of month for the given date.
o NEXT_DAY: This function is used to find next day date based on the given date.
o 'D'-day of the week.
o 'DD' -day of the month.
o 'DDD' -day of the year.
o 'DY' -WEN (day name in 1 st 3 characters).
o 'DAY' -Wednesday (full name of the day).
o 'MM' - 05 (month).
o 'MON' -APR (month name in 1 st 3 characters).
o 'MONTH' -April (full name of the month).
o 'YY' -last two digits of year.
o 'YYY' -2020 (YEAR).
o 'HH' -10 (hour).
o 'HH24' -16 (means 4pm).
o 'HH12' -4.
o 'MI' -minute.
o 'SS' -seconds.
o 'Q' –quarter of the year.
o 'CC' –century of the year.
o 'WW' -45 week of the year.
o 'W' –week of the month.
o 'SP' –spell out.
o 'DDSP' –today’s date is 20th.
o 'YYYYSP' –two thousand twenty.
Oracle provides some predefined char functions like LENGTH, SUBSTR, INSTR, REPLACE,
TRIM, UPPER/LOWER, REVERSE, TRIM etc.,
NOTE:
o If you pass the number then CHR will give you the string which is related to the number
o If you pass the string then ASCII will give you that string number
o Means every string has their individual number
CHAR:
Supports to maximum 2000.
By default it takes size 1, if we want to write the size we can write and it always occupy
the space which we have provided for every inserting record it doesn’t care length of the
record we are inserting.
VARCHAR2:
4000 up to 11g and 32767 from 12c.
We should provide size for Varchar.
What size of the record we are inserting that length only it occupy if we inserting the
record that record is more than provided size then it won’t allow.
CLOB:
Maximum size 4GB.
One table can allow any number of clob data type columns.
We should not write size for clob.
ANALYTICAL FUNCTIONS:
Generally we can’t write aggregate functions along with normal columns without using
group by clause. But without group by clause we want to write aggregate function with normal
column then we should go for the ‘Analytical Function’.
OVER()
OVER(ORDER BY)
OVER(ORDER BY SAL ROWS UNBOUNDED PRECEDING)
RANK()
DENSE_RANK()
ROW_NUMBER()
LISTAGG
o DENSE_RANK() if five members got 1st rank DENSE_RANK will provides 1st rank to
those five members and provides 2nd rank to sixth member;
o RANK() if five members got 1st rank then RANK will provides 1st rank to those five
members and provides 6th rank to sixth member;
o ROW_NUMBER() will simply provides one rank for each row;
ROLLUP AND CUBE: These two are always follows with group by clause.
o ‘ROLLUP’ will give the sum of group on which column based you grouped the data and
also gives the grand total of all groups.
SELECT DEPTNO,JOB,SUM(SAL) FROM EMP GROUP BY ROLLUP (DEPTNO,JOB);
o ‘CUBE’ will give the sum of group on which based your group the data and also gives the
grand total of all groups and additionally it will give sub group wise some, and it gives
grand total in top row.
SELECT DEPTNO,JOB,SUM(SAL) FROM EMP GROUP BY CUBE (DEPTNO,JOB);
ARITHMATIC FUNCTIONS:
Oracle provides some predefined arithmetic functions like POWER, ABS/SIGN,
GREATEST/LEAST, CEIL/FLOOR, ROUND, EXP, TRUNC to make arithmetic calculations easier.
SELECT POWER(3,3),SQRT(625) FROM DUAL;
SELECT ABS(-2000) , ABS(900) FROM DUAL;
SELECT SIGN(-200), SIGN(100) FROM DUAL;
SELECT GREATEST(10,20,-100), LEAST(10,-200,300) FROM DUAL;
SELECT CEIL(10.0001),FLOOR(99.99) FROM DUAL;
SELECT ROUND(1234567.987,2) ,ROUND(1234567.987,2) FROM DUAL;
SELECT ROUND(1234567.487) FROM DUAL;
SELECT EXP(2) FROM DUAL;
SELECT TRUNC(1000.10), TRUNC(1000.4444,2) FROM DUAL;
NOTE:
o Given value is positive or negative ABS will always return positive values only
o If given value is positive then SIGN returns positive value else if given values is negative
then SIGN returns negative value
o CEIL always gives next round figure values of the given dismal and FLOOR always gives
previous round figure values of the given dismal
o ROUND this function is used to find the round the number to nearest.
o EXP given E power N result (natural algorithm).
o TRUNC this function used to delete dismals or delete dismals from some position.
NOTE:
1. By default:
No Cycle
Cache - 20
Start with -1
Increment by - 1
Min value -1
Max value - 18 number of 9’s (999999999999999999);
2. Always min value <= Start with.
3. We can’t rollback the sequence (drawback/disadvantage).
4. We can’t call CURRVAL without calling NEXTVAL.
5. To know the sequence current value we can see in LAST_NUMBER column in this:
SELECT * FROM USER_SEQUENCES;
SELECT U.OBJECT_NAME,V.SESSION_ID,S.SERIAL#,S.OSUSER
FROM USER_OBJECTS U, V$LOCKED_OBJECT V, V$SESSION S
WHERE U.OBJECT_ID=V.OBJECT_ID AND V.SESSION_ID=S.SID;
1st way:
Tools
Sessions
Select the session id and right click on that session id then kill that session;
or
Select the session id and click on the kill button.
2nd way:
ALTER SYSTEM KILL SESSION '25,3563' IMMEDIATE
Here: 25 - Session id
3563 - Serial number.
NOTE: Index won’t store the entire data of the table. It stores only column data with their rowid’s on
which column you have created the index in leaf blocks. Once search the data using where
condition it catches the rowid’s of the conditioned data and then brings the data from table by
using that rowid’s.
To search indexes list of the schema:
SELECT * FROM USER_INDEXES;
TYPES OF INDEXES:
o B-tree index
o Unique index
o Bitmap index
o Function based index
o Reverse key index
WHEN THEN
CARDINALITY = 1 UNIQUE INDEX
WHEN THEN
CARDINALITY BETWEEN B-TREE INDEX
1 AND 20
WHEN THEN
CARDINALITY >20 THEN BITMAP INDEX
B-tree index will separate the data into leaf blocks to make data searching easier. B-tree
index contain root, branch, leaf blocks, root blocks, branch blocks contain directions and leaf
blocks contain the data.
ROUTE BLOCK
1-15
16-30
1 6 11 16 21 26
2 7 12 LEAF BLOCKS 17 22 27
3 8 13 18 23 28
4 9 14 19 24 29
5 10 15 20 25 30
B1 B2 B3 B4 B5 B6
UNIQUE INDEX:
CREATE UNIQUE INDEX IDX_EMPNO ON EMP(EMPNO) TABLESPACE
RAMANA_INDEXES;
Unique index also works like b-tree index but small differences is there, in b-tree index
even searching record founded then also it verifies next row for confirmation of is same record
exists in next row if not found then it will bring data from table by using founded rowid’s.
But in unique index if searching record is found then immediately its go and bring the
data from the table by using the only one rowid. There is no chance to go and search in next
row for same record because unique index blindly follows that column does not contain any
duplicate values.
When we are creating unique or primary key constraints on any column automatically
unique index will be created.
ROUTE BLOCK
TOTAL SAL (1-30,000)
2,000 (rowid) 11,000 (rowid) 24,000 (rowid) 31,000 (rowid) 41,000 (rowid) 51,100 (rowid)
2,500 (rowid) 12,500 (rowid) 25,500 (rowid) 35,500 (rowid) 46,500 (rowid) 53,500 (rowid)
4,500 (rowid) 14,500 (rowid) 25,500 (rowid) 35,800 (rowid) 47,800 (rowid) 58,800 (rowid)
4,500 (rowid) 18,000 (rowid) 28,000 (rowid) 39,000 (rowid) 48,000 (rowid) 59,000 (rowid)
7,000 (rowid) 18,000 (rowid) 30,000 (rowid) 39,500 (rowid) 49,500 (rowid) 59,500 (rowid)
B1 B2 B3 B4 B5 B6
ONLINE KEY:
If you are trying to rebuild the index at the same time somebody is writing DML
operation or writing select statement on that table there is chance to system struck or
hang. If you write online keyword at the time of creation of any kind of index then there
is no chance to dead lock or hang errors at the time of rebuild the index then we can
rebuild the index at any time.
CREATE INDEX IDX_EMP ON EMP(EMPNO) ONLINE;
ALTER INDEX IDX_EMP REBUILD ONLINE;
DROP INDEX IDX_EMP;
NOTE: Cardinality is useful for users to select which index is better for the column.
Selectivity is useful for system to select on which index scan have to search.
If it is not a selective index then system will skip index scan and go for table access
full.
RANGE PARTITION:
A table that is partitioned by range is partitioned in such a way that each partition contains
rows for which the partitioning expression value lies within a given range.
CREATE TABLE EMPLOYEE(EMP_NO NUMBER(2),EMP_NAME VARCHAR(2))
PARTITION BY RANGE(EMP_NO) (PARTITION P1 VALUES LESS THAN(10),
PARTITION P2 VALUES LESS THAN(20), PARTITION P3 VALUES LESS
THAN(30),PARTITION P4 VALUES LESS THAN(MAXVALUE));
Adding a partition:
ALTER TABLE EMPLOYEE ADD PARTITION P5 VALUES LESS THAN(40);
Dropping a partition:
ALTER TABLE EMPLOYEE DROP PARTITION P1;
Renaming a partition:
ALTER TABLE EMPLOYEE RENAME PARTITION P3 TO P6;
Truncate a partition:
ALTER TABLE EMPLOYEE TRUNCATE PARTITION P5;
Splitting a partition:
ALTER TABLE EMPLOYEE SPLIT PARTITION P2 AT(12)INTO(PARTITION
P21,PARTITION P22);
Exchanging a partition:
ALTER TABLE EMPLOYEE EXCHANGE PARTITION P2 WITH TABLE EMPLOYEE_X;
Moving a partition:
ALTER TABLE EMPLOYEE MOVE PARTITION P21 TABLESPACE ABC_TBS;
Adding a partition:
ALTER TABLE EMPLOYEE ADD PARTITION P5 VALUES('ENGINEER','SUPPORT')
Dropping a partition:
ALTER TABLE EMPLOYEE DROP PARTITION P5;
Renaming a partition:
ALTER TABLE EMPLOYEE RENAME PARTITION P5 TO P1;
Truncate a partition:
ALTER TABLE EMPLOYEE TRUNCATE PARTITION P5;
Exchanging a partition:
ALTER TABLE EMPLOYEE EXCHANGE PARTITION P1 WITH TABLE EMPLOYEE_X;
Moving a partition:
ALTER TABLE EMPLOYEE MOVE PARTITION P2 TABLESPACE ABC_TBS;
PARTITIONING KEY:
Each row in a partitioned table is unambiguously assigned to a single
partition. The partitioning key is comprised of one or more columns that determine
the partition where each row will be stored.
Adding a partition:
ALTER TABLE EMPLOYEE ADD PARTITION P9;
Renaming a partition:
ALTER TABLE EMPLOYEE RENAME PARTITION P9 TO P10;
Truncate a partition:
ALTER TABLE EMPLOYEE TRUNCATE PARTITION P9;
Exchanging a partition:
ALTER TABLE EMPLOYEE EXCHANGE PARTITION SYS_P1 WITH TABLE
EMPLOYEE_X;
Moving a partition:
ALTER TABLE EMPLOYEE MOVE PARTITION SYS_P1 TABLESPACE RAMANA_TAB;
ADVANTAGES OF PARTITIONS:
Reducing downtime for scheduled maintenance, which allows maintenance operations to
be carried out on selected partitions while other partitions are available to users.
Reducing downtime due to data failure, failure of a particular partition will no way affect
other partitions.
Partition independence allows for concurrent use of the various partitions for various
purposes.
Cluster we have to create before creating the tables cluster holds common column shared by two
tables cluster will be store the matching of two tables data separately in cluster area separately when we
are using that column in join conditions no need to go and check the for each record because cluster is
already storing mapping data in cluster area. It will improve performance while retrieving or
manipulating data from master child tables.
If you create index on cluster it will give better performance because it again that will be divide
into two parts.
DEPT EMP
DEPTNO ROWID DEPTNO ROWID
10 ROWID 10 ROWID
10 ROWID 10 ROWID
20 ROWID 20 ROWID
20 ROWID 20 ROWID
20 ROWID 20 ROWID
30 ROWID 30 ROWID
30 ROWID 30 ROWID
COMPOSITE INDEX: If we create one index on two in a table that is called composite index.
CREATE INDEX IDX_SAL_COMM ON EMP(SAL,COMM);
NOTE: If table having two composite indexes for (X, Y) index_1, for (X, Z) index_2 then if you are
writing where condition based on X column then index will work based on which index having
less branch blocks, if both indexes having same number of branch blocks then it works based on
the number of leaf of blocks.
SELECT * FROM DBA_INDEXES WHERE INDEX_NAME IN
('IDX_LOAN_ID','IDX_CUST_NO');
In this it will consider 1st B_LEVEL column, next LEAF_BLOCKS column.
If one index has more null values it go for another index even it having less branch, leaf
blocks. Because for null values index not powerful.
SELF JOIN:
SELECT W.ENAME,M.ENAME FROM EMP W, EMP M WHERE W.MGR=M.EMPNO;
EQUILENT JOIN:
SELECT E.ENAME,E.JOB,D.DNAME,E.SAL FROM EMP E, DEPT D WHERE
E.DEPTNO=D.DEPTNO AND D.DNAME IN ('SALES','ACCOUNTING');
o NOTE: Whatever the join you have used even LEFT OUTER JOIN (or) RIGHT
OUETR JOIN that brings on which table column you have attached (+) symbol that
opposite table column entire data
Means that statement brings all join condition matched values and also not matched
distinct values;
If you joining two tables and that probing table column having more data than leading
table data and probing table column has selective index then it goes for nested loop join.
SELECT * FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO
NOTE: In this kind situations sort merge join always follows by comparison (>, <) only. It does
not work in equijoin.
SELECT * FROM EMP1 A, EMP2 B WHERE A.SAL>B.SAL;
HASH JOIN:
When you’re joining two tables and both the joining columns has nearly equal quantity of
data. Then it goes for hash join. Even both the join conditioned column having index/ doesn’t
have index its go for hash join only.
If you want to decrease the execution time then you should go for filter the data by using
any column and that filter condition column should have index.
SELECT * FROM EMP1 A, EMP2 B WHERE A.EMPNO=B.EMPNO AND
A.SAL>100
NORMALIZATION:
Normalization is the process of combining various individual modules into a single process by
using data integrity, main advantage of normalization avoiding data redundancy.
EX: Employee data, employee previous experience data. When one employee having previous
experience in five companies, if we want to write both the information’s in one table then we
should write that employee information with each previous experience, to avoid that we create
another table for previous experiences and put some link between those tables using data
integrity that process is called normalization.
RULE BASED:
If we write a query for searching the data which column you have used to put filter condition
that column has index. Then rule based optimization blindly go and use the index for statement
execution. If that index not a selective index and that is not giving good performance then also it’s
go and use that index for query execution. Because rule based optimization follows rule only.
COST BASED:
In this condition before execution system will check cost, cardinality and the column
having selective index or not then it’s execute the plan. If system having selective index then its
go and use the index, if the index is not a selective index go for index skip scan means it will go
to table access full.
Optimization will plan the execution of a query like which database file, which extend,
which join method, which back and which index scan we have to use for execution. Once you
run any query it’s automatically generates a ‘plan id’. Next you run the same query it’s brings the
output lesser time then previous time by using that ‘plan id’.
HINT:
Hint will pass a message how the query should be execute.
HINT: /*+IDX_DEPTNO(DEPTNO)*/
SELECT /*+IDX_DEPTNO(DEPTNO)*/ * FROM EMP WHERE DEPTNO=10;
PARLELL HINT:
When you are searching the data if you are going for the parallel hint then it will divide
the data into pieces based on what are degrees you have given. Then it will search the data output
we can get in fast.
SELECT EMPNO /*+(PARALLEL 40)*/ , ENAME, SAL FROM EMP WHERE
EMPNO=7369;
In this we are given the degree is 40
Then system will separate blocks into 40% of blocks for one processor, 40% of blocks for
one processor and 20% of blocks for another processor and then system go and search the data
and output we can get in fast.
JULIET FORMAT:
If you want to write a number in letters then you should go for Juliet format.
SELECT TO_CHAR(TO_DATE(100000,'J'),'JSP') FROM DUAL;
A) ----ONE HUNDRED THOUSAND.
CHECK CONSTRAINT:
ALTER TABLE EMP ADD CONSTRAINT CK_DEPTNO CHECK (DEPTNO IN
(10,20,30));
o It is user friendly constraint
o It is works under the condition what we give
o It is accepts null values
COMPOSITE CONSTRAINT:
ALTER TABLE EMP ADD CONSTRAINT UK_EMP UNIQUE (EMPNO,ENAME);
When we create constraint on more than one column is called composite constraint. If
you create composite constraint on two columns it compares the values from both columns. It
combines both columns into single column and works on it.
Composite unique key
Composite primary key
Composite check
Composite foreign
Composite unique key:
ALLOWS DOESN’T ALLOW
EMPNO ENAME EMPNO ENAME
103 RAMANA 103 RAMANA
104 PRASUNA 104 PRASUNA
104 LUCKY 104 LUCKY
103 MURTHY 103 RAMANA
105 GOVINDH 104 PRASUNA
105 NULL 105 LUCKY
Means it is convert that two columns into a single column and won’t allow duplicate values on it.
Composite primary key also works like composite unique key but won’t allow null values.
Method_2:
ALTER TABLE EMP DISABLE CONSTRAINT PK_EMPNO;
ALTER TABLE EMP ENABLE CONSTRAINT PK_EMPNO;
CASE:
Case is statement and it is used to provide if, then, else type of logic
Case we can use inside the select statement and with select statement also we can use
It supports operators like (>, < ,>=, =<, =, in, between, like, not like)
By using case we can directly assign a value to variable in PL/SQL block
SELECT ENAME, SAL, CASE WHEN DEPTNO=10 THEN 'SOFTWARE' WHEN
DEPTNO=20 THEN 'ADMIN' ELSE 'DBA' END JOB FROM EMP;
DECODE:
Decode is function and it is used to provide if, then, else type of logic
Inside select statement only we can use decode. Without select statement we cannot use decode
It does not supports operators like (>, < ,>=, =<, =, in, between, like, not like)
SELECT ENAME,SAL,DECODE(DEPTNO,10,'SOFWARE',20,'ADMIN','DBA') JOB
FROM EMP;
PREDEFINED VIEWS:
o ALL_SOURCE;
o ALL_WM_CONSTRAINTS;
o ALL_IND_COLUMNS;
o ALL_IND_PARTITIONS;
SIMPLE VIEW:
CREATE VIEW VW_EMP AS SELECT EMPNO,ENAME,JOB,SAL FROM EMP;
o If you create a view on only one table is called simple view
o It allow DML commands
COMPLEX VIEW:
CREATE VIEW VW_EMP_DTLS AS SELECT E.ENAME,E.SAL,E.JOB,D.DNAME FROM
EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO;
o If you create a view on more than one table is called complex view.
o It does not allow DML operations.
NOTE: if you want to do DML operations on complex view then you should go for
instead of trigger.
MATERIALIZED VIEW:
It is a stored select statement as well as it will store the data of the select statement. Means
it will store both select statement and data. It is a data base object and it contains result of the
query. Whatever changes you have done on this view should not impact on the table but whatever
changes you have done on the table it may or may not impact on the materialized view it depends
on method of materialized view. Materialized view has four methods.
BEGIN
DBMS_MVIEW.refresh('MV_GRADE','FORCE');
END;
After you have done this forcefully view data also updates exactly like table data,
until that view data in same position.
USER(RAMANA143):
SELECT * FROM ARMURTHY.BRANCH_INFO;
INSERT INTO ARMURTHY.STUDENT_INFO;
USER(RAMANA143):
SELECT * FROM SYN_STUDENT_DATA;
Synonym is nothing but it is alias name of the original object whatever changes you done
at original object it will be impact on the synonym whatever changes your doing in synonym it
will impact on the original object.
PRIVATE SYNONYM:
CREATE SYNONYM SYN_EMP FOR EMP;
o This synonym only useful same user. The only use of private synonym is data security.
Because it gives only insert, select permission for the table.
NOTE: If you want to revoke the permissions you had given to the users.
REVOKE ALL ON SYN_STUDENT_DATA FROM RAMANA143;
REVOKE INSERT,UPDATE ON SYN_BRANCH_INFO FROM RAMANA143;
If you drop the table synonym will be invalid, but if you recreate the table automatically
synonym will be valid there is no need to compile the query again.
Private Synonyms: SELECT * FROM USER_SYNONYMS;
Public Synonyms : SELECT * FROM ALL_SYNONYMS;
SUB QUERY:
After where clause if we write any query as filter condition is called “sub query”.
SELECT * FROM EMP WHERE SAL = (SELECT MAX(SAL) FROM EMP);
SELECT * FROM EMP WHERE (DEPTNO,SAL) IN (SELECT DEPTNO,MAX(SAL)
FROM EMP GROUP BY DEPTNO);
In sub query 1st inner query run and bring some result by using that result outer query
will run and gives the output.
Sub Query:
SELECT * FROM EMP E WHERE (E.DEPTNO,E.SAL) IN (SELECT
DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO)
These both queries will give same results department wise highest salaries.
SCALAR QUERY:
Generally in between select and from clause always we have to write the column name
instead of column name if we write query to find any column that is called scalar query.
LEVEL:
To print 1-10 number:
SELECT LEVEL FROM DUAL CONNECT BY LEVEL<=10;
REGEXP_REPLACE
SELECT REGEXP_REPLACE('$RAMANA MURTHY@143','\D') FROM DUAL;
---'143' -( only for digits);
REGEXP_LIKE
To print all enames which as ‘ad’ in their self:
SELECT * FROM EMP WHERE REGEXP_LIKE(ENAME,'AD');
To print all enames which has ‘KI’ in their self and enames which has ‘ES’ in their self;
SELECT * FROM EMP WHERE REGEXP_LIKE(ENAME,'KI|ES');
REGEXP_SUBSTR
SELECT REGEXP_SUBSTR(P_DELIVERY_IDS,'[^,]+',1,ROWNUM) BULK COLLECT
INTO TYP_ID FROM DUAL CONNECT BY ROWNUM<=((LENGTH(P_DELIVERY_IDS)-
LENGTH (REPLACE(P_DELIVERY_IDS,',','')))+1);
o When client send the records as comma separated values then you want covert into column
rows data then it is use full.
Write your aim in control file (note pad) and save it in all files format only.
Ex: LOAD DATA INFILE ‘D:\STUDENT _DTLS.CSV’ INTO TABLE STUDENT_DATA
FILEDS TERMINATED BY “,” (ROLL_NO, STUDENT_NAME, MARKS).
If you want import data from OS then your data table should be empty but if want add
another table data same table you must use ‘APPEND’ command.
If you want to store new data in same table by removing old data then you should write
‘REPLACE’ in ‘APPEND’ place. If you want to store data from 3 rd or 4th row that means you
want to skip 1st three rows then you should go for ‘SKIP’ key word.
Note: That the OS file should be placed in the DATA_PUMP_DIR location. That
DATA_PUMP_DIR is the location where you are installed the oracle.
After loading the data the data will be at external table we are not able to do any DML operations
on that. Then if you want to do any changes in that data should do it in that OS file, if you are done
change in that OS file it’s automatically updates in the external table. Or you can create table like this
external table in the database.
Ex: CREATE TABLE STUDENT_DATA AS SELECT * FROM EXT_STUDENT_DATA;
If you want to write any conditions for loading you should write in before
NOBADFILE NODISCARDFILE NOLOGFILE
Ex: LOAD WHEN MARKS >450;
BADFILE 'STUDENT_1.BAD'
DISCARDDILE 'STUDENT_2.DISC'
LOGFILE 'STUDENT_3.LOG'
BADFILE: Condition satisfied but error occurred by data type, data size this kind of data stored in this.
DISCARDDILE: Condition not satisfied data stored.
LOGFILE : This is the total script of oracle loader running base.
To export data
Open command prompt.
EXP armurthy/acr143@ORCl file=D:\RAMANA_EXP.DMP OWNER=armurthy
statistics=none.
Statistics means if anyone doing any action in that database not consider that one.
To import data
Open command prompt.
IMP ramana143/ramana143@ORCL file=D:\RAMANA_EXP.DMP
FROMUSER=ARMURTHY TOUSER=RAMANA143.
Whatever the file you have exported that the file can be exported in binary file format for
data security purpose you can read this data after importing in a another schema you want.
In real time mostly FTP (file transfer protocol) services can use for this import/export for
data security purpose because Gmail is not secured.
Then that user can open the text document and select entire scripts paste in SQL command
window then automatically all the objects will be created in that schema also.
(OR)
Open the SQL command window and write the text document name
SQL> @’D:\oracle\murthy_exp.sql’;
Then automatically all the objects will be created. Every time you want to run the script
you should do like this.
Note: If you want to remove the schema name everywhere from the script you can replace with
null by using (CTRL+F).
Here:
1. ‘SET DEFINE OFF’ means while we running this script is there any others going put them
in hold.
2. ‘SPOOL DEC_2018_SCRIPT.LOG’ will create one log file for execution of the script if any
object not created that will be exists in this log file with error number message.
DB LINK
When two users in same database want share data from one user to another user we have public
synonyms. But one user want to share for another user in different database then only option we have
that is DB link.
Ex:
CREATE DATABASE LINK DLK CONNECT TO armurthy IDENTIFIED BY acr143
USING '(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =
localhost)(PORT =1521))(CONNECT_DATA =(SERVER = DEDICATED)
(SERVICE_NAME = ACR)))';
7. DISPLAY THE NAMES OF ALL EMPLOYEES WHO ARE WORKING IN DEPARTMENT NO-10:
SELECT E.ENAME FROM EMP E, DEPT D WHERE E.DEPTNO=10
AND E.DEPTNO=D.DEPTNO
11. DISPLAY THE NAMES OF EMPLOYEES WHO ARE WORKING AS CLERK, SALESMAN,
ANYLIST, DRAWING AND SALARY MORE THAN 300:
SELECT ENAME FROM EMP WHERE JOB IN
('CLERK','SALESMAN','ANALYST','DRAWING') AND SAL>1000;
12. DISPLAY THE NAMES OF EMPLOYEE WHO ARE WORKING IN THE COMPANY FROM
FAST FIVE YEARS:
SELECT ENAME, HIREDATE FROM EMP WHERE ((SYSDATE-HIREDATE)/365)>5
19. DISPLAY EMPLOYEE NAMES FOR WHOSE NAME ENDS WITH ALPHABET S:
SELECT ENAME FROM EMP WHERE ENAME LIKE '%S'
20. DISPLAY THE NAMES FOR EMPLOYEES WHO’S NAMES HAVE SECOND ALPHABET A
IN THEIR NAMES:
SELECT ENAME FROM EMP WHERE ENAME LIKE '_A%'
21. DISPLAY THE NAMES OF EMPLOYEES WHOSE NAMES IS EXACTLY FIVE CHARACTER
IN LENGTH:
SELECT ENAME FROM EMP WHERE LENGTH (ENAME)=5
22. DISPLAY THE NAMES OF EMPLOYEES WHO ARE NOT WORKING AS MANAGER:
SELECT ENAME, JOB FROM EMP WHERE JOB NOT IN ('MANAGER')
------OR-----
SELECT ENAME, JOB FROM EMP WHERE EMPNO NOT IN (MGR)
23. DISPLAY THE NAME OF EMPLOYEES WHO ARE NOT WORKING AS SALESMAN OR
CLERK OR ANALYST:
SELECT ENAME, JOB FROM EMP WHERE JOB
NOT IN ('ANALYST','CLERK','SALESMAN')
24. DISPLAY ALL ROWS FROM EMP TABLE. THE SYSTEM SHOULD WAIT AFTER EVERY
SCREEN FULL OF INFORMATION:
SELECT * FROM EMP (REMAING FRONT_END USER JOB)
31. DISPLAY THE MAXIMUM SALARY BEING PAID IN THE DEPARTMENT NO.20:
SELECT MAX (SAL) FROM EMP WHERE DEPTNO=20
35. DISPLAY THE NAMES OF THE EMPLOYEES IN ORDER OF SALARY i.e THE NAME OF
THE EMPLOYEE EARNING LOWEST SALARY SHOULD APPEAR FIRST:
SELECT ENAME, SAL FROM EMP ORDER BY SAL
37. DISPLAY THE DETAILS FROM EMP TABLE IN ORDER OF EMPLOYEE NAME:
SELECT ENAME, SAL FROM EMP ORDER BY ENAME
38. DISPLAY THE EMPNO, ENAME, DEPTNO AND SAL. SORT THE OUTPUT FIRST BASED
ON NAME AND WITHIN NAME BY DEPTNO AND WITHIN DEPTNO BY SALARY:
SELECT EMPNO, ENAME, DEPTNO, SAL FROM EMP ORDER BY ENAME, DEPTNO, SAL
39. DISPLAY THE NAME OF THE EMPLOYEE ALONG WITH ANNUAL SALARY. THE NAME
OF THE EMPLOYEE EARNING HIGHEST ANNUAL SALARY SHOULD APPEAR FIRST:
SELECT ENAME, SAL*12 ANUAL_SAL FROM EMP ORDER BY (SAL*12) DESC
40. DISPLAY NAME, SALARY, HRA, PF, DA, TOTAL SALARY FOR EACH EMPLOYEE. THE
OUTPUT SHOULD BE IN THE OREDR OF TOTAL SALARY, (HRA 15%, DA 10%, PF 5%)
OF SAL AND TOTAL SALARY WILL BE (SAL*HRA*DA)-PF:
SELECT ENAME, SAL, SAL*15/100 HRA, SAL*10/100 DA, SAL*5/100 PF FROM EMP
ORDER BY (SAL*HRA*DA)-PF
41. DISPLAY THE DEPTNO, TOTAL NUMBER OF EMPLOYEES WITH EACH JOB GROUP:
SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO ORDER BY DEPTNO
43. DISPLAY DEPARTMENT NUMBERS AND TOTAL SALARY FOR EACH DEPARTMENT:
SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO
44. DISPLAY DEPARTMENT NUMBERS AND MAXIMUM SLARY FOR EACH DEPARTMENT:
SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO
45. DISPLAY THE VARIOUS JOBS AND TOTAL SALARY FOR EACH JOB:
SELECT JOB, SUM(SAL) FROM EMP GROUP BY JOB
46. DISPLAY EACH JOB ALONG WITH MINIMUM SALARY BEING PAID IN EACH JOB
GROUP:
SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB
47. DISPLAY THE DEPARTMENT NUMBERS WITH MORE THAN THREE EMPLOYEES IN
EACH DEPARTMENT:
SELECT DEPTNO, COUNT(*) FROM EMP WHEN HAVING COUNT(*)>3 GROUP BY
DEPTNO
48. DISPLAY THE VARIOUS JOBS ALONG WITH TOTAL SALARY FOR EACH OF THE JOBS
WHERE TOTAL SALARY IS GREATER THAN 4000:
SELECT JOB, SUM(SAL) FROM EMP WHEN HAVING SUM(SAL)>4000 GROUP BY JOB
49. DISPLAY THE VARIOUS JOBS ALONG WITH TOTAL NUMBER OF EMPLOYEES IN EACH JOB
THE OUTPUT SHOULD CONTAIN ONLY THOSE JOBS WITH MORE THAN THREE EMPLOYEE :
SELECT JOB, COUNT(*) FROM EMP WHEN HAVING COUNT(*)>3 GROUP BY JOB
50. DISPLAY THE NAME OF THE EMPLOYEE WHO EARNS HIGHEST SALARY:
SELECT ENAME FROM EMP WHERE SAL = (SELECT MAX (SAL) FROM EMP)
51. DISPLAY THE EMPLOYEE NUMBER AND NAME OF THE WORKING AS CLERK AND
EARNING HIGHEST SALARY AMONG CLERK:
SELECT EMPNO, ENAME, SAL FROM EMP WHERE JOB ='CLERK' AND SAL IN (SELECT
MAX (SAL) FROM EMP GROUP BY JOB)
52. DISPLAY THE NAMES OF THE SALESMAN WHO EARNS A SALARY MORE THAN THE
HIGHEST SALARY OF ANY CLERK:
SELECT ENAME FROM EMP WHERE JOB='SALESMAN' AND SAL>
(SELECT MAX (SAL) FROM EMP WHERE JOB='CLERK')
53. DISPLAY THE NAMES OF THE CLERKS WHO EARN A SALARY MORE THAN THAT OF
JAMES OF THAT OF SALARY LESSER THAN THAT OF SCOTT:
SELECT ENAME FROM EMP WHERE JOB='CLERK' AND SAL >
(SELECT SAL FROM EMP WHERE ENAME='JAMES') AND SAL <
(SELECT SAL FROM EMP WHERE ENAME='SCOTT')
55. FIND OUT THE LENGTH OF YOUR NAME BY USING APPROPIATE FUNCTION:
SELECT LENGTH ('RAMANA MURTHY') FROM DUAL
56. DISPLAY THE NAMES OF THE EMPLOYEES WHO EARNS HIGHEST SALARY IN THEIR
RESPECTIVE DEPARTMENTS:
SELECT ENAME FROM EMP WHERE SAL IN (SELECT MAX (SAL)FROM EMP
GROUP BY DEPTNO)
57. DISPLAY THE NAMES OF EMPLOYEES WHO EARNS HIGHEST SALARY IN THEIR
RESPECTIVE JOB GROUPS:
SELECT ENAME FROM EMP WHERE SAL IN(SELECT MAX(SAL) FROM EMP GROUP
BY JOB)
58. DISPLAY THE EMPLOYEES NAME WHO ARE WORKING IN THE ACCOUNTING
DEPARTMENT:
SELECT E.ENAME FROM EMP E, DEPT D WHERE D.DNAME= 'ACCOUNTING' AND
E.DEPTNO=D.DEPTNO
59. DISPLAY THE EMPLOYEES NAMES WHO ARE WORKING IN THE CHICAGO:
SELECT E.ENAME FROM EMP E, DEPT D WHERE D.LOC='CHICAGO' AND
E.DEPTNO=D.DEPTNO
60. DISPLAY THE JOB GROUPS HAVING TOTAL SALARY GREATER THAN THE MAXIMUM
SALARY FOR MANAGERS:
SELECT JOB, SUM (SAL) FROM EMP WHEN HAVING SUM(SAL) >
(SELECT MAX (SAL)FROM EMP WHERE JOB= 'MANAGER')GROUP BY JOB
61. DISPLAY THE NAMES OF EMPLOYEES FROM DEPARTMENT NUMBER 10 AND SALARY
GREATER THAN THAT OF ANY EMPLOYEE WORKING IN OTHER DEPARTMENTS:
SELECT ENAME FROM EMP WHERE SAL> (SELECT MAX(SAL) FROM EMP WHERE
DEPTNO IN (20,30))
62. DISPLAY THE NAMES OF THE EMPLOYEES FROM DEPARTMENT 10 WITH SALARY
GREATER THAN THAT OF ALL EMPLOYEES WORKING IN OTHER DEPARTMENTS:
SELECT ENAME FROM EMP WHERE SAL> (SELECT MAX(SAL) FROM EMP
WHERE DEPTNO IN (20, 30))
69. FIND OUT FIRST OCCURANCE OF CHARACTER 'A' FROM THE FOLLOWING THE
STRING 'COMPUTER MAINTANANCE CORPORATION':
SELECT INSTR ('COMPUTER MAINTENANCE CORPORATION', 'A',1) FROM DUAL
71. DISPLAY THE INFORMATION FROM EMP TABLE WHEREVER JOB 'MANAGER' IS
FOUND IT SHOULD BE DISPLAYED AS BOSS (REPLACE FUNCTION):
SELECT ENAME, JOB, REPLACE (JOB,'MANAGER', 'BOSS') FROM EMP WHERE
JOB='MANAGER'
72. DISPLAY EMPNO, ENAME, DEPTNO FROM TABLE INSTEAD OF DISPLAY DEPATMENT
NUMBERS DISPLAY THE REALATED DEPARTAMENT NAME (DECODE FUNCTION):
SELECT E.ENAME, E.DEPTNO, DECODE (D.DEPTNO, E.DEPTNO, D.DNAME)
FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO ORDER BY E.DEPTNO;
75. DISPLAY CURRENT DATE 15TH AUGEST FRIDAY NINETEEN FORTY SEVEN:
SELECT TO_CHAR(SYSDATE,'DD')||'TH '||TO_CHAR (SYSDATE, 'MONTH')||'
'||TO_CHAR(SYSDATE,'DAY')||' ' ||TO_CHAR(SYSDATE,'YYYYSP') QUARIE_75
FROM DUAL
76. DISPLAY THE FOLLOWING OUTPUT FOR EACH ROW FROM EMP TABLE AS 'SCOTT
HAS JOINED THE COMPANY ON WEDNESDAY 13TH AUGEST NINTEEN NINETY':
SELECT ENAME ||' HAS JOINED'||TO_CHAR(HIREDATE, 'DD')||'TH '||TO_CHAR
(HIREDATE, 'MONTH')||' '||TO_CHAR (HIREDATE,'DAY')||' '||TO_CHAR
(HIREDATE,'YYYYSP') JOIN_DATE_QUARIE_76 FROM EMP
81. DISPLAY THE DETAILS OF THE THOSE WHO DO NOT HAVE ANY PERSON WORKING
UNDER THEM:
SELECT DISTINCT ENAME, JOB, MGR FROM EMP WHERE EMPNO NOT IN MGR
82. DISPLAY THE JOBS WHICH ARE UNIQUE TO THE DEPARTMENT NUMBER 10:
SELECT DISTINCT JOB FROM EMP WHERE DEPTNO=20
84. DISPLAY THE DETAILS OF EMPLOYEES WHO ARE IN DEPT TABLE AND GRADE IS 3:
SELECT E.ENAME, D.DNAME, G.GRADE FROM EMP E, GRADE G, DEPT D WHERE
G.GRADE=3 AND E.SAL BETWEEN G.LOSAL AND G.HISAL
AND E.DEPTNO=D.DEPTNO
85. DISPLAY THOSE WHO ARE NOT MANAGER AND WHO ARE MANAGER ANY ONE:
SELECT ENAME, JOB, EMPNO, MGR FROM EMP WHERE JOB NOT IN ('MANAGER')
AND EMPNO NOT IN MGR
86. DISPLAY THOSE EMPLOYEES WHOSE NAME CONSTAIN NOT LESS THAN 4
CHARACTERS:
SELECT ENAME FROM EMP WHERE LENGTH(ENAME)>3
87. DISPLAY THOSE DEPARTMENTS WHOSE NAME STARTS WITH 'S' WHILE LOCATION
NAME END WITH '0':
SELECT DNAME, LOC FROM DEPT WHERE DNAME LIKE '%S' AND LOC LIKE'%O'
89. DISPLAY THOSE EMPLOYEES WHOSE SALARY IS GREATER THAN 3000 AFTER GIVING
20% INCREMENT:
SELECT ENAME, SAL,(SAL+SAL*20/100) INCR_SAL FROM EMP
WHERE (SAL+SAL*20/100)>3000
92. DISPLAY EMPLOYEE NAME, DEPARTMENT NAME, SALARY AND COMM FOR WHOSE
SALARY IN BETWEEN 2000 AND 5000 WHILE LOCATION IN CHICAGO:
SELECT E.ENAME, D.DNAME, E.SAL, E.COMM FROM EMP E, DEPT D WHERE E.SAL
BETWEEN 2000 AND 5000 AND D.LOC IN ('CHICAGO') AND D.DEPTNO=E.DEPTNO
93. DISPLAY THOSE EMPLOYEE WHOSE SALARY IS GREATER THAN HIS MANAGER
SALARY:
SELECT W.ENAME FROM EMP W, EMP M WHERE W.MGR=M.EMPNO AND
W.SAL>M.SAL
94. DISPLAY THOSE EMPLOYEES WHO ARE WORKING IN THE SAME DEPARTMENT
WHERE HIS MANAGER IS WORKING:
SELECT W.ENAME WORKER, M.ENAME MANAGER, W.DEPTNO, M.DEPTNO FROM
EMP W, EMP M WHERE W.MGR=M.EMPNO AND W.DEPTNO=M.DEPTNO
95. DISPLAY THOSE EMPLOYEES WHO ARE NOT WORKING UNDER ANY MANAGER:
SELECT * FROM EMP WHERE MGR IS NULL
96. DISPLAY GRADE AND EMPLOYES NAME FOR THE DEPARTMENT NUMBER 10 AND 30
BUT GRADE IS NOT 4, WHILE JOINED THE COMPANY BEFORE 31-DEC-82:
SELECT E.ENAME, D.DEPTNO, G.GRADE, E.HIREDATE FROM EMP E, DEPT D,
GRADE G WHERE E.DEPTNO=D.DEPTNO AND E.SAL BETWEEN G.LOSAL AND
G.HISAL AND E.DEPTNO IN (10,30) AND G.GRADE NOT IN (4)
AND E.HIREDATE<'31/DEC/1982' ORDER BY D.DEPTNO
97. UPDATE THE SALARY OF EACH EMPLOYEE BY 10% INCREATENTS THAT ARE NOT
ELIGIBLE FOR COMMISION:
UPDATE EMP2 SET COMM=SAL*10/100 WHERE NVL(COMM,0)=0
98. DELETE EMPLOYEES WHO JOINED THE COMPANY BEFORE 31-DEC-82 WHILE
THERE DEPARTMENT LOCATION IS 'NEW YORK' OR 'CHICAGO':
DELETE FROM EMP2 WHERE DEPTNO IN (SELECT DEPTNO FROM DEPT WHERE LOC
IN ('NEW YORK','CHICAGO')) AND HIREDATE<'31/DEC/1982'
99. DISPLAY EMPLOYEE NAME, JOB, DEPARTMENT NAME, AND LOCATION FOR ALL
WHO ARE WORKING AS MANAGERS:
SELECT E.ENAME, E.JOB, D.DNAME, D.LOC FROM EMP E, DEPT D
WHERE E.JOB='MANAGER'
100. DISPLAY THE NAME AND SALARY OF FORD IF HIS SALARY IS EQUAL TO HIGH
SALARY OF HIS GRADE:
SELECT E.ENAME, E.SAL, G.HISAL FROM EMP E, GRADE G WHERE
E.ENAME='FORD' AND E.SAL=G.HISAL
101. DISPLAY THE NAME OF THOSE EMPLOYEES WHO ARE GETTING HIGHEST SALARY:
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP)
GNANA IT SOLUTIONS, VIZAG 60
102. DISPLAY THOSE EMPLOYEES WHOSE MANAGER NAME IS JONES AND ALSO
DISPLAY THE MANAGER NAME:
SELECT W.ENAME EMPLOYEE, M.ENAME MANAGER FROM EMP W, EMP M
WHERE W.MGR=(SELECT EMPNO FROM EMP WHERE ENAME ='JONES') AND
M.EMPNO=(SELECT EMPNO FROM EMP WHERE ENAME='JONES')-100
103. DISPLAY THE EMPLOYEE NAME, JOB, DEPARTMENT NAME, LOCATION FOR ALL
WHO ARE WORKING AS MANAGER:
SELECT W.ENAME, W.JOB, D.DNAME, M.ENAME MANAGER ,G.GRADE FROM EMP
W,EMP M, DEPT D, GRADE G WHERE W.MGR=M.EMPNO AND W.SAL BETWEEN
G.LOSAL AND G.HISAL AND M.DEPTNO=D.DEPTNO ORDER BY W.DEPTNO
104. DISPLAY EMPLOYEE NAME, JOB, HIS MANAGER AND DISPLAY ALSO EMPLOYEES
WHO ARE WITHOUT MANAGER:
SELECT W.ENAME, W.JOB, M.ENAME MANAGER FROM EMP W,EMP M
WHERE W.MGR=M.EMPNO
105. LIST OUT ALL THE EMPLOYEES NAME, JOB, SALARY GARDE, DEPARTMENT NAME
FOR EVERY ONE IN THE COMPANY EXCEPT 'CLERK' SORT ON SALARY DISPLAY THE
HIGHEST SALARY:
SELECT E.ENAME, E.JOB, D.DNAME, G.GRADE FROM EMP E, DEPT D, GRADE G
WHERE E.SAL BETWEEN G.LOSAL AND G.HISAL AND E.DEPTNO=D.DEPTNO AND
E.ENAME NOT IN ('CLERK')ORDER BY E.SAL DESC
108. DISPLAY DEPARTMENT NAME WHERE AT LEAST 3 ARE WORKING AND DISPLAY
ONLY DEPARTMENT NAME:
SELECT DNAME FROM (SELECT DEPTNO FROM EMP GROUP BY DEPTNO
HAVING COUNT (*)> =3)E,DEPT D WHERE E.DEPTNO = D.DEPTNO
109. DISPLAY NAMES OF THOSE MANAGERS WHOSE SALARY IS MORE THAN THAT
AVERAGE SALARY OF COMAPNY:
SELECT ENAME FROM EMP WHERE JOB ='MANAGER' AND SAL>(SELECT AVG(SAL)
FROM EMP)
111. DISPLAY EMPLOYEE NAME, SALARY, COMMISION, NET PAY AND WHOSE NET PAY
IS GREATER THAN OR EQUAL TO THEIR SALARY OF THE COMPANY:
SELECT E.ENAME, E.SAL, E.COMM, A.NET_PAY FROM EMP E,
(SELECT EMPNO, SAL+NVL (COMM, 0)-SAL*10/100 NET_PAY FROM EMP)A
WHERE E.EMPNO=A.EMPNO AND A.NET_PAY >=SAL;
112. DISPLAY THOSE EMPLOYEES WHOSE SALARY IS LESS THAN HIS MANAGER
SALARY BUT MORE THAN SALARY OF ANY OTHER MANAGER:
SELECT DISTINCT T.ENAME, T.SAL FROM (SELECT W.ENAME, W.SAL FROM EMP W,
EMP M WHERE W.MGR=M.EMPNO AND W.SAL<M.SAL ) T, (SELECT M.SAL FROM
EMP W, EMP M WHERE W.MGR=M.EMPNO) R WHERE T.SAL>R.SAL;
114. FIND OUT THE NUMBER OF EMPLOYEES WHOSE SALARY IS GREATER THAN THERE
MANAGER SALARY:
SELECT COUNT (*) FROM (SELECT W.ENAME FROM EMP W, EMP M WHERE
W.MGR=M.EMPNO AND W.SAL > M.SAL)
115. DISPLAY THOSE MANAGER WHO ARE NOT WORKING UNDER PRESEDENT BUT
WORKING UNDER ANY OTHER MAANAAGER:
SELECT * FROM EMP WHERE MGR IS NOT NULL AND MGR NOT IN(SELECT EMPNO
FROM EMP WHERE JOB='PRESIDENT')
---------OR----------
SELECT * FROM EMP W, EMP M WHERE W.MGR=M.EMPNO
AND W.MGR IS NOT NULL AND M.JOB NOT IN ('PRESIDENT')
117. DELETE THOSE RECORDS FROM EMP TABLE WHOSE DEPARTMENT NUMBER NOT
AVAILANBLE IN DEPARTMENT TABLE:
DELETE FROM EMP2 WHERE DEPTNO NOT IN
(SELECT D.DEPTNO FROM EMP2 E, DEPT D WHERE E.DEPTNO(+)=D.DEPTNO)
118. DISPLAY THOSE EARNERS WHOSE SALARY IS OUT OF THE GRADE AVAILABLE IN
SALARY GRADE TABLE:
SELECT *FROM EMP E,GRADE G WHERE GRADE=
(SELECT MAX(GRADE)FROM GRADE) AND E.SAL BETWEEN G.LOSAL AND G.HISAL
119. DISPLAY EMPLOYEE NAME, SALARY, COMMISION AND WHO’S NET PAY IS
GREATER THAN ANY OTHER IN THE COMPANY:
SELECT DISTINCT E.EMPNO, E.ENAME, E.SAL, E.COMM, A.NET_PAY FROM EMP E,
(SELECT EMPNO, SAL+NVL (COMM,0)-SAL*10/100 NET_PAY FROM EMP)A
WHERE A.NET_PAY > (SAL+NVL (COMM, 0)-SAL*10/100);
123. DISPLAY THOSE EMPLOYEES WHO JOINED IN THE COMPANY IN THE MONTH OF
DECEMBER:
SELECT * FROM EMP WHERE TO_CHAR (HIREDATE,'MM')=12
127. DISPLAY THOSE EMPLOYEE WHOSE 10% SALARY IS EQUAL TO THE YEAR OF
JOINING:
SELECT * FROM EMP WHERE(SAL*10/100)= (TO_CHAR (HIREDATE,'YY'))
130. DISPLAY THOSE EMPLOYEES WHO JOINED THE COMPANY BEFORE 15TH OF THE MONTH:
SELECT * FROM EMP WHERE TO_CHAR (HIREDATE,'DD')<15
131. DELETE THOSE EMPLOYEES WHO JOINED THE COMPANY 21 YAERS BACK FROM TODAY:
SELECT * FROM EMP WHERE (SYSDATE-HIREDATE)/365>21
135. DISPLAY THE NAME OF THE DEPARTMENT THOSE EMPLOYEES WHO JOINED THE
COMPANY ON THE SAME DATE:
SELECT * FROM EMP WHERE HIREDATE IN (SELECT HIREDATE FROM EMP
GROUP BY HIREDATE HAVING COUNT (*) >1)
----------- (OR) ------------
SELECT * FROM EMP E, (SELECT HIREDATE FROM EMP GROUP BY HIREDATE
HAVING COUNT (*)>1) AWHEREE.HIREDATE=A.HIREDATE
136. DISPLAY THE MANAGER NAME WHO HAS MAXIMUM NUMBER OF EMPLOYEES
WORKING UNDER HIM:
SELECT E.ENAME, C.NO_EMP FROM EMP E, (SELECT * FROM (SELECT
MGR, COUNT (*) NO_EMP FROM EMP GROUP BY MGR ORDER BY COUNT (*)DESC)
WHERE ROWNUM=1)C WHERE E.EMPNO=C.MGR
137. LIST OUT EMPLOYEES NAME AND SALARY INCREASED BY 15% AND EXPREDDED
AS WHOLE NUMBER DOLLAR:
SELECT ENAME, TRUNC((SAL+SAL*15/100)/72,2) SAL_DOLLORS FROM EMP
138. PRODUCE THE OUTPUT OF THE EMP TABLE "EMPLOYEE_AND_JOB" FOR NAME AND
JOB:
SELECT ENAME||'_AND_'||JOB FROM EMP
140. PRINT A LIST OF EMPLOYEES DISPLAYING 'LESS SALARY' IF LESS THAN 1500 IF
EXACTLY 1500 DISPLAY AS 'EXACT SALARY' AND IF GREATER THAN 1500 THEN
DISPLAY 'MORE SALARY':
SELECT ENAME, SAL, CASE WHEN SAL<1500 THEN 'LESS_SAL'WHEN SAL=1500
THEN 'EXACT_SAL' ELSE 'MORE_SAL' END SAL_INFO FROM EMP
141. WRITE A QUERY TO CALUCULATE THE LENGTH OF EMPLOYEE NAME HAS BEEN
WITH THE QUERY:
SELECT ENAME, LENGTH (ENAME) FROM EMP
142. DISPLAY THOSE MANAGERS WHO ARE GETTING LESS THAN HIS EMPLOYEES
SALARY:
SELECT * FROM EMP W, EMP M WHERE W.MGR=M.EMPNO AND W.SAL>M.SAL
143. DISPLAY THOSE WHO WORKING AS MANAGER USING CO-REALTED SUB QUERY:
SELECT * FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP)
146. USE THE VARIABLE IN A STATEMENT WHICH FINDS ALL EMPLOYEES WHO CAN
EARN 3000 A YEAR OR MORE:
SELECT ENAME, (SAL+NVL(COMM,0))*12 ANNUAL_SAL FROM EMP WHERE
((SAL+NVL(COMM,0))*12)>=30000
147. FIND OUT HOW MANY MANAGERS ARE THERE WITH OUT LISTENING THEM:
SELECT COUNT (*) FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP)
148. DISPLAY THOSE EMPLOYEES WHOSE MANAGER NAME IS JONES ALSO WITH HIS
MANAGER NAME:
SELECT W.ENAME WORKER, M.ENAME MANAGER FROM EMP W, EMP M WHERE
W.MGR IN (SELECT EMPNO FROM EMP WHERE ENAME= 'JONES')
AND W.MGR=M.EMPNO
UNION
SELECT W.ENAME WORKER, M.ENAME MANAGER FROM EMP W, EMP M
WHERE W.EMPNO IN (SELECT EMPNO FROM EMP WHERE ENAME='JONES')
AND W.MGR=M.EMPNO
--------- (OR) ---------
SELECT W.ENAME WORKER, M.ENAME MANAGER FROM EMP W, EMP M WHERE
W.MGR IN ((SELECT EMPNO FROM EMP WHERE ENAME='JONES'), (SELECT MGR
FROM EMP WHERE ENAME='JONES'))AND W.MGR=M.EMPNO
149. FIND OUT THE AVERAGE SALARY AND AVERAGE TOTAL REMUNIRATION FOR
EACH JOB TYPE REMEMBER SALESMAN EARN COMMISSION:
SELECT JOB, TRUNC(AVG(SAL+NVL(COMM,0))) AVG_SAL,
TRUNC(AVG((SAL+NVL(COMM,0))*12)) AVG_ANNUAL FROM EMP GROUP BY JOB
152. LIST OUT THE LOWEST PAID EMPLOYEES WORKING FOR THE EACH MANAGER,
EXCLUDE ANY GROUPS WHERE MIN SALARY IS LESS THAN 1000 SORT THE OUTPUT
BY SALARY:
SELECT W.ENAME, W.SAL , M.ENAME, M.SAL FROM EMP W, EMP M
WHERE M.EMPNO=W.MGR AND W.SAL<M.SAL AND W.SAL>1000 AND
W.SAL IN(SELECT MIN(SAL) SAL FROM EMP GROUP BY MGR) ORDER BY W.SAL
155. LIST OUT ALL THE EMPLOYEES BY NAME AND NUMBER ALONG WITH THEIR
MANAGERD NAME AND NUMBER ALSO DISPLAY 'NO MANGER' WHO HAS NO
MANAGER:
SELECT DISTINCT W.EMPNO, W.ENAME, CASE WHEN W.MGR IS NOT NULL THEN
M.ENAME WHEN W.MGR IS NULL THEN 'NO MANAGER' END MANAGER
FROM EMP W, EMP M WHERE W.MGR IS NULL OR W.MGR=M.EMPNO
156. FIND OUT THE EMPLOYEE WHO EARNED THE MIN SAL FOR THEIR IN ASCENDING
ORDER:
SELECT ENAME, JOB, SAL FROM EMP WHERE SAL IN(SELECT MIN(SAL)
FROM EMP GROUP BY JOB) ORDER BY SAL
157. FIND OUT THE MOST RECENTLY HIRED EMPLOYEES IN EACH DEPARTMENT ORDER
BY HIREDATE:
SELECT D.DNAME, E.ENAME, E.HIREDATE FROM EMP E, DEPT D
WHERE E.HIREDATE IN (SELECT MAX (HIREDATE) FROM EMP
GROUP BY DEPTNO) AND E.DEPTNO=D.DEPTNO
-------- (OR)---------
SELECT DISTINCT ENAME, HIREDATE FROM EMP WHERE HIREDATE IN (SELECT
MAX(HIREDATE) FROM EMP GROUP BY DEPTNO) ORDER BY HIREDATE
158. DISPLAY NAME, SALARY AND DEPTNO FOR EACH EMPLOYEE WHO EARN SALARY
GREATER THAN THE AVERAGE OF THE THEIR DEPARTMENT ORDER BY DEPTNO:
SELECT E.DEPTNO ,E.ENAME, E.SAL, S.AVG_SAL FROM EMP E,(SELECT DEPTNO,
TRUNC(AVG(SAL))AVG_SAL FROM EMP GROUP BY DEPTNO)S
WHERE S.DEPTNO=E.DEPTNO AND E.SAL>S.AVG_SAL
158. FIND OUT ALL DEPARTMENTS WICH HAVE MORE THAN 3 EMPLOYEES:
SELECT DEPTNO, COUNT (*) FROM EMP HAVING COUNT(*)>3 GROUP BY DEPTNO
159. IN WHICH YEAR DID MOST PEOPLE JOIN THE COMPANY. DISPLAY THE YEAR AND
NUMBER OF EMPLOYEES:
SELECT YEAR_OF_JOIN, NO_OF_EMP FROM(SELECT HIREDATE YEAR_OF_JOIN,
COUNT (*) NO_OF_EMP FROM (SELECT ENAME, TO_CHAR(HIREDATE ,'YYYY')
HIREDATE FROM EMP) GROUP BY HIREDATE ORDER BY COUNT(*) DESC) WHERE
ROWNUM=1
161. WRITE A QUERY OF DISPLAY AGAINIST THE ROW OF THE MOST RECENT HIRED
EMPLOYEE. DISPLAY ENAME HIREDATE AND COLUMN MAX DATE SHOWING:
SELECT * FROM (SELECT ENAME, HIREDATE FROM EMP
ORDER BY HIREDATE DESC) WHERE ROWNUM=1
------- (OR) ---------
SELECT ENAME, HIREDATE FROM EMP ORDER BY HIREDATE DESC
162. DISPLAY EMPLOYEES WHO CAN EARN MORE THAN LOWEST SALARY IN
DEPARTMENT NO.30:
SELECT * FROM EMP WHERE SAL>
(SELECT MIN(SAL) FROM EMP WHERE DEPTNO=30)
-------- (OR) ----------
SELECT * FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP
HAVING DEPTNO=30 GROUP BY DEPTNO)
163. FIND EMPLOYEES WHO CAN EARN MORE THAN EVERY EMPLOYEE IN
DEPARTMENT NO.30:
SELECT * FROM EMP WHERE SAL>
ANY (SELECT SAL FROM EMP WHERE DEPTNO=30)
164. FIND OUT AVERAGE SALARY AVERAGE TOTAL REMAINDERS FOR EACH JOB TYPE:
SELECT J.JOB, J.M NO_OF_EMP, J.N AVG_SAL, TRUNC (J.N/J.M) REMINDER FROM
(SELECT JOB, COUNT (JOB)M, TRUNC (AVG(SAL)) N FROM EMP GROUP BY JOB)J
165. DISPLAY THE HALF OF THE ENAME IN UPPER AND HALF OF THE ENAME IN LOWER CASE:
SELECT UPPER (SUBSTR (ENAME, 1, LENGTH (ENAME)/2)) ||LOWER (SUBSTR
(ENAME, (LENGTH (ENAME)/2)+1)) FROM EMP
169. DISPLAY THOSE EMPLOYEES WHO’S JOING OF THE MONTH AND GRADE IS EQUAL:
SELECT E.ENAME, E.HIREDATE, G.GRADE FROM EMP E,GRADE G WHERE E.SAL
BETWEEN G.LOSAL AND G.HISAL AND TO_CHAR(HIREDATE,'MM')=GRADE
171. DISPLAY THOSE EMPLOYEE WHOS JOING DATE IS AVAILABLE IN DEPARTMENT NUMBER:
SELECT * FROM (SELECT ENAME,TO_CHAR(HIREDATE,'DD') J_DATE, DEPTNO
FROM EMP2) WHERE J_DATE IN DEPTNO
173. LIST OUT THE EMPLOYEE NAME, SALARY AND PF FROM EMP:
SELECT ENAME, SAL, SAL*12/100 PF FROM EMP
179. I WANT TO GIVE A VALIDATION SAYING THAT SALARY CONNOT BE GREATER THAN 10,000,
(NOTE GIVE NAME TO THIS COLUMN):
ALTER TABLE EMP ADD CONSTRAINT CK_SAL CHECK (SAL<10000)
180. FOR THE TIME BEING I HAVE DECIDED THAT I WILL NOT IMPOSE THIS VALIDATION. MY
BOSS HAS AGREED TO PAY MORE THAN 10000:
ALTER TABLE EMP DROP CONSTRAINT CK_SAL
182. MY BOSS HAS CHANGED HIS MIND. NOW HE DOES'T WANT TO PAY MORE THAN
10000 SALARY. SO REVOKE THAT SALARY CONSTRAINT:
ALTER TABLE EMP ADD CONSTRAINT CK_SAL CHECK(SAL<10000)
184. OH! THIS COLUMN SHOULD BE RELATED TO EMPNO. GIVE A COMMAND TO ADD
THIS CONSTRAINT ADD DEPTNO COLUMN TO EMP TABLE THIS DEPTNO NO
COLUMN SHOULD BE RELATED TO DEPT TABLE:
“ALTER TABLE DEPT ADD CONSTRAINT UK_DEPTNO UNIQUE (DEPTNO)”
“ALTER TABLE EMP ADD CONSTRAINT FK_DEPTNO FOREIGN KEY(DEPTNO)
REFERENCES DEPT(DEPTNO)”
186. CREATE TABLE CALLED AS NEW_EMP. THIS TABLE SHOULD CONTAIN EMPNO,
ENAME and DNAME ONLY:
CREATE TABLE NEW_EMP AS SELECT ENAME, EMPNO, DNAME FROM EMP E,
DEPT D WHERE E.DEPTNO=D.DEPTNO
187. DELETE THE ROWS OF EMPLOYEES WHO ARE WORKING IN THE COMPANY FOR
MORE THAN TWO YEARS:
DELETE FROM EMP WHERE HIREDATE IN (SELECT HIREDATE FROM EMP WHERE
(SYSDATE-HIREDATE)/365>39)
191. DISPLAY EMPLOYEE NAME AND DEPARTMENT NAME FOR EACH EAMPLOYEE:
SELECT ENAME, DNAME FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO
193. DISPLAY DEPARTMENT NUMBER ALONG WITH TOTAL SALARY IN EACH DEPARTMENT:
SELECT DEPTNO, SUM(TOTAL_SAL) TOTAL_SAL FROM (SELECT DEPTNO, SAL+
NVL(COMM,0)TOTAL_SAL FROM EMP) GROUP BY DEPTNO
---------- (OR) ----------
SELECT DEPTNO, SUM (SAL+NVL(COMM,0)) TOTAL_SAL FROM EMP GROUP BY DEPTNO
1. PL/SQL block
2. PL/SQL Engine
3. Database Server
PL/SQL:
NOTE: ‘ ; ’ is not acceptable for declare, as, begin, if, loop. If you want to print a hardcore value
in PL/SQL you have to put it in between single quote (‘’). And variable should not write
between single quote. If you write variables in between single quotes its print like hardcore
values. Variables should be declared between declare and begin.
Ex_1: Declare
DECLARE
X NUMBER:=10;
Y NUMBER:=20;
Z NUMBER;
BEGIN
Z:= X+Y;
DBMS_OUTPUT.PUT_LINE(Z);
END;
If we have don’t written ‘EXIT WHEN X=5’ condition it will be infinite loop.
FOR LOOP:
We have to give lower and upper limits to run the FOR LOOP.
WHILE LOOP:
It is condition based loop. If don’t satisfy the condition at any time it run’s continuously
infinity times.
Ex: DECLARE
X NUMBER;
BEGIN
WHILE (X<10) LOOP
DBMS_OUTPUT.PUT_LINE(X);
X:= X+1;
END LOOP;
END;
If we have don’t satisfy ‘(X<10)’ condition in the program it will run infinite times.
BLOB:
DECLARE
SRC_LOB BFILE:=BFILENAME('DATA_PUMP_DIR','RAMANA_ID.JPG');
DEST_LOB BLOB;
BEGIN
INSERT INTO EMP_INFO (NAME, PHOTO) VALUES ('RAMANA', EMPTY_BLOB())
RETURNING PHOTO INTO DEST_LOB;
DBMS_LOB.open (SRC_LOB, DBMS_LOB.LOB_READONLY);
DBMS_LOB.LOADFROMFILE (DEST_LOB, SRC_LOB,
DBMS_LOB.GETLENGTH(SRC_LOB));
DBMS_LOB.CLOSE (SRC_LOB);
END;
PRAGMA AUTONOMOUS_TRANSACTION:
Autonomous transaction defines any transaction as independent transaction from the parent
transaction allows commit, rollback without any effecting of parent transaction.
In any procedure we write “PRAGMA AUTONOMOUS_TRANSACTION” between as and begin, and
we write commit or rollback in code is works for that procedure only there is no chance to commit or
rollback previous programs DML actions.
Because we used “PRAGMA AUTONOMOUS_TRANSACTION” transaction in that procedure means
that commit or rollback is limited for corresponding procedure only.
DYNAMIC SQL:
Generally we can’t perform DDL operations in the PL/SQL block if you want to perform DML
operations in PL/SQL blocks we should go for the “Dynamic SQL”.
DDL operations are auto commit. If PL/SQL allows DDL operations that DDL operation will be
committed then previous operations also commit automatically that’s why PL/SQL won’t allow DDL
operations. But we want to use DDL operation in PL/SQL block compulsory we will go for “Dynamic
SQL”. It keyword is “EXECUTE IMMEDIATE”.
If we use ‘select into’ class in implicit cursor. It gives only two values either 0 or 1.
Because INTO clause gives values of only one row in PL/SQL block.
It is only for status of DML operations or select into class.
It is single type and “SQL%” is the key word for implicit cursor.
EXPLICIT CURSOR:
Generally we cannot write select statement in the PL/SQL block if you want to write
select statement in the PL/SQL block we should go for into clause. Into clause will allow
fetching maximum one row I want to fetch more than one row I should for the cursor. Cursor is a
private area created by PL/SQL block to store what is the data fetching by the cursor select
statement.
Cursor has three models
Basic cursor:
DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME,DNAME FROM EMP E, DEPT D
WHERE E.DEPTNO=D.DEPTNO;
LN_EMPNO EMP.EMPNO%TYPE;
LV_ENAME VARCHAR2(30);
LV_DNAME DEPT.DNAME%TYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO LN_EMPNO,LV_ENAME,LV_DNAME;
EXIT WHEN C1% NOTFOUND;
DBMS_OUTPUT.PUT_LINE(LN_EMPNO||', '||LV_ENAME||', '||LV_DNAME);
END LOOP;
CLOSE C1;
END;
Even declaration section also not necessary for cursor for loop with select statement. We
can directly write select statement in loop;
REFERENCE CURSOR:
Cursor is always associated with same result set but ref cursor can be assigned to
different result sets. It has two types:
1. Weak Refcursor
TYPE TYP_REF IS REF CURSOR;
TYP TYP_REF;
2. Strong Refcursor
TYPE TYP_REF IS REF CURSOR RETURN EMP%ROWTYPE;
TYP TYP_REF;
Weak Refcursor:
By using only one weak ref cursor we can assign to no. of select statements. We
can able to join different tables in select statement.
Explicit cursor always associated with same result set but ref cursors can assign to
different result sets. Means one ref cursor we can open for emp table for once and next
time we can open same ref cursor for dept table data and again we can open same ref
cursor for salgrade table data but explicit cursor is always open with same result set.
BEGIN
OPEN TYP FOR SELECT * FROM EMP;
LOOP
FETCH TYP INTO VEC;
EXIT WHEN TYP%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(VEC.ENAME||' '||VEC.SAL);
END LOOP;
CLOSE TYP;
Strong Refcursor:
The difference between explicit cursor and strong refcursor is explicit cursor
gives information every time with same select statement but strong refcursor able to
change where condition every time.
The difference between explicit cursor, weak refcursor and strong refcursor is
explicit cursor, weak refcursor allow joins in select statement but strong refcursor not
allow joins because its key word is RETURN EMP%ROWTYPE;
TYP2 SYS_REFCURSOR;
BEGIN
OPEN C1;
CLOSE C1;
This normal function we can use in both SQL and PL/SQL, there no restrictions for this.
Note: SF means Stored Function.
Note: If you write DML operations in function it is not eligible to use in SQL. But you are using
DML operations with “pragma autonomous_transaction+TCL” it allowed in SQL.
Note: If you write out parameter in the function. It is not eligible in SQL there is no
medicine for this.
PREDEFINED FUNCTIONS:
o Date functions
o Char functions
o Arithmetic functions
o Aggregate functions
o Analytical functions
If you want to use any DML operations in the program better to go for “procedure”.
We cannot use procedures in SQL. We use out parameters for return values but these are also not
allowed in SQL.
There is no predefined procedure’s.
We don’t have any pre defined procedures. We have predefined packages in that we have
some packaged procedures.
VARRAY:
TYPE TYP_VAR IS VARRAY(100) OF NUMBER;
TYP TYP_VAR;
RECORD:
TYPE TYP_REC IS RECORD(ENAME VARCHAR2(30),DNAME VARCHAR2(15));
TYP TYP_REC;
Record is nothing but collections of elements
Record is not a composite data type because record does not support bulk collect
Record brings only one row from any table
If you want to bring all rows by using bulk collect for record then should write a
composite data type on record.
If you write nested table as sub data type for record then you can use bulk collect in
record.
Ex: DECLARE
TYPE TYP_REC IS RECORD (EMPNO NUMBER, ENAME VARCHAR2(30),
DNAME VARCHAR2(15));
TYPE TYP_NEST IS TABLE OF TYP_REC;
TYP TYP_NEST;
BEGIN
SELECT E.EMPNO, E.ENAME, D.DNAME BULK COLLECT INTO TYP
FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO;
END;
RETURNING CLAUSE:
Ex_1:
DECLARE
X NUMBER;
BEGIN
UPDATE EMP SET COMM=NVL (COMM,0)+SAL*20/100
WHERE EMPNO=7369 RETURNING COMM INTO X;
END;
Ex_2:
DECLARE
TYPE TYP_TAB IS TABLE OF VARCHAR2 (100);
TYP TYP_TAB;
BEGIN
DELETE FROM EMP WHERE DEPTNO=30
RETURNING ENAME BULK COLLECT INTO TYP;
END;
COUNT LAST
It will give number of elements in a It will give largest index number
collection
Ex: Suppose collection having 5 records, Ex: Suppose collection having 5 records,
in that 3rd record deleted by using delete in that 3rd record deleted by using delete
method then count will give 4 method then last will give 5
EXISTS: This also supports to all composite data types, exist will give true or false only.
TYP_VAR TYP_VARRAY:= TYP_VARRAY (100,200,300);
TYP_TAB TYP_PLSQL_TAB;
TYP_NEST TYP_NEST_TAB:= TYP_NEST_TAB (111,222,333,444);
---VARRAY
IF TYP_VAR.EXISTS(3) THEN TYP_VAR(3) := 999;
---PL/SQL TABLE
IF TYP_TAB.EXISTS(1) THEN TYP_TAB(1) := 888;
---THIS IS FAILED BECAUSE NO RECORDS IN PL/SQL TABLE DATATYPE
---NESTED TABLE
IF TYP_NEST.EXISTS(3) THEN TYP_NEST(3) := 666;
--PL_SQL TABLE
TYP_T (1):= 10;
--VARRAY
TYP_V.EXTEND;
TYP_V (1):= 20;
LIMIT: Limit method not useful for all composite types. It useful for only varray to show the
limit of varray. Because there is no limit for nested and PL/SQL table, Varray is the only
composite type having limit.
TYP_VAR.LIMIT
NEXT, PRIOR: These are only useful for first box or last box numbers finding. Means if you
pass a value number for NEXT then if the next box exist then gives the next box number
else if the next box is not exist then gives null, if you pass a value number for PRIOR
then if the previous box exist then gives the previous box number else if the previous box
is not exist then gives null.
Ex: DECLARE
TYPE TYP_NEST IS TABLE OF VARCHAR2(10);
TYP TYP_NEST:=TYP_NEST('ORANGE','APPLE','MANGO','GRAPS');
BEGIN
DBMS_OUTPUT.PUT_LINE('NEXT----'||TYP.NEXT(2));
-------OUT PUT =3 ;
DBMS_OUTPUT.PUT_LINE('PRIOR------'||TYP.PRIOR(2));
-------OUT PUT =1 ;
DBMS_OUTPUT.PUT_LINE('NEXT----'||TYP.NEXT(4));
DBMS_OUTPUT.PUT_LINE('PRIOR------'||TYP.PRIOR(1));
--BOTH OF THE RESULTS-----OUT PUT IS NULL ;
END;
TYP_VAR.NEXT(3);
TYP_VAR.PRIOR(3);
TYP_NEST.NEXT(2);
TYP_NEST.PRIOR(3);
TYP_TAB.NEXT(2);
TYP_TAB.PRIOR(3);
MULTISET INTERSET:
If you want to store common data in two collections into another collection then you
should go for multiset intersect.
Ex: TYP3:= TYP MULTISET INTERSECT TYP2;
MULTISET INTERSET:
If you want check some data of one collection is found in another collection then go with
sub multiset.
Ex: IF TYP2 SUBMULTISET TYP THEN;
MEMBER OF:
If any value in normal variable you want to check that the value is a member collection
value then it useful. This ‘ member of ’ is useful only in collections to check.
Ex: X VARCHAR2(30):= 'YELLOW';
IF X NUMBER OF TYP THEN
DBMS_OUTPUT.PUT_LINE('YES IT IS MEMBER OF TYP');
END IF;
Ex: DECLARE
TYPE TYP_TAB IS TABLE OF EMP%ROWTYPE;
TYP TYP_TAB;
BEGIN
SELECT * BULK COLLECT INTO TYP FROM EMP;
FOR I IN 1..TYP.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(TYP(I).EMPNO||' '||TYP(I).ENAME);
END LOOP;
END;
BULK BIND:
It will bind all the DML operations and moves from PL/SQL engine SQL engine at
one-shot. If you write DML operation inside the collection for loop each DML operation
consider as a separate DML operation then each DML operation create one context switch
for execution purpose if loop is running 10lac times 10lac context switches will be created
from Pl/SQL to SQL.
BULK LIMIT:
Bulk limit divide the data into pieces we can do the process with each piece of data.
Generally collections are stored in the RAM. If table having massive data then there is
chance to storage error/system hang because of memory to avoid that we can go for the bulk
limit.
FORWARD DECLARATION:
If you write any private program you can use it in package body only. You can’t use
outside the package body. But wherever you want use it in the body before that this program
should be created this concept called as forward declaration.
EXAMPLE:
-----------------------------------------------PACKAGE SPECIFICATION:
CREATE OR REPLACE PACKAGE PKG_INSERTS AS
LV_TYP VARCHAR2(4);
LN_NUM NUMBER(5);
LV_CUST_ID VARCHAR2(10);
AS BEGIN
INSERT INTO LO_CUST_DOC_DTLS VALUES
(SF_CUST_ID(P_APPLI_ID),P_AADHAR,P_ADAR_COPY,P_PAN,P_PAN_COPY,P_PAY,
P_STAT,P_NOM_ADAR,P_NOM_ADAR_COPY,P_NOM_PAN,P_NOM_PAN_COPY,'P');
END;
END;
PREDEFINED PACKAGES:
o DBMS_PROFILER
o DBMS_JOB
o DBMS_MVIEW
o DBMS_UTILITY
o UTL_FILE
o DBMS_LOB
o UTL_SMTP
o DBMS_METADATA etc.,
BEGIN
DBMS_PROFILER.start_profiler('SP_DATA_LOADINNG');
SP_DATA_LOADINNG;
DBMS_PROFILER.stop_profiler;
END;
Here
start_profiler, stop_profiler are packaged procedures in the
“DBMS_PROFILER” package.
SP_DATA_LOADINNG is a individual profiler which is we want to know the run time.
After executing this then we want to check the result then we want to result we should go for that
two tables join like:
Ex: SELECT A.TEXT, A.line, P.TOTAL_OCCUR, P.TOTAL_TIME/1000
FROM ALL_SOURCE A, PLSQL_PROFILER_DATA P
WHERE A.line=P.LINE# AND A.name='SP_DATA_LOADINNG';
BEGIN
FO:= UTL_FILE.fopen('DATA_PUMP_DIR',LV_FILE,'W',400);
UTL_FILE.putf(FO,'%s\n','OBJECT_NAME,OBJECT_COUNT');
BEGIN
FT:= UTL_FILE.fopen('DATA_PUMP_DIR','RAMANA.CSV','R',4000);
LOOP
BEGIN
UTL_FILE.get_line(FT,LV_DATA);
LV_DATA:= CHR(39)||REPLACE(LV_DATA,',',''',''')||CHR(39);
IF X>0 THEN
LV_DATA:='INSERT INTO RAMANA VALUES('||LV_DATA||')';
EXECUTE IMMEDIATE LV_DATA;
END IF;
EXCEPTION WHEN NO_DATA_FOUND THEN EXIT;
END;
X:= X+1;
END LOOP;
END;
BEGIN
UTL_FILE.fgetattr('DATA_PUMP_DIR','EMP.TXT',X,Y,Z);
IF X THEN
DBMS_OUTPUT.PUT_LINE('YES THAT FILE IS EXISTS IN THE DIRECORY');
ELSE DBMS_OUTPUT.PUT_LINE( 'FILE NOT EXISTS');
END IF;
END;
FT UTL_FILE.file_type;
LV_DATA VARCHAR2(100);
A NUMBER:=0;
BEGIN
UTL_FILE.fgetattr('DATA_PUMP_DIR',P_FILE,X,Y,Z);
IF X= FALSE THEN RETURN;
ELSIF X= TRUE THEN
FT:= UTL_FILE.fopen('DATA_PUMP_DIR',P_FILE,'R',4000);
LOOP
BEGIN
UTL_FILE.get_line(FT,LV_DATA);
LV_DATA:= CHR(39)||REPLACE(LV_DATA,',',''',''')||CHR(39);
IF A>0 THEN
LV_DATA:='INSERT INTO RAMANA VALUES ('||LV_DATA||')';
EXECUTE IMMEDIATE LV_DATA;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN EXIT;
END;
A := A+1;
END LOOP;
END IF;
END;
To stop job:
BEGIN
DBMS_JOB.broken(23,TRUE);
COMMIT;
END;
To change interval:
BEGIN
DBMS_JOB.interval(24,'ADD_MONTHS(SYSDATE,1)');
COMMIT;
END;
But it changes the interval of that job if want to run a job immediately but without
changing the job interval then you should go for test by right clicking on the program and go to
test.
If you want create a trigger for only one or more DDL commands on only one particular
object in the schema. It is possible by using pseudo columns.
ora_dict_obj_name
ora_dict_obj_type
ora_sysevent
ora_login_user
sysdate
These five are system defined key columns and these are useful when we want to trace
who is doing DDL operations, which action they are doing and on which object they are doing in
the schema .
Ex: CREATE OR REPLACE TRIGGER TRG_EMP BEFORE DDL ON SCHEMA
BEGIN
IF ORA_DICT_OBJ_NAME='EMP' AND ORA_DICT_OBJ_TYPE='TABLE' AND
ORA_SYSEVENT IN ('DROP','ALTER') THEN RAISE_APPLICATION_ERROR
(-20400,'YOU CANNOT DROP/ALTER ON THIS TABLE');
END IF;
END;
Instead of trigger:
Generally complex views won’t allow DML operations if you want to perform the
DML operation on complex views then you should go for the instead of trigger.
o It’s mainly for allow DML operations in complex views.
o There is no before/after condition this only ‘ instead of ’ is there.
o There is no chance for mutating/recursive errors in this.
View:
CREATE VIEW VW_EMP_DEPT AS SELECT EMPNO,ENAME,JOB,SAL,E.DEPTNO,
DNAME,LOC FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO;
Instead of trigger:
CREATE OR REPLACE TRIGGER TRG_COMPLEX
INSTEAD OF UPDATE ON VW_EMP_DEPT FOR EACH ROW
BEGIN
UPDATE EMP
SET ENAME=:NEW.ENAME, EMPNO=:NEW.EMPNO,JOB=:NEW.JOB,SAL=:NEW.SAL,
DEPTNO=:NEW.DEPTNO WHERE EMPNO=:OLD.EMPNO;
UPDATE DEPT
SET DNAME=:NEW.DNAME, DEPTNO=:NEW.DEPTNO,LOC=:NEW.LOC
WHERE DEPTNO=:OLD.DEPTNO;
END;
COMPOUND TRIGGER:
If you can write more than one trigger at one area is called “compound trigger”. (allows
min:1 , max:4);
It allows only four conditions:
1. One before statement level
2. One before row level
3. One after row level
4. One after statement level.
MUTATING ERROR:
Mutating error occur only in row level triggers on which table you are performing the
DML operation same table if you are using inside the trigger body. Then you will get mutating
error. If you want to resolve this then you should go for “pragma
autonomous_transaction +TCL”.
Means: Mutating error (ORA-04091) occurs whenever a row level trigger tries to modify or
select data from the table that is already undergoing change.
RECURSIVE ERROR:
If we are writing trigger on an action and we are using same action in the trigger body we
will get recursive error.
Note: Recursive error occur in row level trigger by (insert/insert)
And statement level trigger by (insert/insert, update/update, delete/delete).
PREDEFINED EXCEPTION:
no_data_found:
When select into clause not fetch any record (or) When select statement is unable to
retrieve data into PL/SQL variables.
Too_many_rows:
Select into fetched more records or when select statement is retrieve more than one row
into PL/SQL table.
Zero divide:
When user try to divide zero with any number (simply: when divisor =0);
Value error:
When data types are not matched or when we are trying to store larger value into smaller
variable.
Cursor already open:
When without closing cursor try to open cursor again.
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN CLOSEC1;
WHEN INVALID_CURSOR THEN OPEN C1;
END;
Invalid cursor:
When user try to fetch rows without opening the cursor or when we are trying to open the
cursor with a wrong name.
Program error:
It occurs when internal SQL or PL/SQL error happens means background processor (BG,
LGWR etc.,) are not working properly.
Storage error:
When server is out of memory.
When collection exceeds RAM memory.
Dup_val_on_index:
When we are trying to insert duplicate values in unique index columns.
Time_out_on_resorces:
Activated when user performs infinite loop process.
When others:
It will handle any type of oracle runtime error this exception you have to write end of all
the exceptions.
2. RAISE:
Declare section is required and exception section is required it will stop the
program then it will go to exception part.
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO VEC;
EXIT WHEN C1%NOTFOUND;
BEGIN
LN_COMM:= VEC.SAL*P_COMM/100;
IF LN_COMM<100 THEN RAISE EX;
ELSIF LN_COMM>1000 THEN RAISE DX;
ELSIF LN_COMM IS NULL THEN RAISE EX;
ELSE UPDATE EMP SET COMM=LN_COMM WHERE EMPNO=VEC.EMPNO;
END IF;
EXCEPTION
WHEN EX THEN
UPDATE EMP SET COMM=100 WHERE EMPNO=VEC.EMPNO;
WHEN DX THEN
UPDATE EMP SET COMM=1000 WHERE EMPNO=VEC.EMPNO;
END;
END LOOP;
CLOSE C1;
END;
BULK EXCEPTION:
When we are going for the bulk bind concept we have to do multiple operations at one
shot then there is a chance to get bulk of errors at a time. So if we want to catch those errors then
we should go for bulk exception.
Step_1:
Step_2:
CREATE OR REPLACE PROCEDURE SP_BULK_ERROR(P_MODULE VARCHAR2,
P_ERROR_NO VARCHAR2,P_ERROR_MSG VARCHAR2, P_ROW_NO NUMBER)
AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO BULK_EXP_ERRORS
VALUES (P_MODULE, SYSDATE, P_ERROR_NO, P_ERROR_MSG, P_ROW_NO);
COMMIT;
END;
BEGIN
OPEN C1;
LOOP
FETCH C1 BULK COLLECT INTO TYP LIMIT 4;
EXIT WHEN TYP.COUNT=0;
BEGIN
FORALL I IN 1..TYP.COUNT SAVE EXCEPTIONS
INSERT INTO EMP_2 VALUES TYP(I);
LN_COUNT:=LN_COUNT+4;
EXCEPTION
WHEN EX THEN
FOR I IN 1.. SQL%BULK_EXCEPTIONS.COUNT LOOP
LN_COUNT:=LN_COUNT+SQL%BULK_EXCEPTIONS(I).ERROR_INDEX;
SP_BULK_ERROR ('SP_BULK_EXP', SQLCODE,
SQLERRM (-SQL%BULK_EXCEPTIONS(I).ERROR_CODE), LN_COUNT);
LN_COUNT:=LN_COUNT+1;
END LOOP;
END;
END LOOP;
CLOSE C1;
END;
EXCEPTION SECTION:
EXCEPTION
WHEN OTHERS THEN
SP_ERROR_LOG ('SP_COMM_CAL',SQLCODE,SQLERRM,
SUBSTR (DBMS_UTILITY.format_error_backtrace,-5));
RAISE_APPLICATION_ERROR(-20400,SQLERRM);
END;
Step_1:
CREATE TABLE LOCK_TAB (ID_NO NUMBER);
Step_2:
CREATE OR REPLACE PROCEDURE SP_DATA_CON(P_EMPNO NUMBER)
AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO LOCK_TAB VALUES (P_EMPNO);
COMMIT;
END;
Step_3:
CREATE OR REPLACE PROCEDURE SP_CON_DELETE(P_EMPNO NUMBER)
AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
DELETE FROM LOCK_TAB WHERE ID_NO=P_EMPNO;
COMMIT;
END;
IF LN_COUNT>0 THEN
RAISE_APPLICATION_ERROR
(-20345,'SOME TRANSACTION IS UNDERGOING PLEASE WAIT FOR
SOME TIME AND TRY AGAIN');
ELSE
SP_DATA_CON (P_EMPNO);
END IF;
UPDATE EMP SET SAL=SAL-P_AMT WHERE EMPNO=P_EMPNO;
DELETE FROM LOCK_TAB WHERE ID_NO=P_EMPNO;
COMMIT;
Depositor procedure
CREATE OR REPLACE PROCEDURE SP_DEPOSIT(P_EMPNO NUMBER,P_AMT NUMBER)
AS
LN_COUNT NUMBER;
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
SELECT COUNT(*) INTO LN_COUNT FROM LOCK_TAB WHERE ID_NO=P_EMPNO;
IF LN_COUNT>0 THEN
RAISE_APPLICATION_ERROR
(-20345,'SOME TRANSACTION IS UNDERGOING PLEASE WAIT FOR
SOME TIME AND TRY AGAIN');
ELSE
SP_DATA_CON(P_EMPNO);
END IF;
UPDATE EMP SET SAL=SAL-P_AMT WHERE EMPNO=P_EMPNO;
DELETE FROM LOCK_TAB WHERE ID_NO=P_EMPNO;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
SP_CON_DELETE (P_EMPNO);
SP_ERROR_LOG ('SP_DEPOSIT', SQLERRM,
SUBSTR (DBMS_UTILITY.format_error_backtrace,-3));
RAISE_APPLICATION_ERROR (-20200, SQLERRM);
END;
OBJECT TABLE:
Object is nothing but a collection of elements. It is also works like record whatever the
columns you want to add you can add in this and it is also store maximum one record like record
(collection).
CREATE TYPE TYP_OBJ IS OBJECT (NAME VARCHAR2(30), SEAT_NO NUMBER);
CREATE TYPE TYP_O IS TABLE OF TYP_OBJ;
Note: Record is local variable, if you declare record becomes global. But every time you
want to call that record at out of that package you have write like package. record.
But object is global by creation you can call it in anywhere in the schema by suing
the object name.
Ex_1:
CREATE OR REPLACE FUNCTION SF_EMP_DATA
RETURN TYP_O
AS
TYP TYP_O;
BEGIN
SELECT TYP_OBJ(ENAME,EMPNO) BULK COLLECT INTO TYP FROM EMP;
RETURN TYP;
END;
Ex_2:
CREATE OR REPLACE PROCEDURE SP_OBJECT (P1 TYP_O, P2 OUT TYP_O)
AS
BEGIN
SELECT TYP_OBJ (ENAME,EMPNO) BULK COLLECT INTO X FROM EMP;
FOR I IN P1.COUNT LOOP;
DBMS_OUTPUT.PUT_LINE(P1(I).NAME ||' '||P1(I).SEAT_NO);
END LOOP;
END;
Trace file: Oracle will save the information trace file in certain time like last 30mins or last 2hrs
how many
programs has run and how much time they taken to run.
Then if you want to see the log file open my computer and type “ *.TRC ” in search bar then
trace files will be open but document format is not readable if you open the file it will be
displayed in binary format.
AZALEA MODEL:
REQUIREMENT GATHERING
DESIGN
IMPLEMENTATION/CODING
TESTING TEAM
They are preparing test cases before the project is coming to test.
Those test cases contain which, what kind of test they should do.
There are all programs working properly or not, all the errors what
we have raised for client requirement is that messages are same or not in
F.S.D, if any problem they will raise (BUJJ, ERRORS and ISSUES).
DEPLOYMENT/DELIVERY
After the completion of testing if there is any issues are not found
then our project will go to live. Means we are handover the project to
client.
MAINTENANCE
TRUNCATE DELETE
It removes all the rows from a table It can removes all rows or selected
rows
Where clause not support Where clause support
Max will picks the largest value Greatest will picks the highest
from given column and return in values from given columns and
single row return in a single column
Max can be used to go down the Greatest can be used across the row
column
Max gives one value in single row Greatest gives multiple rows and
return single column from given
multiple columns of data
HAVING WHERE
Once the data is grouped then we When want to put a condition on
want put a condition on that data we row data then we should go for
should go for the having clause where clause
SYNONYM VIEW
Synonym hide the original name of View is stored select statement
the object
It is alias name of the object
Always we can create synonym on a We can create view on multiple
single object objects
Synonym can create on views, tables, We can create views on tables,
procedures, functions views, synonyms
It will not hold the data physically on It will not hold the data physically
it on it
Whatever the changes your doing in Whatever the changes your doing in
original object it will impact on original object it will impact on
synonym, view,
Whatever the changes your doing on Whatever the changes your doing on
the synonym that will impact on the view that will impact on original
original object object
Select * from user_synonyms Select * from user_views
Unique key will allow any number of Primary key won’t allow null values
null values ( Unique Key +NOT NULL
= Primary Key)
We can create any number of unique We can create maximum one
constraints on a table primary key on a table
Automatically unique key index will Automatically primary key index
be create will be create
Unique key won’t allow duplicate Primary also won’t allow duplicate
values values and won’t allows null values
also
We can create only primary key on a We can create any number of foreign
table keys on a table
We can create primary key on any We can create foreign key constraint
column on any column but reference column
should be primary or unique
Blocks which is not have header That’s PL/SQL blocks which having
section are known as anonymous Header (or) Labels are known as
blocks ‘Named Blocks’
It cannot stores in database. It will stores in database. Whenever
We cannot recall anonymous blocks. you want to call you can the named
Means these are not reusable blocks. Means these are reusable.
It cannot allow any mode of It accepts the mode of parameters like
parameters in, out
It won’t return a value Subprograms called functions must
return a value
Need to compile every time when we Once you complied after compilation
execute. it is permanently stored as p-code in
the shared pool of the system global
area
We cannot call in any other block We can call it anywhere in the
schema.
We cannot permissions to other user We can give permissions to other
on unnamed blocks. users.
TABLE VIEW
Cursor fetching data record by record Bulk collect moves entire data in
single shot from SQL to PL/SQL
engine. But PL/SQL engine should
have collection variable.
SQL directly interacts with database PL/SQL does not directly interact
server with database server
SQL not have for loop, PL/SQL has for loop, while loop, if
if control and similar structures control and similar structures
SQL does not have variables PL/SQL has variables and data
types etc.,
SQL is data oriented language PL/SQL is application oriented
language
Mainly used manipulate data Mainly used to create an
application
FUNCTION PROCEDURE
Function we can call inside the select Procedure we can’t call inside
statement select statement
Function must return a value Procedure may or may not return a
value
We can use return statement in We can use return in procedure but
function this return will be terminate the
program
(this return statement not work like
function return statement)
We can use DML operation in We can use DML operations in
function but that the function we can’t procedure
call in inside the select statement
If we want call DML function in select We can’t call procedure in select
statement then pragma autonomous statement
transaction is require
Out parameter is not require in If you want retrieve something in
function because function must return procedure then out parameter is
a value require
If we use out parameter in function We can’t call procedure in select
then that function we can’t call inside statement
the select statement
TRIGGER PROCEDURE
TRIGGER CONSTRAINT
PROCEDURE PACKAGE
EXCEPTION SECTION:
EXCEPTION
WHEN OTHERS THEN
SP_ERROR_LOG ('SP_COMM_CAL',SQLCODE,SQLERRM,
SUBSTR (DBMS_UTILITY.format_error_backtrace,-5));
RAISE_APPLICATION_ERROR(-20400,SQLERRM);
END;
Cost: No. of hits to the database (means how many times it goes to database to bring the data).
Cardinality: How many records it’s searched.
Bytes: How much of area it’s searching for the data.
BEGIN
DBMS_PROFILER.start_profiler('SP_DATA_LOADINNG');
SP_DATA_LOADINNG;
DBMS_PROFILER.stop_profiler;
END;
Here
start_profiler, stop_profiler are procedures in the “DBMS_PROFILER”
package.
SP_DATA_LOADINNG is a individual profiler which is we want to know the run time
by using this package.
After executing this then we want to check the result then we want to result we should go
for that two tables join like:
Ex: SELECT A.TEXT, A.line, P.TOTAL_OCCUR, P.TOTAL_TIME/1000
FROM ALL_SOURCE A, PLSQL_PROFILER_DATA P
WHERE A.line=P.LINE# AND A.name='SP_OBJECTS_REPORT';
Trace file: Oracle will save the information trace file in certain time like last 30mins or
last 2hrs how many programs has run and how much time they taken to run.
Then if you want to see the log file open my computer and type “ *.TRC ” in search bar
then trace files will be open but document format is not readable if you open the file it will be
displayed in binary format.
Means:
In co-related sub one query result depends on another query result both are not individual
queries.
1st outer query will run and send the data to inner query.
Then inner query filter the data and send to outer query.
Then outer query will bring the output by using the result of inner query.
13. Difference between cursor for loop and for loop which is faster..?
For loop is faster. Because for loop mostly we are executed in the PL/SQL block /
PL/SQL engine but for cursor for loop two engines is required because it has select statement
need go for SQL engine and collect data from SQL engine. Means cursor for loop takes some
additional time for go and bring the data from SQL engine to PL/SQL engine.
%TYPE used to define variable according to specific column in data base table.
%ROWTYPE used to define, variable representing complete structure.
When we want to declare a variable and that variable data type should be particular column
data type in any table then we should go for %type.
When we want to declare a record representing a complete row of any table we should go for
%rowtype
(b). When you will go for explicit cursor and ref cursor..?
When you will go for implicit cursor..?
When we want to fetch the data from the tables in PL/SQL block into clause will fetch
one record only but we want to fetch more than one record we should go for the explicit cursor
or we can go for ref cursor.
Explicit cursor always associated with a single result set. Ref cursor will be
associated with the different result sets. If you want to fetch any table data one ref cursor should
be work for any table.
But we will go for the implicit cursor separate uses. When we are writing DML operation
in the PL/SQL block and we want to know is that DML is working or not and how many rows
are affected by that DML then compulsory we should go for implicit cursor.
DML TRIGGER: I want to do the validation after your going for the insert or update or
delete on the table then you go for the DML trigger.
Generally when we want to put a condition like ‘weekends you can’t insert or delete’ or
‘Fridays you can’t update on the table then you can go for the statement level trigger. Statement
level trigger mainly we use for avoid the transaction.
Row level trigger mainly we are using to maintain the audit. If you want to write rule or
restriction for particular rows data else if we are doing update statement what is the previous
value, what is the value after update if you want to maintain the audit for each DML operation
then you should go for the row level trigger.
Generally complex views won’t allow DML operations if you want to perform the DML
operation on complex views then you should go for the instead of trigger. Instead of trigger we
can use on complex views only.
These three or the DML triggers. DML triggers will be fired on insert, update, delete
only.
22. Write a PL/SQL block for trigger at the time of insertion, deleting, updating for inserting old
and new values auditing table..?
Note: For inserting there is no :OLD.VALUES only :NEW.VALUES are available,
For updating, deleting both :OLD.VALUES : NEW.VALUES are available.
BEGIN
X:=CASE WHEN :NEW.EMPNO IS NULL THEN :OLD.EMPNO ELSE :NEW.EMPNO END;
Y:= CASE WHEN INSERTING THEN 'INSERT' WHEN UPDATING THEN 'UPDATE' ELSE
'DELETE' END;
If any package have hundreds of procedures/functions and then if you calling only one
procedure in the package then entire package will come and store in the RAM means
unnecessarily package occupying the RAM memory.
Self join: Where joining same table it self is called ‘self join’.
When you want to print employee name along with their manager name then you
should go for self join.
SELECT W.ENAME, M.ENAME FROM EMP W, EMP M WHERE
W.MGR=M.EMPNO;
Cartesian join:
When you are fetching the data from 2 tables and you not putting any proper join
condition between 2 tables then it’s called cartesian/ cross join.
Ex: if you are fetching data from a and b table if you not putting any join condition
between A and B. if a table having M rows and B table having N rows then you will get the
output is =M*N rows;
To avoid we can go for join.
Mainly ‘=’ operator will support to pass only one value after ‘=’. But ‘IN’ will support to
pass list of values.
If you are calling P1,P2 procedure in P3 procedures and P3 having variables X,Y then
you are able to use that X,Y variables as parameters of in P1,P2 procedures. But you are not able
to use those variables as variables in P1,P2 procedures. If you want use then you have to declare
those X,Y variables in P1,P2 procedures also. Means we can use that P1 variables in P2, P3
procedure as in or out parameters only.
GNANA IT SOLUTIONS, VIZAG 129
27. What are the collections in PL/SQL..?
Generally whatever the variables we use number, varchar, date these are SQL variables
and these will be store one value at a time. If you want to store multiple rows you have to create
composite variables, Composite variables nothing but collection variables.
Mostly we use collection variable along with bulk collect concept. When we are using
bulk collect we will definitely need to write collection variable.
Varray table have a limit remaining nested, PL/SQL table doesn’t have a limit. But if you
going for the PL/SQL table index number is already exist when we want to store one by one
record into PL/SQL table no need to go for extend method because there is index number is
already exists we can directly put the values. But in nested/varray table we want put the one by
one record we have to go for the extend method. But when you are going for the bulk collect
concept there is no difference for nested, PL/SQL, varray. But for varray we have to know that
number of records already have and the limit of varray table.
28. (a) Which is the best method to kill the process in (unix, oracle)..?
Unix is best and faster method to kill the process.
SELECT U.OBJECT_NAME,V.SESSION_ID,S.SERIAL#,S.OSUSER
FROM USER_OBJECTS U, V$LOCKED_OBJECT V, V$SESSION S
WHERE U.OBJECT_ID=V.OBJECT_ID AND V.SESSION_ID=S.SID;
2nd way:
ALTER SYSTEM KILL SESSION '25,3563' IMMEDIATE
Here: 25 - Session id
3563 - Serial number.
Constant variable: If you are passing a constant value to a variable at the time of
declaration throughout the program that variable contain same value we are not able to change
the value of that variable these kind of variables are known as constant variables.
32. If we have both user exception and system exception and system exception which will be
handled first...?
It depends on the code. Exception you can write in any order.
1st you can write predefined exception or
1st you can write user defined exception or
1st you can write non-predefined exception
But if there is any when other exception that exception should be at end of the
program. For remaining there is no rule like that. You write any number of exceptions in
procedure.
You can able to write other exception after the when others exception but in this
case that when others exception is there in separate begin, end;
If you want to check how the application is working then you should go for
“dbms_profiler”. Means you want to check particular object working process and executing time
of the object/program. This program contain so many statements.
If you want to check execution plan of one statement then you should go for execution
plan (F5). Execution plan shows how the statement is executing like which join method it is
using or is this using index scan or not.
40. How to count number of records in the table without using count..?
SELECT MAX(R) FROM (SELECT ROWNUM R FROM EMP);
42. Select only those employees information who are earning same salary..?
SELECT * FROM EMP WHERE SAL IN (SELECT SAL FROM EMP GROUP BY SAL
HAVING COUNT(*)>1);
46. I have a row in a column as ‘RA@MA#NA$’, Now I want my output is ‘RAMANA’ how you
retrieve..?
SELECT regexp_replace ('RA@MA#NA$','\W') FROM DUAL;
If you are fetching single column then you can write normal variable. If you are fetching
entire row/table data you can write row type variable. If you are fetching the data by using bulk
collect then you have to write collection variable.
Cursor will fetch the data in two ways either into clause or either by using bulk collect
into. When we are go for bulk limit clause mostly we can go for the bulk collect into clause.
Bulk collect will fetch all the records at one shot. It will reduce the number context
switches from more to 1.
Means: Mutating error (ORA-04091) occurs whenever a row level trigger tries to modify or
select data from the table that is already undergoing change.
59. Which will fire default first statement level or row level trigger..?
It is based on what type of event you are written. In before case 1 st statement level trigger
will fire and after case 1st row level trigger will fire.
Trigger firing order:
Before statement level
Before row level
After row level
Before row level
After row level
After statement level.
65. How you give permission for packaged procedure to other user..?
For packaged procedure
GRANT EXECUTE ON PKG1.P1 TO RAMANA143;
GRANT EXECUTE ON PKG1 TO RAMANA143;
Instead of trigger:
CREATE OR REPLACE TRIGGER TRG_COMPLEX
INSTEAD OF UPDATE ON VW_EMP_DEPT FOR EACH ROW
BEGIN
UPDATE EMP
SET ENAME=:NEW.ENAME,EMPNO=:NEW.EMPNO,JOB=:NEW.JOB,SAL=:NEW.SAL,
DEPTNO=:NEW.DEPTNO WHERE EMPNO=:OLD.EMPNO;
SUBSTR:
SELECT SUBSTR(ENAME,1,3) FROM EMP;
SELECT SUBSTR(ENAME,3) FROM EMP;
INSTR:
SELECT INSTR('GOOD MORNING','O',2,3) FROM EMP;
Both column level and table level constraints are used put rule or restrictions.
Restrictions:
If you want to delete the data from master table 1 st you should delete corresponding
records from the child table. When you want to insert the data into child table that parent data
should be present in the parent table.
3. Generated as identity:
CREATE TABLE XYZ (A NUMBER GENERATED AS IDENTITY, B
VARCHAR2(30));
Ii is always starting with 1 and increment by 1.
There is no need to create a sequence separately.
If you write the key word “generated as identity” then its automatically
generates the numbers with increment of 1.
5. Varchar2 size:
Varchar2 size : 32767 (12c);
( up to 11g :4000)
5. Invisible indexes:
ALTER TABLE IDX_EMPNO VISIBLE;
ALTER INDEX IDEX_EMPNO INVISIBLE;
This is useful to disable the index for execute a query in a different join method.
6. Virtual column:
CREATE TABLE ABC(A NUMBER, B NUMBER, C NUMBER AS (A+B));
CREATE TABLE XYZ(X NUMBER, Y NUMBER, Z NUMBER, M NUMBER AS
(SF_GET_MAX(X,Y,Z)));
Note: Which function you want use in virtual column is should be deterministic function;
7. Continue statement:
BEGIN
FOR I IN 1..10 LOOP
IF I=5 THEN CONTINUE;
ELSE DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END;
It is replacement for ‘then null’ in some cases.
9. REGEXP_COUNT:
SELECT REGEXP_COUNT('GOOD MORNING','O') FROM DUAL;
----3 -(gives count of ‘o’ in ‘good morning’);
SELECT REGEXP_COUNT(ENAME,'A') FROM EMP;
----3 -(gives count a ‘a’ in each ename (each row) );
Differences:
o LISTAGG separate the records with different type special characters.
WM_CONCAT by default separate the records with comma only.
o We can use order by clause in LISTAGG for any column in the table.
We can use order by clause in WM_CONCAT for only column which is we used
to group by.
MATERIALIZED VIEW:
It is a stored select statement as well as it will store the data of the select statement. Means it
will store both select statement and data means it is data base object and it contains result of
the query. It may be local copy of the data or may be a sub set row and columns of table or
join result.
o The log store the script of changes what you have apply commit after until you apply the
commit after the commit the log will apply the same changes on the view.
o That primary key helps to store the changes order wise in log .That’s why both log and
primary key are compulsory for refresh fast on commit method of materialized view.
B-tree index will separate the data into leaf blocks to make data searching easier. B-tree
index contain root, branch, leaf blocks, root blocks, branch blocks contain directions and leaf
blocks contain the data.
ROUTE BLOCK
1-15
16-30
1 6 11 16 21 26
2 7 12 LEAF BLOCKS 17 22 27
3 8 13 18 23 28
4 9 14 19 24 29
5 10 15 20 25 30
B1 B2 B3 B4 B5 B6
UNIQUE INDEX:
CREATE UNIQUE INDEX IDX_EMPNO ON EMP(EMPNO) TABLESPACE
RAMANA_INDEXES;
Unique index also works like b-tree index but small differences is there, in b-tree index
even searching record founded then also it verifies next row for confirmation of is same record
exists in next row if not found then it will bring data from table by using founded rowid’s.
But in unique index if searching record is found then immediately its go and bring the
data from the table by using the only one rowid. There is no chance to go and search in next
row for same record because unique index blindly follows that column does not contain any
duplicate values.
When we are creating unique or primary key constraints on any column automatically
unique index will be created.
ROUTE BLOCK
TOTAL SAL (1-30,000)
2,000 (rowid) 11,000 (rowid) 24,000 (rowid) 31,000 (rowid) 41,000 (rowid) 51,100 (rowid)
2,500 (rowid) 12,500 (rowid) 25,500 (rowid) 35,500 (rowid) 46,500 (rowid) 53,500 (rowid)
4,500 (rowid) 14,500 (rowid) 25,500 (rowid) 35,800 (rowid) 47,800 (rowid) 58,800 (rowid)
4,500 (rowid) 18,000 (rowid) 28,000 (rowid) 39,000 (rowid) 48,000 (rowid) 59,000 (rowid)
7,000 (rowid) 18,000 (rowid) 30,000 (rowid) 39,500 (rowid) 49,500 (rowid) 59,500 (rowid)
B1 B2 B3 B4 B5 B6
If you are not given any temporary table space at the time of schema creation system will
use default temporary table space. Oracle will provide a temporary table space by default.
110. How will you connect to the servers from your PC..?
Go to run
Enter IP address of server
Ex: 10.1.46.224
Enter your user id, password.
To user
SQL command window
Show user
126. What is cursor..? Using cursor how you increase the salary of employees by 15% whose
salary is greater than 20,000.
Cursor is a private area created by PL/SQL block when we are fetching the data by using
cursor select statement that data will be stored in some area that area is called cursor.
DECLARE
CURSOR C1 IS SELECT * FROM EMP WHERE SAL>20000;
SAL_2 EMP.SAL%TYPE;
BEGIN
OPEN C1
LOOP
FETCH C1 IN SAL_2;
UPDATE EMP SET SAL=SAL+(SAL_2*20/100);
EXIT WHEN C1% NOT FOUND;
END LOOP;
CLOSE C1;
END;
Function:
Open SQL command window.
> EXEC :X:=SF_OTP;
Procedure:
> Variable X number;
> EXEC SP_CAL (10,20, :X);
136. What is partition..? Why you go for partitions and write the syntax..?
Partition will divide larger table data into smaller more manageable pieces. Partition
allows tables, indexes and index organized table to be sub divide into smaller pieces.
If table having huge amount of data or table having more than 2GB then even if you are
going for the index also may be system will give slow performance because table having huge
amount of data it’s very difficult to finding the record by using index then if you going for the
partition then it will divided into smaller more manageable pieces then one partition has one type
of data another partition having another type of data tomorrow we are updating, selecting,
deleting the data directly it will go for that partition area where that record is exists.
137. Difference between unique index and primary key/ unique key constrains unique index..?
If we inserting duplicate values on that column:
Unique key/Primary key constraints show the error
“Unique key constraint violated”.
144. ‘SELECT COUNT (*) FROM EMP WHERE ROWNUM>2’ what is the output..?
ROWNUM won’t support ‘>’ operator. But is supports to ‘<, <=, =, >=’.
145. If there are two after insert triggers on a table for each row which will be fired first..?
Recently written trigger will fire first.
146. ‘SELECT SEQ_1.CURRVAL FROM DUAL’ what will be the value when the session opens..?
It gives error because without using nextval we cannot use currval.
Error: (ORA-08002 sequence seq_1.currval is not yet defined in this session).
149. If there are three users. If U1 gives permission on how will you give that to U1 and how U2
can grant permission to U3..?
If U1 gives all permissions to U2 like: GRANT ALL ON EMP TO U2;
Then U2 can give any permission on that object to another user
like: GRANT SELECT ON EMP TO U2;
151. until run time you don’t know the table name to select a query which method you should
fallow..?
When we are fetching the data from the table and which table we are fetching we don’t
know then we should go for ref cursor.
Else if table name they are passing dynamically then we should go for dynamic SQL (or)
ref cursor.
Ex: CREATE OR REPLACE PROCEDURE SP_1 (P_TABLE VARCHAR2,P_COL VARCHAR2)
AS
X NUMBER;
LV_QUERY VARCHAR2 (1000);
BEGIN
LV_QUERY:= 'SELECT '||P_COL||' FROM '||P_TABLE||
' WHERE ROWNUM=1';
EXECUTE IMMEDIATE LV_QUERY INTO X;
END;
Cursors:
Invalid cursor.
Cursor already open.
Triggers:
Mutating error.
Recursive error.
AZALEA MODEL:
DESIGN Architectures
IMPLEMENTATION/CODING Developers
PRAGMA + TCL
BEFORE EVENT AFTER EVENT
STATEMENT ACTION ERROR STATEMENT ACTION ERROR
INSERT INSERT RECURSIVE INSERT INSERT RECURSIVE
UPDATE NO ISSUE UPDATE NO ISSUE
DELETE NO ISSUE DELETE NO ISSUE
SELECT NO ISSUE SELECT NO ISSUE
------------------------------------------------
1.TYPES OF SQL COMMANDS (5)
1.DDL (DATA DEFINITION LAN)
CREATE, ALTER (ADD, MODIFY, DROP), DROP TRUNCATE.
CREATE table tablename (rollno number(5), name varchar2(20),dob
date);
ALTER table tabalename ADD age number (3)
ALTER table tablename MODIFY name varchar2(30)
ALTER table tablename DROP column dob (----- particular column)
DROP table tablename
Truncate table tablename---pernminently delete no rollback.