Professional Documents
Culture Documents
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. SQL is a de facto standard, as
well as an ISO and ANSI standard. SQL is often pronounced SEQUEL.
What is the difference between SQL and SQL*PLUS?
SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool.
Its a command line tool that allows user to type SQL commands to be executed directly against an
Oracle database. SQL is a language used to query the relational database (DML, DDL, DCL).
SQL*PLUS commands are used to format query result, Set options, Edit SQL commands & PL/SQL.
What is the difference between SQL and SQL*PLUS commands?
SQL commands are stored in a buffer where as SQL*PLUS are not.
Name some SQL*PLUS commands?
DESC[RIBE], START, DEFINE, GET, SAVE.
What are the SQL*PLUS reporting commands?
SPOOL. TTITLE, BTITLE, BREAK ON.
What is Schema and Schema Objects?
Schema is a collection of logical structure of data or Schema Objects. A Schema is owned by a
database user and has the same name as that of user. Each user owns a single Schema.
Schema Objects include the following type of objects Clusters, Database Links, Tables, Indexes,
Sequence, Synonyms, Views, Functions, Procedures, Database Triggers and Packages.
What is a Session?
The period between Login and Log-off on Schema.
How to display data Page Wise in SQL?
Table level
(ii)
Table space
(iii)
What is Deadlock?
A deadlock can occur when two or more user are waiting for data locked by each other. Deadlocks
prevent some transactions from continuing to work.
What are the large OBJECT types supported by the Oracle?
BLOB
CLOB
What are the data types allowed in a table?
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW
How many LONG columns are allowed in a table? Is it possible to use LONG columns in
WHERE clause or ORDER BY?
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER
BY clause.
Which datatype is used for storing graphics and images?
LONG RAW data type is used for storing BLOB's (binary large objects).
What is the difference between CHAR, VARCHAR, VARCHAR2 data types?
CHAR
VARCHAR
Yes
If content of dual is updated to some value computation takes place or not?
Yes
If any other table same as dual is created would it act similar to dual?
Yes
What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 character long, block no, row
number are the components of ROWID
What is the difference between rowid and rownum?
ROWID is an internal representation of a row in a table, it is effectively the primary key and can be
used for fast access to the row
ROWNUM is a function of a result set of your query:
select * from emp where rownum = 1 will get the first row of your result set.
So rowid is a function of the table. rownum is a function of the result set.
What are the difference between DDL, DML, DQL, TCL and DCL commands?
DDL: DDL statements are used to define the data base structure or schema.
(A) CREATE
(B) ALTER
(C) DROP
DML: DML statements are used to manage the data with in the schema objects.
(A) INSERT
(B) UPDATE
(C) DELETE
DQL: DQL is used to get the data from data base objects for read only purpose
DCL: It is used to share information between users
(A) GRANT - It is used to give permission
(B) REVOKE - It is used to cancel the permission
TCL: It is used to control the DML operation.
(A) COMMIT
Clusters are an optional method of storing table data. A Cluster is a group of tables that share the same
data blocks because they share common columns and are often used together. It improves access time
for joins of clustered tables.
What are the Disadvantages of a CLUSTER?
Low performance in case of DML operations
Example: The EMPLOYEE and DEPARTMENT table share the DEPT_ID column. When you cluster
the employees and departments tables, Oracle physically stores all rows for each department from both
the tables.
Ex:
Step:1 Create a Cluster
Create CLUSTER c1(deptno number(2));
Step:2 Create a Employee table
Sql> Create table emp(empno number(4),
ename varchar2(15),
sal number(7),
deptno number(2)) cluster
c1(deptno);
Step:3 Create a Department table
Sql> Create table dept(dname varchar2(15),
deptno number(2),
loc varchar2(15)) cluster c1(deptno);
Step:4 Create a Index on Cluster
Sql> Create index id_c1 on cluster c1;
How to drop a CLUSTER when CLUSTERED table exists?
When cluster table exists it is not possible to drop the cluster, if we want drop the table first then only
cluster to be dropped.
What are the advantages of clusters?
Access time reduced for joins.
What are the disadvantages of clusters?
The time for Insert increases.
How does one escape special characters when building SQL queries?
The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one
character, '%' is used to match zero or more occurrences of any characters. These characters can be
escaped in SQL.
Ex: SELECT ename FROM emp WHERE empno LIKE '%_%' ESCAPE '\';
How does one escape special characters when writing SQL queries?
Use tow quotes for every one displayed.
Ex: SELECT 'franks Oracle Site' as text from dual;
What is meant by SORTING and GROUPING?
For sorting we use order by clause in select statement. This is used to sort data in Ascending order or
Descending order.
To group the data based on particular column we use group by clause.
What is the Difference between TRUNCATE, DELETE and DROP?
TRUNCATE : Truncate removes all rows from a table. The operation cannot be
rollback and no Triggers will be fired. It is faster than delete command.
DELETE
DROP
: Drop command will removes a table from the database. All the Table
rows, Indexes and privileges will also be removed. No DML triggers
will be fired. The operation cannot be roll backed.
SELECT
(ii)
CONNECT
(iii)
RESOURCES
An insert statement followed by a create table statement followed by rollback? Will the rows be
inserted?
No.
Can you define multiple savepoints?
Yes.
How to make every DML operations as AUTO COMMIT?
By using SET AUTOCOMMIT ON command.
What happens when commit is given in executable section when an error occurs?
It Rollback the transactions
If you insert a row in a table, then create another table and then say Rollback. In this case will
the row be inserted?
Yes, because Create table is a DDL which commits automatically as soon as it is executed.
The DDL commits the transactions even if the create statement fails internally.
What is the difference between Transaction and a Query?
A Transaction is unit of some commands where as Query is a single line request for the information
from the database.
What are the BUILT-IN's?
DISTINCT
SUM
COUNT
MIN
MAX
AVG
ABS
POWER
Syntax : POWER(3,2)
ROUND
TRUNC
CEIL
FLOOR
: Returns the largest integer value that is equal to or less than a number.
MOD
SQRT
EXP
LEAST
GREATEST
LOWER
UPPER
INITCAP
: Returns a string with the first letter of each word in upper case.
SUBSTR
EXTRACT
EX: SELECT extract (year from date 2004-07-02') year from dual;
LTRIM
RTRIM
TRIM
LPAD
RPAD
TRANSLATE
REPLACE
LENGTH
TO_CHAR
TO_DATE
TO_NUMBER
ADD_MONTH
LAST_DAY
MONTHS_BETWEEN
NEXT_DAY
: Returns the date of the first weekday named by char that is after the
date named by date.
VSIZE
NVL
: NVL is used when we are dealing with null values if we want to show
any another value instead of NULL then we will use NVL.
DECODE
What is DISTINCT?
The DISTINCT clause removes the duplicate values from the result set.
What is the difference between COUNT (), COUNT (*) Functions?
Count () will restrict the NULL values whereas count (*) will retrieve all the rows including NULL
values in a table.
What is the difference between SUBSTR () and INSTR () Functions?
Substr() will return the specified part of a string whereas
Instr() return the position of the specified part of the string.
What is the use of EXTRACT?
EXTRACT extracts and returns the value of a specified date time field from a date time or interval
value expression.
Example:
SELECT EXTRACT(YEAR FROM DATE '1998-03-07') FROM DUAL;
SELECT EXTRACT(MONTH FROM DATE '1998-03-07') FROM DUAL;
SELECT EXTRACT(DAY FROM DATE '1998-03-07') FROM DUAL;
Which date function returns number value?
MONTHS_BETWEEN this date function takes 2 valid dates and returns number of months in between
them.
FROM
emp;
Display the records between two range 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?
You can use the decode function for the above requirement. Please find the query as below:
Ex: select ename,DECODE(NVL(comm,0),0,'Not Applicable',comm) from scott.emp;
What is the use of CASE?
CASE expression is used like IF..THEN...ELSE logic in SQL statement without invoking procedures.
Example:
SELECT
ename,
sal,
CASE sal WHEN 1000 THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium'
END
FROM
emp;
deptno,
job,
sum(sal)
FROM
emp
GROUP BY
ROLLUP(deptno,job);
CUBE takes a specified set of grouping columns and creates subtotals for all the possible
combinations. The result set will include all the values that would be included in an equivalent
ROLLUP statement plus additional combinations.
Example:
SELECT
FROM
emp
GROUP BY CUBE(deptno,job);
What is MERGE statement (9i)?
Merge statement enables us to do either UPDATE or INSERT a row into a target table using a single
statement.
Example:
merge into dept d
using emp e
on(d.deptno=e.deptno)
when matched found then
update set d.name=e.ename,
d.job=e.job,
d.salary=e.salary,
d.deptno=e.deptno
when not matched then
insert(d.name,d.job,d.salary,d.deptno)
values(e.ename,e.job,e.salary,e.deptno);
What are set operator?
Set operators combine the result of two component queries into a single result queries containing set
operator are called components queries
UNION
UNION ALL : All rows selected by either query, including all duplicate
INTERSECT : All distinct rows selected by both queries
MINUS
: All distinct rows selected by the first query but not the second.
Normal Queries
(ii)
Sub Queries
(iii)
Co-related queries
(iv)
Compound queries
(ii)
: The exists condition is considered to be met if the sub query returns at least one row.
The below statement will return all the records from the emp table.
Ex: SELECT * FROM emp WHERE EXISTS(select *from dept where emp.deptno=dept.deptno);
NOT EXISTS : This will return all records from emp where there are no records in the dept table for
the given deptno.
ANY
: The any operator computes the lowest value from the set & compares a value to each
returned by a sub query.
ALL
What is the difference b/w sub query and correlated sub query?
In a normal sub query the child query does not depends upon parent query for the conditional value.
Here child query processes first and returns values to parent query.
In a correlated sub query the child query depends upon the parent query for the conditional value. Here
parent query processed first then child query processed one by one for each row of parent query.
What is the difference between IN & Exist?
IN
: We will use this IN operator if we want to find out a value in a list of values.
EXIST : We will use exist operator when we want to find out a value from Result of the sub query.
Which is faster - IN or EXISTS?
Exists is more than IN because Exists returns a Boolean value where as IN returns a value.
What is a JOIN?
It is used to display data from more than one table in single query.
A join is a query that combines rows from two or more tables, views or materialized views.
What are the types of JOINS?
Cross join (or) Cartesian join
Equi join (or) Natural join (or) INNER JOIN
Outer join (LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN)
Non- Equi join
Self join
What is SELF-JOIN?
SELF JOIN is nothing but EQUI JOIN on same table. For self join the table must have at least two
common columns.
Select
e.ename "E_NAME",
m.ename "M_NAME"
FROM
emp e,
emp m
WHERE
e.mgr = m.empno;
What is EQUI-JOIN?
It is used to retrieve data from different tables based on the join condition.
For this condition we need to have at least common column between the tables.
For this join we use '=' operator
SELECT
e.empno,
d.dname
FROM
emp e,
dept d
WHERE
e.deptno = d.deptno;
What Is INNER-JOIN?
It is also same as EQUI-JOIN but syntax is different.
SELECT
e.empno, d.dname
FROM
emp e
ON
e.deptno = d.deptno;
emp e, salgrade g
: This join returns all the rows from the first table even if there are no
matches in the second table.
: This join returns all the rows from the second table even if there are no
matches in the first table.
: The full outer join retrieves all records from both the left and the right
table. Most likely, you won't run into a need for this join very often.
ON e.deptno = d.deptno
What is CROSS JOIN?
A CROSS JOIN returns a Cartesian product. This means that the join combines every row from the left
table with every row in the right table.
Ex: SELET * FROM emp,dept;
[or]
SELECT e.empno,e.ename,d.deptno FROM emp CROSS JOIN dept;
What is a CONSTRAINT? What are its various levels?
CONSTRAINTS are used to check validations before inserting data into Table and also provide
relationship between tables.
TABLE LEVEL CONSTRAINTS
: 1. UNIQUE CONSTRAINT
2. PRIMARY KEY CONSTRAINT
3. CHECK CONSTRAINT
4. FOREIGN KEY CONSTRAINT
COLUMNLEVEL CONSTRAINTS
: 1. UNIQUE CONSTRAINT
2. PRIMARY KEY CONSTRAINT
3. CHECK CONSTRAINT
4. FOREIGN KEY CONSTRAINT
5. NOT NULL CONSTRAINT
6. DEFAULT CONSTRAINT.
UNIQUE Constraint
PRIMARY KEY Constraint - Disallows duplicate values and NULL values in a column or set
of columns.
FOREIGN KEY Constraint - Require each value in a column or set of columns match a
value in a related table's UNIQUE or PRIMARY KEY.
CHECK Constraint
If a unique key constraint on DATE column is created, will it validate the rows that are inserted
with sysdate?
It won't, Because SYSDATE format contains time attached with it.
What is the difference between REFERENCES and FOREIGN KEY Constraint?
Foreign key is the key which refers to another table primary key.
Reference key is the primary key of table referred by another table.
What is Composite PRIMARY KEY?
A Primary key created on combination of columns is called Composite Primary Key.
What is created implicitly for every UNIQUE and PRIMARY KEY column?
INDEX
What are the limitations for CHECK constraint?
In this we can't specify Pseudo Columns like sysdate etc.
What are the pre-requisites to (i) modify data type of a column (ii) add a column with NOT
NULL constraint?
To Modify the data type of a column the column must be empty.
To add a column with NOT NULL constrain, the table must be empty
What is the fastest way of accessing a row in a table?
Using ROWID, CONSTRAINTS
What is a sequence?
Sequence is a database object. It is used to generate number in order. It is not related to table. By using
sequence the retrieve data from table is very fast.
It has two pseudo columns.
NEXTVAL (holds the next generated value)
CURRVAL (holds the current available value)
What are the parameters in SEQUENCE?
INCREMENT BY
START WITH
MAXVALUE | NOMAXVALUE
MINVALUE | NOMINVALUE
CYCLE
| NOCYCLE
CACHE
| NOCACHE
ORDER
| NOORDER
(ii)
(iii)
Inline view
(ii)
Updateable view
(iii)
Non updateable view : if the view is created from two or more tables and if it contains
any aggregate functions, joins, union commands then that view
is called as non updateable view.
(iv)
Materialized view
If the view is create base on a single table and it doesn't contain any aggregate functions then that view
is 'Updatable'.
If the view is created based on a join statement or it contains any aggregate functions then that view
is 'not updateable'.
Can a view be updated/inserted/deleted
A simple view can be updated/inserted/deleted but the complex view which is constructed by using
multiple tables or by using group functions can't be updated.
If a View on a single base table is manipulated will the changes be reflected on the base table?
If changes are made to the tables which are base tables of a view then the changes effected on view.
What is the function of 'force' in view?
FORCE function is used to create view with out table. When we create the corresponding tables the
forced view become valid. When we drop the base table the view exists but becomes forced view.
What is the difference between a View and Materialized View?
View
1. View can be created based on
Materialized View
1. Materialized can be creates based on
views.
views.
statement.
the query
Yes
Can you create index on view
No.
What is a SNAPSHOT?
It is a static picture of table, snapshot is a table that contains the results of a query of one or more
tables or views, and it contains structure and data also.
Data retrieval is faster in snapshot than view.
Syntax: CREATE snapshot <snapshot_name> AS select statement
What is the difference between snap shots and materialized views?
SNAP SHOT
MATERIALIZED VIEW
Contents
[hide]
1 What is SQL and where does it come from?
2 What are the difference between DDL, DML and DCL commands?
3 Difference between TRUNCATE, DELETE and DROP commands?
4 How does one escape special characters when writing SQL queries?
5 Can one select a random collection of rows from a table?
6 How does one eliminate duplicates rows from a table?
7 How does one get the time difference between two date columns?
8 How does one add a day/hour/minute/second to a date value?
9 How does one code a matrix/crosstab/pivot report in SQL?
10 Can one retrieve only rows X to Y from a table?
11 Can one retrieve only the Nth row from a table?
12 How can one dump/ examine the exact content of a database column?
13 How does one add a column to the middle of a table?
14 How does one code a hierarchical tree-structured query?
15 How does one count/sum data values in a column?
16 How does one drop/ rename a column in a table?
17 How does one implement IF-THEN-ELSE logic in a SELECT statement?
18 How does one prevent Oracle from using an Index?
19 How does one select EVERY Nth row from a table?
20 How does one select the LAST N rows from a table?
21 How does one select the TOP N rows from a table?
22 How to generate a text graphs (histograms) using SQL?
remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to the data
LOCK TABLE - controls concurrency
TCL - Transaction Control: statements used to manage the changes made by DML statements. It
allows statements to be grouped together into logical transactions.
SQL> COMMIT;
Commit complete.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------10
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will
be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE.
SQL> TRUNCATE TABLE emp;
Table truncated.
SQL> SELECT COUNT(*) FROM emp;
COUNT(*)
---------0
The DROP command removes a table from the database. All the tables' rows, indexes and privileges
will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
SQL> DROP TABLE emp;
Table dropped.
SQL> SELECT * FROM emp;
SELECT * FROM emp
*
ERROR at line 1:
ORA-00942: table or view does not exist
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore
DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be
rolled back.
From Oracle 10g a table can be "undropped". Example:
SQL> FLASHBACK TABLE emp TO BEFORE DROP;
Flashback complete.
PS: DELETE will not free up used space within a table. This means that repeated DELETE commands
will severely fragment the table and queries will have to navigate this "free space" in order to retrieve
rows.
[edit] How does one escape special characters when writing SQL queries?
Escape quotes
Use two quotes for every one displayed. Examples:
SQL> SELECT 'Frank''s Oracle site' AS text FROM DUAL;
TEXT
-------------------Franks's Oracle site
SQL> SELECT 'A ''quoted'' word.' AS text FROM DUAL;
TEXT
---------------A 'quoted' word.
SQL> SELECT 'A ''''double quoted'''' word.' AS text FROM DUAL;
TEXT
------------------------A ''double quoted'' word.
Escape wildcard characters
The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one
character, while '%' is used to match zero or more occurrences of any characters. These characters can
be escaped in SQL. Examples:
SELECT name FROM emp
WHERE id LIKE '%/_%' ESCAPE '/';
SELECT name FROM emp
WHERE id LIKE '%\%%' ESCAPE '\';
Escape ampersand (&) characters in SQL*Plus
When using SQL*Plus, the DEFINE setting can be changed to allow &'s (ampersands) to be used in
text:
SET DEFINE ~
SELECT 'Laurel & Hardy' FROM dual;
Other methods:
Define an escape character:
SET ESCAPE '\'
SELECT '\&abc' FROM dual;
Don't scan for substitution variables:
.000694444
Solution 1
SQL> SELECT floor(((date1-date2)*24*60*60)/3600)
2
|| ' HOURS ' ||
3
floor((((date1-date2)*24*60*60) 4
floor(((date1-date2)*24*60*60)/3600)*3600)/60)
5
|| ' MINUTES ' ||
6
round((((date1-date2)*24*60*60) 7
floor(((date1-date2)*24*60*60)/3600)*3600 8
(floor((((date1-date2)*24*60*60) 9
floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60) ))
10
|| ' SECS ' time_difference
11 FROM dates;
TIME_DIFFERENCE
-------------------------------------------------------------------------------24 HOURS 0 MINUTES 0 SECS
1 HOURS 0 MINUTES 0 SECS
0 HOURS 1 MINUTES 0 SECS
Solution 2
If you don't want to go through the floor and ceiling maths, try this method:
SQL> SELECT to_number( to_char(to_date('1','J') +
2
(date1 - date2), 'J') - 1) days,
3
to_char(to_date('00:00:00','HH24:MI:SS') +
4
(date1 - date2), 'HH24:MI:SS') time
5 FROM dates;
DAYS TIME
---------- -------1 00:00:00
0 01:00:00
0 00:01:00
Solution 3
Here is a simpler method:
SQL> SELECT trunc(date1-date2) days,
2 to_char(trunc(sysdate) + (date1 - date2), 'HH24 "Hours" MI "Minutes" SS "Seconds"') time
3 FROM dates;
DAYS TIME
---------- -----------------------------1 00 Hours 00 Minutes 00 Seconds
0 01 Hours 00 Minutes 00 Seconds
0 00 Hours 01 Minutes 00 Seconds
Date Expression
Now
SYSDATE
SYSDATE + 1
SYSDATE + 7
SYSDATE + 1/24
SYSDATE + 3/24
SYSDATE + 1/48
SYSDATE + 10/1440
SYSDATE + 30/86400
TRUNC(SYSDATE + 1) + 8/24
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
Here is the same query with some fancy headers and totals:
SQL> ttitle "Crosstab Report"
SQL> break on report;
SQL> compute sum of dept10 dept20 dept30 dept40 total on report;
SQL>
SQL> SELECT *
2 FROM (SELECT job,
3
sum(decode(deptno,10,sal)) DEPT10,
4
sum(decode(deptno,20,sal)) DEPT20,
5
sum(decode(deptno,30,sal)) DEPT30,
6
sum(decode(deptno,40,sal)) DEPT40,
7
sum(sal)
TOTAL
8
FROM emp
9
GROUP BY job)
10 ORDER BY 1;
Mon Aug 23
page 1
Crosstab Report
JOB
DEPT10 DEPT20 DEPT30 DEPT40 TOTAL
--------- ---------- ---------- ---------- ---------- ---------ANALYST
6000
6000
CLERK
1300
1900
950
4150
MANAGER
2450
2975
2850
8275
PRESIDENT
5000
5000
SALESMAN
5600
5600
---------- ---------- ---------- ---------- ---------sum
8750
10875
9400
29025
Here's another variation on the theme:
SELECT *
FROM (SELECT a.*, rownum RN
FROM (SELECT *
FROM t1 ORDER BY key_column) a
WHERE rownum <=7)
WHERE rn >=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.
The generic solution to get full information of rows between x and y
SELECT * FROM emp WHERE empno in (SELECT empno FROM emp GROUP BY
rownum,empno HAVING rownum BETWEEN &x AND &y);
"select particular rows from a table : select for rownum = 4, 15 and 17."
select * from (
select rownum myrownum, emp.* from employees emp
) mytable
where myrownum in (4,15,17);
"selecting row between range of rownum: select for rownum between (12, 20)."
select * from (
select rownum myrownum, emp.* from employees emp
) mytable
where myrownum between 12 and 20;
"Replace 12 and 20 with &x and &y respectively to assign range dynamically."
select * from (
select rownum myrownum, emp.* from employees emp
) mytable
where myrownum between &x and &y;
"Combined query to give complete flexibility to pick particular rows and also a given range."
select * from (
For this example, type=96 is indicating a CHAR column. 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.
[edit] How does one add a column to the middle of a table?
Oracle only allows columns to be added to the end of an existing table. Example:
SQL> CREATE TABLE tab1 ( col1 NUMBER );
Table created.
SQL> ALTER TABLE tab1 ADD (col2 DATE);
Table altered.
SQL> DESC tab1
Name
Null? Type
----------------------------------------- -------- ---------------------------COL1
NUMBER
COL2
DATE
Nevertheless, some databases also allow columns to be added to an existing table after a particular
column (i.e. in the middle of the table). For example, in MySQL the following syntax is valid:
ALTER TABLE tablename ADD columnname AFTER columnname;
Oracle does not support this syntax. However, it doesn't mean that it cannot be done.
Workarounds:
1. Create a new table and copy the data across.
SQL> RENAME tab1 TO tab1_old;
Table renamed.
SQL> CREATE TABLE tab1 AS SELECT 0 AS col1, col1 AS col2 FROM tab1_old;
Table created.
2. Use the DBMS_REDEFINITION package to change the structure on-line while users are working.
[edit] How does one code a hierarchical tree-structured query?
The SCOTT/TIGER database schema contains a table EMP with a self-referencing relation (EMPNO
and MGR columns). This table is perfect for testing 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:
group by my_table_column;
A more sophisticated example...
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;
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;
[edit] How does one drop/ rename a column in a table?
Drop a column
From Oracle 8i one can DROP a column from a table. Look at this sample script, demonstrating the
ALTER TABLE table_name DROP COLUMN column_name; command.
Workarounds for older releases:
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;
SQL> create table t2 as select >specific columns> from t1;
SQL> drop table t1;
SQL> rename t2 to t1;
Rename a column
From Oracle 9i one can RENAME a column from a table. Look at this example:
ALTER TABLE tablename RENAME COLUMN oldcolumn TO newcolumn;
Workarounds for older releases:
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;
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;
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;
[edit] How does one implement IF-THEN-ELSE logic in a SELECT statement?
One can use the CASE statement or functions like DECODE, NVL, NVL2, NULLIF, COALESCE,
etc.
Here is the syntax for the CASE-statement:
CASE exp WHEN comparison_exp1 THEN return_exp1
[WHEN comparison_exp2 THEN return_exp2
WHEN comparison_exp3 THEN return_exp3
ELSE else_exp
]
END
And for DECODE:
DECODE( col | exprn, srch1, rslt1 [, srch2, rslt2,...,] [,default] )
[edit] How does one prevent Oracle from using an Index?
In certain cases, one may want to disable the use of a specific, or all indexes for a given query. Here
are some examples:
0
1
2
[edit] 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;
Method 3: Using GROUP BY and HAVING
SELECT rownum, f1 FROM t1
GROUP BY rownum, f1 HAVING MOD(rownum,n) = 0 OR rownum = 2-n;
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.
[edit] How does one select the LAST N rows from a table?
From Oracle 9i onwards, the RANK() and DENSE_RANK() functions can be used to determine the
LAST N or BOTTOM N rows. Examples:
Get the bottom 10 employees based on their salary
SELECT ename, sal
FROM ( SELECT ename, sal, RANK() OVER (ORDER BY sal ASC) sal_rank
FROM emp )
WHERE sal_rank <= 10;
Select the employees getting the lowest 10 salaries
SELECT ename, sal
12
ELSE
13
ret := ret || ',' || hold;
14
END IF;
15 END LOOP;
16 RETURN ret;
17 END;
18 /
Function created.
This function returns a string result with the concatenated non-NULL values from a SQL statement. It
returns NULL if there are no non-NULL values.
Here is an example of how to map several rows to a single concatenated column:
SQL> SELECT rowconcat('SELECT dname FROM dept') AS departments
2 FROM dual;
DEPARTMENTS
-------------------------------------------------------------------------------ACCOUNTING,RESEARCH,SALES,OPERATIONS
This example is more interresting, it concatenates a column across several rows based on an
aggregation:
SQL> col employees format a50
SQL> SELECT deptno,
2
rowconcat('SELECT ename FROM emp a WHERE deptno='||deptno) AS Employees
3 FROM emp
4 GROUP BY deptno
5 /
DEPTNO EMPLOYEES
---------- -------------------------------------------------30 ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES
20 SMITH,JONES,SCOTT,ADAMS,FORD
10 CLARK,KING,MILLER
[edit] What is the difference between VARCHAR, VARCHAR2 and CHAR data types?
Both CHAR and VARCHAR2 types are used to store character string values, however, they behave
very differently. The VARCHAR type should not be used:
CHAR
CHAR should be used for storing fixed length character strings. String values will be space/blank
padded before stored on disk. If this type is used to store variable length strings, it will waste a lot of
disk space.
SQL> CREATE TABLE char_test (col1 CHAR(10));
Table created.
SQL> INSERT INTO char_test VALUES ('qwerty');
1 row created.
SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM char_test;
COL1
LENGTH(COL1) ASCII Dump
---------- ------------ -----------------------------------------------------------qwerty
10 Typ=96 Len=10: 113,119,101,114,116,121,32,32,32,32
Note: ASCII character 32 is a blank space.
VARCHAR
Currently VARCHAR behaves exactly the same as VARCHAR2. However, this type should not be
used as it is reserved for future usage.
SQL> CREATE TABLE varchar_test (col1 VARCHAR2(10));
Table created.
SQL> INSERT INTO varchar_test VALUES ('qwerty');
1 row created.
SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM varchar_test;
COL1
LENGTH(COL1) ASCII Dump
---------- ------------ -----------------------------------------------------------qwerty
6 Typ=1 Len=6: 113,119,101,114,116,121
VARCHAR2
VARCHAR2 is used to store variable length character strings. The string value's length will be stored
on disk with the value itself.
SQL> CREATE TABLE varchar2_test (col1 VARCHAR2(10));
Table created.
SQL> INSERT INTO varchar2_test VALUES ('qwerty');
1 row created.
SQL> SELECT col1, length(col1), dump(col1) "ASCII Dump" FROM varchar2_test;
COL1
LENGTH(COL1) ASCII Dump
---------- ------------ -----------------------------------------------------------qwerty
6 Typ=1 Len=6: 113,119,101,114,116,121
A. commit;
2. How to cancel changes which we made?
A. rollback;
[Ans: 20 19 19.78]
[Ans: 19 19 19.73]
CHARACTER FUNCTIONS
1. How to display the first char as capital?
A. select empno,initcap(ename),job,salary from emp;
GENERAL FUNCTIONS
1. How to select the least value from the given values?
A. select least(12,09,4,20,6,46) from dual;
2. How to select greatest value from the given values?
A. select greatest(12,09,4,20,6,46) from dual;
3. How to select minimum & maximum salary from the table?
A. select min(salary),max(salary) from emp;
SPECIAL OPERATORS
1. How to converts a null value in to actual value?
A. select empno,ename,nvl(comm,10) from emp;
select count(nvl(comm,0)) from emp;
VIEWS
* It is a stored select statement.
* It will not hold any data.
* Desc, DML, Select allowed in views.
* Any manipulations in view will be reflected in table.
* Providing high security while sharing view with other users.
1. How to create view?
A. create view v1 as select * from emp;
2. How to display the view structure?
A. desc view
3. How to insert values in view?
A. insert into view v1 values(108,'prasad','clerk',7000,40,sysdate);
[these values will be automatically inserted into emp also]
4. How to update values in to view?
A. update v1 set salary=8000 where empno=102;
5. How to delete rows in view?
A. delete from v1 where empno=102;
A. select empno,ename,job,sal from (select empno,ename,job,sal from emp order by sal desc)
group by rownum,empno,ename,job,sal having rownum=&n;
3. How to retrieve alternate rows?
A. select rownum,empno,ename,job,sal from emp group by rownum,empno,ename,job,sal having
mod(rownum,2)=0;
4. How to delete the duplicate records which is having the same data,empno & ename?
A. delete from emp where rowid not in(select min(rowid) from emp group by empno);
5. How to retrieve the first five rows from the table?
A. select * from emp where rownum<6;
6. How to retrieve the last five rows from the table?
A. select * from emp minus select * from emp where rownum<=10;
select * from emp minus select * from emp where rownum<=(select max(rownum)-5 from emp);
7. How to retrieve a particular row from the table?
A. select * from emp where rownum<6 minus select * from emp where rownum<5;
8. How to see the no.of rows in the table?
A. select max(rownum) from emp;
9. How to delete a row from the table using rownum?
A. delete from emp where rownum<2;
delete from emp where rownum<5;
10. How to update row using rownum?
A. update emp set sal=2500 where rownum<2;
SEQUENCE
It is used to generate number in order.
It is not related to the tables.
It uses two pseudo columns.
-- nextval (holds the next generated value)
--currval (holds the current available value)
1. How to create sequence?
A. create sequence s1
increment by 1
start with 200
maxvalue 210
nocache
nocycle;
2. How to insert into a table using sequence?
A. insert into emp(empno,ename,job,salary,deptno) values(s1.nextval,'ravi','employee',8000,10);
3. How to see the sequence current value?
A. select s1.currval from dual;
(enter)
(enter)
(enter)
(enter)
(enter)
(enter)