SlideShare a Scribd company logo
1 of 13
What is SQL and where does it come from? 
Structured Query Language (SQL) is a language that provides an interface to relational database 
systems. SQL was developed by IBM in the 1970s for use in System R, and is a de facto 
standard, as well as an ISO and ANSI standard. SQL is often pronounced SEQUEL. 
In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs, 
UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying 
tables and other database structures. 
-------------------------------------------------------------------------------- 
What are the difference between DDL, DML and DCL commands? 
DDL is Data Definition Language statements. Some examples: 
CREATE - to create objects in the database 
ALTER - alters the structure of the database 
DROP - delete objects from the database 
TRUNCATE - remove all records from a table, including all spaces allocated for the records are 
removed 
COMMENT - add comments to the data dictionary 
GRANT - gives user's access privileges to database 
REVOKE - withdraw access privileges given with the GRANT command 
DML is Data Manipulation Language statements. Some examples: 
SELECT - retrieve data from the a database 
INSERT - insert data into a table 
UPDATE - updates existing data within a table 
DELETE - deletes all records from a table, the space for the records remain 
CALL - call a PL/SQL or Java subprogram 
EXPLAIN PLAN - explain access path to data 
LOCK TABLE - control concurrency 
DCL is Data Control Language statements. Some examples: 
COMMIT - save work done 
SAVEPOINT - identify a point in a transaction to which you can later roll back 
ROLLBACK - restore database to original since the last COMMIT 
SET TRANSACTION - Change transaction options like what rollback segment to use 
-------------------------------------------------------------------------------- 
How can I eliminate duplicates values in a table? 
Choose one of the following queries to identify or remove duplicate rows from a table leaving 
one record: 
Method 1: 
SQL> DELETE FROM table_name A WHERE ROWID > ( 
2 SELECT min(rowid) FROM table_name B
3 WHERE A.key_values = B.key_values); 
Method 2: 
SQL> create table table_name2 as select distinct * from table_name1; 
SQL> drop table_name1; 
SQL> rename table_name2 to table_name1; 
Method 3: 
SQL> Delete from my_table where rowid not in( 
SQL> select max(rowid) from my_table 
SQL> group by my_column_name ); 
Method 4: 
SQL> delete from my_table t1 
SQL> where exists (select 'x' from my_table t2 
SQL> where t2.key_value1 = t1.key_value1 
SQL> and t2.key_value2 = t1.key_value2 
SQL> and t2.rowid > t1.rowid); 
-------------------------------------------------------------------------------- 
How can I generate primary key values for my table? 
Create your table with a NOT NULL column (say SEQNO). This column can now be populated 
with unique values: 
SQL> UPDATE table_name SET seqno = ROWNUM; 
or use a sequences generator: 
SQL> CREATE SEQUENCE sequence_name START WITH 1 INCREMENT BY 1; 
SQL> UPDATE table_name SET seqno = sequence_name.NEXTVAL; 
Finally, create a unique index on this column. 
-------------------------------------------------------------------------------- 
How can I get the time difference between two date columns 
Look at this example query: 
select floor(((date1-date2)*24*60*60)/3600) 
|| ' HOURS ' || 
floor((((date1-date2)*24*60*60) - 
floor(((date1-date2)*24*60*60)/3600)*3600)/60) 
|| ' MINUTES ' || 
round((((date1-date2)*24*60*60) - 
floor(((date1-date2)*24*60*60)/3600)*3600 - 
(floor((((date1-date2)*24*60*60) - 
floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60))) 
|| ' SECS ' time_difference
from ... 
-------------------------------------------------------------------------------- 
How does one count different data values in a column? 
select dept, sum( decode(sex,'M',1,0)) MALE, 
sum( decode(sex,'F',1,0)) FEMALE, 
count(decode(sex,'M',1,'F',1)) TOTAL 
from my_emp_table 
group by dept; 
-------------------------------------------------------------------------------- 
How does one count/sum RANGES of data values in a column? 
A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z). Look at this 
example: 
select f2, 
sum(decode(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100", 
sum(decode(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59", 
sum(decode(greatest(f1, 0), least(f1, 29), 1, 0)) "Range 00-29" 
from my_table 
group by f2; 
For equal size ranges it might be easier to calculate it with DECODE(TRUNC(value/range), 0, 
rate_0, 1, rate_1, ...). Eg. 
select ename "Name", sal "Salary", 
decode( trunc(f2/1000, 0), 0, 0.0, 
1, 0.1, 
2, 0.2, 
3, 0.31) "Tax rate" 
from my_table; 
-------------------------------------------------------------------------------- 
Can one retrieve only the Nth row from a table? 
SELECT f1 FROM t1 
WHERE rowid = ( 
SELECT rowid FROM t1 
WHERE rownum <= 10 
MINUS 
SELECT rowid FROM t1 
WHERE rownum < 10); 
Alternatively... 
SELECT * FROM emp WHERE rownum=1 AND rowid NOT IN 
(SELECT rowid FROM emp WHERE rownum < 10);
Please note, there is no explicit row order in a relational database. However, this query is quite 
fun and may even help in the odd situation. 
-------------------------------------------------------------------------------- 
Can one retrieve only rows X to Y from a table? 
To display rows 5 to 7, construct a query like this: 
SELECT * 
FROM tableX 
WHERE rowid in ( 
SELECT rowid FROM tableX 
WHERE rownum <= 7 
MINUS 
SELECT rowid FROM tableX 
WHERE rownum < 5); 
Please note, there is no explicit row order in a relational database. However, this query is quite 
fun and may even help in the odd situation. 
-------------------------------------------------------------------------------- 
How does one select EVERY Nth row from a table? 
One can easily select all even, odd, or Nth rows from a table using SQL queries like this: 
Method 1: Using a subquery 
SELECT * 
FROM emp 
WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4) 
FROM emp); 
Method 2: Use dynamic views (available from Oracle7.2): 
SELECT * 
FROM ( SELECT rownum rn, empno, ename 
FROM emp 
) temp 
WHERE MOD(temp.ROWNUM,4) = 0; 
Please note, there is no explicit row order in a relational database. However, these queries are 
quite fun and may even help in the odd situation. 
--------------------------------------------------------------------------------
How does one select the TOP N rows from a table? 
Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this example: 
SELECT * 
FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC) 
WHERE ROWNUM < 10; 
Use this workaround with prior releases: 
SELECT * 
FROM my_table a 
WHERE 10 >= (SELECT COUNT(DISTINCT maxcol) 
FROM my_table b 
WHERE b.maxcol >= a.maxcol) 
ORDER BY maxcol DESC; 
-------------------------------------------------------------------------------- 
How does one code a tree-structured query? 
Tree-structured queries are definitely non-relational (enough to kill Codd and make him roll in 
his grave). Also, this feature is not often found in other database offerings. 
The SCOTT/TIGER database schema contains a table EMP with a self-referencing relation 
(EMPNO and MGR columns). This table is perfect for tesing and demonstrating tree-structured 
queries as the MGR column contains the employee number of the "current" employee's boss. 
The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle can handle 
queries with a depth of up to 255 levels. Look at this example: 
select LEVEL, EMPNO, ENAME, MGR 
from EMP 
connect by prior EMPNO = MGR 
start with MGR is NULL; 
One can produce an indented report by using the level number to substring or lpad() a series of 
spaces, and concatenate that to the string. Look at this example: 
select lpad(' ', LEVEL * 2) || ENAME ........ 
One uses the "start with" clause to specify the start of the tree. More than one record can match 
the starting condition. One disadvantage of having a "connect by prior" clause is that you cannot 
perform a join to other tables. The "connect by prior" clause is rarely implemented in the other 
database offerings. Trying to do this programmatically is difficult as one has to do the top level 
query first, then, for each of the records open a cursor to look for child nodes. 
One way of working around this is to use PL/SQL, open the driving cursor with the "connect by 
prior" statement, and the select matching records from other tables on a row-by-row basis, 
inserting the results into a temporary table for later retrieval.
-------------------------------------------------------------------------------- 
How does one code a matrix report in SQL? 
Look at this example query with sample output: 
SELECT * 
FROM (SELECT job, 
sum(decode(deptno,10,sal)) DEPT10, 
sum(decode(deptno,20,sal)) DEPT20, 
sum(decode(deptno,30,sal)) DEPT30, 
sum(decode(deptno,40,sal)) DEPT40 
FROM scott.emp 
GROUP BY job) 
ORDER BY 1; 
JOB DEPT10 DEPT20 DEPT30 DEPT40 
--------- ---------- ---------- ---------- ---------- 
ANALYST 6000 
CLERK 1300 1900 950 
MANAGER 2450 2975 2850 
PRESIDENT 5000 
SALESMAN 5600 
-------------------------------------------------------------------------------- 
How does one implement IF-THEN-ELSE in a select statement? 
The Oracle decode function acts like a procedural statement inside an SQL statement to return 
different values or columns based on the values of other columns in the select statement. 
Some examples: 
select decode(sex, 'M', 'Male', 
'F', 'Female', 
'Unknown') 
from employees; 
select a, b, decode( abs(a-b), a-b, 'a > b', 
0, 'a = b', 
'a < b') 
from tableX; 
select decode( GREATEST(A,B), A, 'A is greater than B', 'B is greater than A')... 
Note: The decode function is not ANSI SQL and is rarely implemented in other RDBMS 
offerings. It is one of the good things about Oracle, but use it sparingly if portability is required.
From Oracle 8i one can also use CASE statements in SQL. Look at this example: 
SELECT ename, CASE WHEN sal>1000 THEN 'Over paid' ELSE 'Under paid' END 
FROM emp; 
-------------------------------------------------------------------------------- 
How can one dump/ examine the exact content of a database column? 
SELECT DUMP(col1) 
FROM tab1 
WHERE cond1 = val1; 
DUMP(COL1) 
------------------------------------- 
Typ=96 Len=4: 65,66,67,32 
For this example the type is 96, indicating CHAR, and the last byte in the column is 32, which is 
the ASCII code for a space. This tells us that this column is blank-padded. 
-------------------------------------------------------------------------------- 
Can one drop a column from a table? 
From Oracle8i one can DROP a column from a table. Look at this sample script, demonstrating 
the ALTER TABLE table_name DROP COLUMN column_name; command. 
With previous releases one can use Joseph S. Testa's DROP COLUMN package that can be 
downloaded from http://www.oracle-dba.com/ora_scr.htm. 
Other workarounds: 
1. SQL> update t1 set column_to_drop = NULL; 
SQL> rename t1 to t1_base; 
SQL> create view t1 as select <specific columns> from t1_base; 
2. SQL> create table t2 as select <specific columns> from t1; 
SQL> drop table t1; 
SQL> rename t2 to t1; 
-------------------------------------------------------------------------------- 
Can one rename a column in a table? 
No, this is listed as Enhancement Request 163519. Some workarounds: 
1. -- Use a view with correct column names...
rename t1 to t1_base; 
create view t1 <column list with new name> as select * from t1_base; 
2. -- Recreate the table with correct column names... 
create table t2 <column list with new name> as select * from t1; 
drop table t1; 
rename t2 to t1; 
3. -- Add a column with a new name and drop an old column... 
alter table t1 add ( newcolame datatype ); 
update t1 set newcolname=oldcolname; 
alter table t1 drop column oldcolname; 
-------------------------------------------------------------------------------- 
How can I change my Oracle password? 
Issue the following SQL command: ALTER USER <username> IDENTIFIED BY 
<new_password> 
/ 
From Oracle8 you can just type "password" from SQL*Plus, or if you need to change another 
user's password, type "password user_name". 
-------------------------------------------------------------------------------- 
How does one find the next value of a sequence? 
Perform an "ALTER SEQUENCE ... NOCACHE" to unload the unused cached sequence 
numbers from the Oracle library cache. This way, no cached numbers will be lost. If you then 
select from the USER_SEQUENCES dictionary view, you will see the correct high water mark 
value that would be returned for the next NEXTVALL call. Afterwards, perform an "ALTER 
SEQUENCE ... CACHE" to restore caching. 
You can use the above technique to prevent sequence number loss before a SHUTDOWN 
ABORT, or any other operation that would cause gaps in sequence values. 
-------------------------------------------------------------------------------- 
Workaround for snapshots on tables with LONG columns 
You can use the SQL*Plus COPY command instead of snapshots if you need to copy LONG and 
LONG RAW variables from one location to another. Eg:
COPY TO SCOTT/TIGER@REMOTE - 
CREATE IMAGE_TABLE USING - 
SELECT IMAGE_NO, IMAGE - 
FROM IMAGES; 
Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated. 
-------------------------------------------------------------------------------- 
Oracle Interview Questions and Answers : SQL 
1. To see current user name 
Sql> show user; 
2. Change SQL prompt name 
SQL> set sqlprompt “Manimara > “ 
Manimara > 
Manimara > 
3. Switch to DOS prompt 
SQL> host 
4. How do I eliminate the duplicate rows ? 
SQL> delete from table_name where rowid not in (select max(rowid) from table group by 
duplicate_values_field_name); 
or 
SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select 
min(rowid) from table_name tb where ta.dv=tb.dv); 
Example. 
Table Emp 
Empno Ename 
101 Scott 
102 Jiyo 
103 Millor 
104 Jiyo 
105 Smith
delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = 
b.ename); 
The output like, 
Empno Ename 
101 Scott 
102 Millor 
103 Jiyo 
104 Smith 
5. How do I display row number with records? 
To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename 
from emp; 
Output: 
1 Scott 
2 Millor 
3 Jiyo 
4 Smith 
6. Display the records between two range 
select rownum, empno, ename from emp where rowid in 
(select rowid from emp where rownum <=&upto 
minus 
select rowid from emp where rownum<&Start); 
Enter value for upto: 10 
Enter value for Start: 7 
ROWNUM EMPNO ENAME 
--------- --------- ---------- 
1 7782 CLARK 
2 7788 SCOTT 
3 7839 KING 
4 7844 TURNER 
7. I know the nvl function only allows the same data type(ie. number or char or date 
Nvl(comm, 0)), if commission is null then the text “Not Applicable” want to display, 
instead of blank space. How do I write the query? 
SQL> select nvl(to_char(comm.),'NA') from emp; 
Output : 
NVL(TO_CHAR(COMM),'NA') 
----------------------- 
NA 
300 
500
NA 
1400 
NA 
NA 
8. Oracle cursor : Implicit & Explicit cursors 
Oracle uses work areas called private SQL areas to create SQL statements. 
PL/SQL construct to identify each and every work are used, is called as Cursor. 
For SQL queries returning a single row, PL/SQL declares all implicit cursors. 
For queries that returning more than one row, the cursor needs to be explicitly declared. 
9. Explicit Cursor attributes 
There are four cursor attributes used in Oracle 
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name 
%ISOPEN 
10. Implicit Cursor attributes 
Same as explicit cursor but prefixed by the word SQL 
SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN 
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor 
after executing SQL statements. 
: 2. All are Boolean attributes. 
11. Find out nth highest salary from emp table 
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT 
(b.sal)) FROM EMP B WHERE a.sal<=b.sal); 
Enter value for n: 2 
SAL 
--------- 
3700 
12. To view installed Oracle version information 
SQL> select banner from v$version; 
13. Display the number value in Words 
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) 
from emp; 
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) 
--------- ----------------------------------------------------- 
800 eight hundred 
1600 one thousand six hundred 
1250 one thousand two hundred fifty 
If you want to add some text like, 
Rs. Three Thousand only. 
SQL> select sal "Salary ", 
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) 
"Sal in Words" from emp 
/ 
Salary Sal in Words 
------- ------------------------------------------------------ 
800 Rs. Eight Hundred only. 
1600 Rs. One Thousand Six Hundred only. 
1250 Rs. One Thousand Two Hundred Fifty only. 
14. Display Odd/ Even number of records 
Odd number of records: 
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp); 
1 
3 
5 
Even number of records: 
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp) 
2 
4 
6 
15. Which date function returns number value? 
months_between 
16. Any three PL/SQL Exceptions? 
Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others 
17. What are PL/SQL Cursor Exceptions? 
Cursor_Already_Open, Invalid_Cursor 
18. Other way to replace query result null value with a text 
SQL> Set NULL ‘N/A’ 
to reset SQL> Set NULL ‘’ 
19. What are the more common pseudo-columns?
SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM 
20. What is the output of SIGN function? 
1 for positive value, 
0 for Zero, 
-1 for Negative value. 
21. What is the maximum number of triggers, can apply to a single table? 
12 triggers. 
--------------------------------------------------------------------------------

More Related Content

What's hot

Most useful queries
Most useful queriesMost useful queries
Most useful queries
Sam Depp
 
Database Oracle Basic
Database Oracle BasicDatabase Oracle Basic
Database Oracle Basic
Kamlesh Singh
 

What's hot (20)

Adapting to Adaptive Plans on 12c
Adapting to Adaptive Plans on 12cAdapting to Adaptive Plans on 12c
Adapting to Adaptive Plans on 12c
 
Mysql quick guide
Mysql quick guideMysql quick guide
Mysql quick guide
 
Most useful queries
Most useful queriesMost useful queries
Most useful queries
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 
Oracle 9i notes(kamal.love@gmail.com)
Oracle 9i  notes(kamal.love@gmail.com)Oracle 9i  notes(kamal.love@gmail.com)
Oracle 9i notes(kamal.love@gmail.com)
 
12c SQL Plan Directives
12c SQL Plan Directives12c SQL Plan Directives
12c SQL Plan Directives
 
dbms lab manual
dbms lab manualdbms lab manual
dbms lab manual
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
Database Oracle Basic
Database Oracle BasicDatabase Oracle Basic
Database Oracle Basic
 
Sql 
statements , functions & joins
Sql 
statements , functions  &  joinsSql 
statements , functions  &  joins
Sql 
statements , functions & joins
 
Star Transformation, 12c Adaptive Bitmap Pruning and In-Memory option
Star Transformation, 12c Adaptive Bitmap Pruning and In-Memory optionStar Transformation, 12c Adaptive Bitmap Pruning and In-Memory option
Star Transformation, 12c Adaptive Bitmap Pruning and In-Memory option
 
Quick reference for mongo shell commands
Quick reference for mongo shell commandsQuick reference for mongo shell commands
Quick reference for mongo shell commands
 
Full Table Scan: friend or foe
Full Table Scan: friend or foeFull Table Scan: friend or foe
Full Table Scan: friend or foe
 
Things you should know about Oracle truncate
Things you should know about Oracle truncateThings you should know about Oracle truncate
Things you should know about Oracle truncate
 
Sql 3
Sql 3Sql 3
Sql 3
 
Oracle training in hyderabad
Oracle training in hyderabadOracle training in hyderabad
Oracle training in hyderabad
 
Checking clustering factor to detect row migration
Checking clustering factor to detect row migrationChecking clustering factor to detect row migration
Checking clustering factor to detect row migration
 
12c Mini Lesson - Invisible Columns
12c Mini Lesson - Invisible Columns12c Mini Lesson - Invisible Columns
12c Mini Lesson - Invisible Columns
 
Dbms plan - A swiss army knife for performance engineers
Dbms plan - A swiss army knife for performance engineersDbms plan - A swiss army knife for performance engineers
Dbms plan - A swiss army knife for performance engineers
 

Viewers also liked

Pc 811 transformation_guide
Pc 811 transformation_guidePc 811 transformation_guide
Pc 811 transformation_guide
Venkat Madduru
 
методика обчислення основних показників діяльності лікувальних установ акушер...
методика обчислення основних показників діяльності лікувальних установ акушер...методика обчислення основних показників діяльності лікувальних установ акушер...
методика обчислення основних показників діяльності лікувальних установ акушер...
Igor Nitsovych
 
Ies la mola iris y cynthia
Ies la mola iris y cynthiaIes la mola iris y cynthia
Ies la mola iris y cynthia
iesMola
 
цсноп 2 11_3_проект памяти
цсноп 2 11_3_проект памятицсноп 2 11_3_проект памяти
цсноп 2 11_3_проект памяти
Irina Hahanova
 
Boda en etla
Boda en etlaBoda en etla
Boda en etla
vedmoga
 
Cau chuyen hoa hoc (phan 2)
Cau chuyen hoa hoc (phan 2)Cau chuyen hoa hoc (phan 2)
Cau chuyen hoa hoc (phan 2)
vjt_chjen
 
Sat -mrphong12
Sat -mrphong12Sat -mrphong12
Sat -mrphong12
vjt_chjen
 
Media question 2
Media question 2Media question 2
Media question 2
samiii1994
 
апкс 2011 02_verilog
апкс 2011 02_verilogапкс 2011 02_verilog
апкс 2011 02_verilog
Irina Hahanova
 

Viewers also liked (20)

Autosys Complete Guide
Autosys Complete GuideAutosys Complete Guide
Autosys Complete Guide
 
Pc 811 transformation_guide
Pc 811 transformation_guidePc 811 transformation_guide
Pc 811 transformation_guide
 
Autosys
AutosysAutosys
Autosys
 
Essbase intro
Essbase introEssbase intro
Essbase intro
 
Hamlet
HamletHamlet
Hamlet
 
Thesis Presentation 2.1.11
Thesis Presentation 2.1.11Thesis Presentation 2.1.11
Thesis Presentation 2.1.11
 
методика обчислення основних показників діяльності лікувальних установ акушер...
методика обчислення основних показників діяльності лікувальних установ акушер...методика обчислення основних показників діяльності лікувальних установ акушер...
методика обчислення основних показників діяльності лікувальних установ акушер...
 
Ies la mola iris y cynthia
Ies la mola iris y cynthiaIes la mola iris y cynthia
Ies la mola iris y cynthia
 
цсноп 2 11_3_проект памяти
цсноп 2 11_3_проект памятицсноп 2 11_3_проект памяти
цсноп 2 11_3_проект памяти
 
Boda en etla
Boda en etlaBoda en etla
Boda en etla
 
RevRev Manufacturing
RevRev Manufacturing RevRev Manufacturing
RevRev Manufacturing
 
History of Earthquake
History of EarthquakeHistory of Earthquake
History of Earthquake
 
Cau chuyen hoa hoc (phan 2)
Cau chuyen hoa hoc (phan 2)Cau chuyen hoa hoc (phan 2)
Cau chuyen hoa hoc (phan 2)
 
Sat -mrphong12
Sat -mrphong12Sat -mrphong12
Sat -mrphong12
 
Gcpug begginers #1LT startup scriptとshutdown script
Gcpug begginers #1LT startup scriptとshutdown scriptGcpug begginers #1LT startup scriptとshutdown script
Gcpug begginers #1LT startup scriptとshutdown script
 
Office plots 2014 sept paper 4 co150
Office plots 2014 sept paper 4 co150Office plots 2014 sept paper 4 co150
Office plots 2014 sept paper 4 co150
 
Media question 2
Media question 2Media question 2
Media question 2
 
Festivalul Mondial al Culturii
Festivalul Mondial al CulturiiFestivalul Mondial al Culturii
Festivalul Mondial al Culturii
 
апкс 2011 02_verilog
апкс 2011 02_verilogапкс 2011 02_verilog
апкс 2011 02_verilog
 
Kerr center for sustainable agriculture summary overview
Kerr center for sustainable agriculture summary overview Kerr center for sustainable agriculture summary overview
Kerr center for sustainable agriculture summary overview
 

Similar to SQLQueries

Advanced tips of dbms statas
Advanced tips of dbms statasAdvanced tips of dbms statas
Advanced tips of dbms statas
Louis liu
 
Understanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
Understanding Query Optimization with ‘regular’ and ‘Exadata’ OracleUnderstanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
Understanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
Guatemala User Group
 
Database & Technology 1 _ Tom Kyte _ SQL Techniques.pdf
Database & Technology 1 _ Tom Kyte _ SQL Techniques.pdfDatabase & Technology 1 _ Tom Kyte _ SQL Techniques.pdf
Database & Technology 1 _ Tom Kyte _ SQL Techniques.pdf
InSync2011
 
Intro to tsql unit 3
Intro to tsql   unit 3Intro to tsql   unit 3
Intro to tsql unit 3
Syed Asrarali
 

Similar to SQLQueries (20)

Oracle Join Methods and 12c Adaptive Plans
Oracle Join Methods and 12c Adaptive PlansOracle Join Methods and 12c Adaptive Plans
Oracle Join Methods and 12c Adaptive Plans
 
Sql interview questions
Sql interview questionsSql interview questions
Sql interview questions
 
SQL-8 Table Creation.pdf
SQL-8 Table Creation.pdfSQL-8 Table Creation.pdf
SQL-8 Table Creation.pdf
 
Advanced tips of dbms statas
Advanced tips of dbms statasAdvanced tips of dbms statas
Advanced tips of dbms statas
 
Oracle 11g caracteristicas poco documentadas 3 en 1
Oracle 11g caracteristicas poco documentadas 3 en 1Oracle 11g caracteristicas poco documentadas 3 en 1
Oracle 11g caracteristicas poco documentadas 3 en 1
 
Oracle 12c SPM
Oracle 12c SPMOracle 12c SPM
Oracle 12c SPM
 
Managing Statistics for Optimal Query Performance
Managing Statistics for Optimal Query PerformanceManaging Statistics for Optimal Query Performance
Managing Statistics for Optimal Query Performance
 
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
[Pgday.Seoul 2019] Citus를 이용한 분산 데이터베이스
 
Understanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
Understanding Query Optimization with ‘regular’ and ‘Exadata’ OracleUnderstanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
Understanding Query Optimization with ‘regular’ and ‘Exadata’ Oracle
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
SQL
SQLSQL
SQL
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorial
 
Database & Technology 1 _ Tom Kyte _ SQL Techniques.pdf
Database & Technology 1 _ Tom Kyte _ SQL Techniques.pdfDatabase & Technology 1 _ Tom Kyte _ SQL Techniques.pdf
Database & Technology 1 _ Tom Kyte _ SQL Techniques.pdf
 
Oracle Database 12c Application Development
Oracle Database 12c Application DevelopmentOracle Database 12c Application Development
Oracle Database 12c Application Development
 
Explaining the Postgres Query Optimizer
Explaining the Postgres Query OptimizerExplaining the Postgres Query Optimizer
Explaining the Postgres Query Optimizer
 
Intro to tsql unit 3
Intro to tsql   unit 3Intro to tsql   unit 3
Intro to tsql unit 3
 
Intro To TSQL - Unit 3
Intro To TSQL - Unit 3Intro To TSQL - Unit 3
Intro To TSQL - Unit 3
 
Informix Warehouse Accelerator (IWA) features in version 12.1
Informix Warehouse Accelerator (IWA) features in version 12.1Informix Warehouse Accelerator (IWA) features in version 12.1
Informix Warehouse Accelerator (IWA) features in version 12.1
 
Connor McDonald 11g for developers
Connor McDonald 11g for developersConnor McDonald 11g for developers
Connor McDonald 11g for developers
 
SQL/MX 3.6 Select for update feature
SQL/MX 3.6 Select for update featureSQL/MX 3.6 Select for update feature
SQL/MX 3.6 Select for update feature
 

More from karunakar81987 (7)

Introduction to Datawarehousing
Introduction to  DatawarehousingIntroduction to  Datawarehousing
Introduction to Datawarehousing
 
Frame 12
Frame 12Frame 12
Frame 12
 
Frame2
Frame2Frame2
Frame2
 
Frame
FrameFrame
Frame
 
Atm
AtmAtm
Atm
 
11 atm
11 atm11 atm
11 atm
 
Frame relay
Frame relayFrame relay
Frame relay
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

SQLQueries

  • 1. What is SQL and where does it come from? Structured Query Language (SQL) is a language that provides an interface to relational database systems. SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO and ANSI standard. SQL is often pronounced SEQUEL. In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables and other database structures. -------------------------------------------------------------------------------- What are the difference between DDL, DML and DCL commands? DDL is Data Definition Language statements. Some examples: CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed COMMENT - add comments to the data dictionary GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command DML is Data Manipulation Language statements. Some examples: SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain CALL - call a PL/SQL or Java subprogram EXPLAIN PLAN - explain access path to data LOCK TABLE - control concurrency DCL is Data Control Language statements. Some examples: COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMIT SET TRANSACTION - Change transaction options like what rollback segment to use -------------------------------------------------------------------------------- How can I eliminate duplicates values in a table? Choose one of the following queries to identify or remove duplicate rows from a table leaving one record: Method 1: SQL> DELETE FROM table_name A WHERE ROWID > ( 2 SELECT min(rowid) FROM table_name B
  • 2. 3 WHERE A.key_values = B.key_values); Method 2: SQL> create table table_name2 as select distinct * from table_name1; SQL> drop table_name1; SQL> rename table_name2 to table_name1; Method 3: SQL> Delete from my_table where rowid not in( SQL> select max(rowid) from my_table SQL> group by my_column_name ); Method 4: SQL> delete from my_table t1 SQL> where exists (select 'x' from my_table t2 SQL> where t2.key_value1 = t1.key_value1 SQL> and t2.key_value2 = t1.key_value2 SQL> and t2.rowid > t1.rowid); -------------------------------------------------------------------------------- How can I generate primary key values for my table? Create your table with a NOT NULL column (say SEQNO). This column can now be populated with unique values: SQL> UPDATE table_name SET seqno = ROWNUM; or use a sequences generator: SQL> CREATE SEQUENCE sequence_name START WITH 1 INCREMENT BY 1; SQL> UPDATE table_name SET seqno = sequence_name.NEXTVAL; Finally, create a unique index on this column. -------------------------------------------------------------------------------- How can I get the time difference between two date columns Look at this example query: select floor(((date1-date2)*24*60*60)/3600) || ' HOURS ' || floor((((date1-date2)*24*60*60) - floor(((date1-date2)*24*60*60)/3600)*3600)/60) || ' MINUTES ' || round((((date1-date2)*24*60*60) - floor(((date1-date2)*24*60*60)/3600)*3600 - (floor((((date1-date2)*24*60*60) - floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60))) || ' SECS ' time_difference
  • 3. from ... -------------------------------------------------------------------------------- How does one count different data values in a column? select dept, sum( decode(sex,'M',1,0)) MALE, sum( decode(sex,'F',1,0)) FEMALE, count(decode(sex,'M',1,'F',1)) TOTAL from my_emp_table group by dept; -------------------------------------------------------------------------------- How does one count/sum RANGES of data values in a column? A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z). Look at this example: select f2, sum(decode(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100", sum(decode(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59", sum(decode(greatest(f1, 0), least(f1, 29), 1, 0)) "Range 00-29" from my_table group by f2; For equal size ranges it might be easier to calculate it with DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...). Eg. select ename "Name", sal "Salary", decode( trunc(f2/1000, 0), 0, 0.0, 1, 0.1, 2, 0.2, 3, 0.31) "Tax rate" from my_table; -------------------------------------------------------------------------------- Can one retrieve only the Nth row from a table? SELECT f1 FROM t1 WHERE rowid = ( SELECT rowid FROM t1 WHERE rownum <= 10 MINUS SELECT rowid FROM t1 WHERE rownum < 10); Alternatively... SELECT * FROM emp WHERE rownum=1 AND rowid NOT IN (SELECT rowid FROM emp WHERE rownum < 10);
  • 4. Please note, there is no explicit row order in a relational database. However, this query is quite fun and may even help in the odd situation. -------------------------------------------------------------------------------- Can one retrieve only rows X to Y from a table? To display rows 5 to 7, construct a query like this: SELECT * FROM tableX WHERE rowid in ( SELECT rowid FROM tableX WHERE rownum <= 7 MINUS SELECT rowid FROM tableX WHERE rownum < 5); Please note, there is no explicit row order in a relational database. However, this query is quite fun and may even help in the odd situation. -------------------------------------------------------------------------------- How does one select EVERY Nth row from a table? One can easily select all even, odd, or Nth rows from a table using SQL queries like this: Method 1: Using a subquery SELECT * FROM emp WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4) FROM emp); Method 2: Use dynamic views (available from Oracle7.2): SELECT * FROM ( SELECT rownum rn, empno, ename FROM emp ) temp WHERE MOD(temp.ROWNUM,4) = 0; Please note, there is no explicit row order in a relational database. However, these queries are quite fun and may even help in the odd situation. --------------------------------------------------------------------------------
  • 5. How does one select the TOP N rows from a table? Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this example: SELECT * FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC) WHERE ROWNUM < 10; Use this workaround with prior releases: SELECT * FROM my_table a WHERE 10 >= (SELECT COUNT(DISTINCT maxcol) FROM my_table b WHERE b.maxcol >= a.maxcol) ORDER BY maxcol DESC; -------------------------------------------------------------------------------- How does one code a tree-structured query? Tree-structured queries are definitely non-relational (enough to kill Codd and make him roll in his grave). Also, this feature is not often found in other database offerings. The SCOTT/TIGER database schema contains a table EMP with a self-referencing relation (EMPNO and MGR columns). This table is perfect for tesing and demonstrating tree-structured queries as the MGR column contains the employee number of the "current" employee's boss. The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle can handle queries with a depth of up to 255 levels. Look at this example: select LEVEL, EMPNO, ENAME, MGR from EMP connect by prior EMPNO = MGR start with MGR is NULL; One can produce an indented report by using the level number to substring or lpad() a series of spaces, and concatenate that to the string. Look at this example: select lpad(' ', LEVEL * 2) || ENAME ........ One uses the "start with" clause to specify the start of the tree. More than one record can match the starting condition. One disadvantage of having a "connect by prior" clause is that you cannot perform a join to other tables. The "connect by prior" clause is rarely implemented in the other database offerings. Trying to do this programmatically is difficult as one has to do the top level query first, then, for each of the records open a cursor to look for child nodes. One way of working around this is to use PL/SQL, open the driving cursor with the "connect by prior" statement, and the select matching records from other tables on a row-by-row basis, inserting the results into a temporary table for later retrieval.
  • 6. -------------------------------------------------------------------------------- How does one code a matrix report in SQL? Look at this example query with sample output: SELECT * FROM (SELECT job, sum(decode(deptno,10,sal)) DEPT10, sum(decode(deptno,20,sal)) DEPT20, sum(decode(deptno,30,sal)) DEPT30, sum(decode(deptno,40,sal)) DEPT40 FROM scott.emp GROUP BY job) ORDER BY 1; JOB DEPT10 DEPT20 DEPT30 DEPT40 --------- ---------- ---------- ---------- ---------- ANALYST 6000 CLERK 1300 1900 950 MANAGER 2450 2975 2850 PRESIDENT 5000 SALESMAN 5600 -------------------------------------------------------------------------------- How does one implement IF-THEN-ELSE in a select statement? The Oracle decode function acts like a procedural statement inside an SQL statement to return different values or columns based on the values of other columns in the select statement. Some examples: select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown') from employees; select a, b, decode( abs(a-b), a-b, 'a > b', 0, 'a = b', 'a < b') from tableX; select decode( GREATEST(A,B), A, 'A is greater than B', 'B is greater than A')... Note: The decode function is not ANSI SQL and is rarely implemented in other RDBMS offerings. It is one of the good things about Oracle, but use it sparingly if portability is required.
  • 7. From Oracle 8i one can also use CASE statements in SQL. Look at this example: SELECT ename, CASE WHEN sal>1000 THEN 'Over paid' ELSE 'Under paid' END FROM emp; -------------------------------------------------------------------------------- How can one dump/ examine the exact content of a database column? SELECT DUMP(col1) FROM tab1 WHERE cond1 = val1; DUMP(COL1) ------------------------------------- Typ=96 Len=4: 65,66,67,32 For this example the type is 96, indicating CHAR, and the last byte in the column is 32, which is the ASCII code for a space. This tells us that this column is blank-padded. -------------------------------------------------------------------------------- Can one drop a column from a table? From Oracle8i one can DROP a column from a table. Look at this sample script, demonstrating the ALTER TABLE table_name DROP COLUMN column_name; command. With previous releases one can use Joseph S. Testa's DROP COLUMN package that can be downloaded from http://www.oracle-dba.com/ora_scr.htm. Other workarounds: 1. SQL> update t1 set column_to_drop = NULL; SQL> rename t1 to t1_base; SQL> create view t1 as select <specific columns> from t1_base; 2. SQL> create table t2 as select <specific columns> from t1; SQL> drop table t1; SQL> rename t2 to t1; -------------------------------------------------------------------------------- Can one rename a column in a table? No, this is listed as Enhancement Request 163519. Some workarounds: 1. -- Use a view with correct column names...
  • 8. rename t1 to t1_base; create view t1 <column list with new name> as select * from t1_base; 2. -- Recreate the table with correct column names... create table t2 <column list with new name> as select * from t1; drop table t1; rename t2 to t1; 3. -- Add a column with a new name and drop an old column... alter table t1 add ( newcolame datatype ); update t1 set newcolname=oldcolname; alter table t1 drop column oldcolname; -------------------------------------------------------------------------------- How can I change my Oracle password? Issue the following SQL command: ALTER USER <username> IDENTIFIED BY <new_password> / From Oracle8 you can just type "password" from SQL*Plus, or if you need to change another user's password, type "password user_name". -------------------------------------------------------------------------------- How does one find the next value of a sequence? Perform an "ALTER SEQUENCE ... NOCACHE" to unload the unused cached sequence numbers from the Oracle library cache. This way, no cached numbers will be lost. If you then select from the USER_SEQUENCES dictionary view, you will see the correct high water mark value that would be returned for the next NEXTVALL call. Afterwards, perform an "ALTER SEQUENCE ... CACHE" to restore caching. You can use the above technique to prevent sequence number loss before a SHUTDOWN ABORT, or any other operation that would cause gaps in sequence values. -------------------------------------------------------------------------------- Workaround for snapshots on tables with LONG columns You can use the SQL*Plus COPY command instead of snapshots if you need to copy LONG and LONG RAW variables from one location to another. Eg:
  • 9. COPY TO SCOTT/TIGER@REMOTE - CREATE IMAGE_TABLE USING - SELECT IMAGE_NO, IMAGE - FROM IMAGES; Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated. -------------------------------------------------------------------------------- Oracle Interview Questions and Answers : SQL 1. To see current user name Sql> show user; 2. Change SQL prompt name SQL> set sqlprompt “Manimara > “ Manimara > Manimara > 3. Switch to DOS prompt SQL> host 4. How do I eliminate the duplicate rows ? SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name); or SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from table_name tb where ta.dv=tb.dv); Example. Table Emp Empno Ename 101 Scott 102 Jiyo 103 Millor 104 Jiyo 105 Smith
  • 10. delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = b.ename); The output like, Empno Ename 101 Scott 102 Millor 103 Jiyo 104 Smith 5. How do I display row number with records? To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename from emp; Output: 1 Scott 2 Millor 3 Jiyo 4 Smith 6. Display the records between two range select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum <=&upto minus select rowid from emp where rownum<&Start); Enter value for upto: 10 Enter value for Start: 7 ROWNUM EMPNO ENAME --------- --------- ---------- 1 7782 CLARK 2 7788 SCOTT 3 7839 KING 4 7844 TURNER 7. I know the nvl function only allows the same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then the text “Not Applicable” want to display, instead of blank space. How do I write the query? SQL> select nvl(to_char(comm.),'NA') from emp; Output : NVL(TO_CHAR(COMM),'NA') ----------------------- NA 300 500
  • 11. NA 1400 NA NA 8. Oracle cursor : Implicit & Explicit cursors Oracle uses work areas called private SQL areas to create SQL statements. PL/SQL construct to identify each and every work are used, is called as Cursor. For SQL queries returning a single row, PL/SQL declares all implicit cursors. For queries that returning more than one row, the cursor needs to be explicitly declared. 9. Explicit Cursor attributes There are four cursor attributes used in Oracle cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name %ISOPEN 10. Implicit Cursor attributes Same as explicit cursor but prefixed by the word SQL SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements. : 2. All are Boolean attributes. 11. Find out nth highest salary from emp table SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal); Enter value for n: 2 SAL --------- 3700 12. To view installed Oracle version information SQL> select banner from v$version; 13. Display the number value in Words SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like,
  • 12. SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------- 800 eight hundred 1600 one thousand six hundred 1250 one thousand two hundred fifty If you want to add some text like, Rs. Three Thousand only. SQL> select sal "Salary ", (' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words" from emp / Salary Sal in Words ------- ------------------------------------------------------ 800 Rs. Eight Hundred only. 1600 Rs. One Thousand Six Hundred only. 1250 Rs. One Thousand Two Hundred Fifty only. 14. Display Odd/ Even number of records Odd number of records: select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp); 1 3 5 Even number of records: select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp) 2 4 6 15. Which date function returns number value? months_between 16. Any three PL/SQL Exceptions? Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others 17. What are PL/SQL Cursor Exceptions? Cursor_Already_Open, Invalid_Cursor 18. Other way to replace query result null value with a text SQL> Set NULL ‘N/A’ to reset SQL> Set NULL ‘’ 19. What are the more common pseudo-columns?
  • 13. SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM 20. What is the output of SIGN function? 1 for positive value, 0 for Zero, -1 for Negative value. 21. What is the maximum number of triggers, can apply to a single table? 12 triggers. --------------------------------------------------------------------------------