You are on page 1of 26

What is SQL?

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.
It’s 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?


By using SET PAUSE ON command.

How to change Line Size and Page Size and SQL Prompt?
By using SET LINESIZE <value>, SET PAGESIZE <value>, SET SQLPROMPT <new prompt>.
What is Database?
The Collection of Interrelated Data is called Data Base.

What is Database Management System (DBMS) Package?


The Collection of Interrelated Data and some Programs to access the Data is Called Data Base
Management System (DBMS).

Describe Oracle database's physical and logical structure?


Physical: Data files, Redo Log files, Control file.
Logical: Tables, Views, Table spaces, etc.

What is database link?


A database link is a pointer that defines a one-way communication path from an oracle database server
to another database server
Ex: scott>Create database link <link name>
Connect to scott
Identified by tiger
Using '<link name>'
/
Scott> select * from dual@<link name>;

What are the types of Locks?


1) Share Lock
--- It allows the other users for only reading not to insert or update or delete.
2) Exclusive Lock
--- Only one user can have the privileges of insert or update and delete of particular object
--- Others can only read.
3) Update Lock
--- Multiple user can read, update delete

What are the types of Lock Levels?


(i) Table level
(ii) Table space
(iii) Data base level.
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 : CHAR is used for storing Fixed Length Character String.
VARCHAR : It behaves exactly same as VARCHAR2. This type should not be
Used as it is reserved for future usage.
VARCHAR2 : VARCHAR2 is used for storing Variable Length Character String.

What is a DUAL table?


Dual is a table owned by SYS. It is a pseudo table, which consist of only one row and one column. The
column name is DUMMY and it holds the value X.

Can dual table be deleted, dropped or altered or updated or inserted?


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 - It is used to save the data dynamically.
(B) ROLL BACK - It is used to cancel the changes.
(C) SAVEPOINT - It is used to mark the transactions.

What is a transaction?
A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.
What is the maximum no. of columns a table can have?
1000

Is SYSDATE a system variable or a system function?


System Function

How can i see the time of execution of a sql statement?


SET TIME ON

IS 'DEFINE' a valid SQL statement?


DEFINE is a command of SQL * PLUS Tool. This is only valid in SQL * PLUS.
With DEFINE command, user can define the session variables.

What are pseudo-columns in SQL? Provide examples?


A pseudo column behaves like a table column, but is not actually stored in the table. You can select
from pseudo columns, but you cannot insert, update, or delete their values.
Ex: CURRVAL, NEXTVAL, ROWID, LEVEL

What is a dynamic SQL?


DDL statement used within PL/SQL using “Execute Immediate”

What is INDEX and what are the advantages?


An Index is a database object used to retrieve the data fastly from the Tables.
An Index increases the performance of the database.

How Oracle identifies each record of Table uniquely?


By Creating indexes and reference IDs.

What is the use of CLUSTER?


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.

Can Long/Long RAW be clustered?


No

Can null keys be entered in cluster index, normal index?


Yes

What is ALTER command? How we use it to Add a new column?


ALTER command is used to modify the structure of table. By using alter we can add, modify & delete
columns. to change the data type or decrease the size of a column the column must be empty. For
ALTER a table we need ALTER, INSERT & CREATE privileges.
Ex: ALTER table <table_name> ADD <column_name> type(size);

Can we change the data type and size in a table when data is there and when data is not there?
When there is data we can increase the size, we can not decrease the size but we cannot change the
data type.
Yes we can change the data type and size when there is no data

What is difference between Update and Alter commands?


Alter command is used to modify the database objects where as the Update command is used to
modify the values of a data base object.

What is the use of INSERT ALL?


Is used for multiple insert more than one rows to more than one table.
Ex: INSERT ALL into emp2 values(empno,ename,job,sal,deptno,comm,hire_date) select * from emp;

What is the difference Rename and Alias?


Rename is a permanent name given to a table or column where as Alias is a temporary name given to a
table or column which does not exist once the SQL statement executed.

What is the use of AND condition?


The AND condition allows to create a SQL statement based on 2 or more conditions being met.

What is the use of OR condition?


The OR condition allows to create a SQL statement when any one of the conditions are met based on
the records returned.

What is the use of WHERE clause?


The WHERE clause allows to filter the results from an SQL statement. We can also the WHERE
clause to join multiple tables together in a single SQL statement.

What is the significance of the & and && operators in PL SQL?


The & operator means that the PL SQL block requires user input for a variable.
The && operator means that the value of this variable should be the same as Inputted by the user
previously for this same variable.

When do you use WHERE clause and when do you use HAVING clause?
HAVING clause is used when you want to specify a condition for a group function and it is written
after GROUP BY clause. The WHERE clause is used when you want to specify a condition for
columns, single row functions except group functions and it is written before GROUP BY clause if it
is used.

What is the use of GROUP BY clause?


The group by clause is another section of select statement. This option tells oracle to group rows based
on distinct values that exits or specified columns. The GROUP BY clause creates a data set, contained
several sets of records grouped tighter based on condition.

What is the use of HAVING clause?


The having clause can be used in conjunction with the GROUP BY clause. HAVING imposes a
condition on the GROUP BY clause, which further filters the groups created by GROUP BY clause.

What is the use of ORDER BY clause?


For sorting we use order by clause in select statement. This is used to sort data in
Ascending order or Descending order.

What is the use of LIKE condition?


The LIKE condition allows to perform pattern matching.
%  It allows to match any string of any length (including zero length)
_  It allows to match on a single character

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 'frank’’s 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 : Delete command is used to remove the rows from a table. A WHERE
clause can also be used to remove only some rows. After performing
delete operation you need to COMMIT or ROLLBACK the transaction
to make the changes permanent or to undo it.
For this delete operation all Delete triggers will be fire on the table.
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.

What is the use of GRANT?


Using GRANT command we can provide various privileges to users on tables.

What is the use of REVOKE?


Once we granted the privileges, we may need to cancel/revoke some or all privileges. To do this we
execute REVOKE command.

How to see what privileges given by user to other users?


Using USER_TAB_PRIVS_MADE
USER_COL_PRIVS_MADE

How to see what privileges received to user by owner user?


Using USER_TAB_PRIVS_RECD
USER_COL_PRIVS_RECD

What are the System and Object Privileges?


Connect and Resource etc are System Privileges.
Create <object>, Select, Insert, Alter etc are Object Privileges.

What is the GRANT command with "WITH GRANT OPTION"?


“With Grant Option” with Grant Command gives privileges to the user to grant privileges to other
user(s) among the privileges he/she has.

What are various privileges that a user can grant to another user?
(i) SELECT
(ii) CONNECT
(iii) RESOURCES

What is the use of ROLLBACK?


The rollback statement undoes all the changes for the current session up to the save point specified. If
no save point specified then all changes are undone.

What is the use of COMMIT?


A commit is used to ends the current transaction and makes permanent any changes made during the
transaction. All transactional locks acquired on the tables are released.

What is SAVEPOINT?
A SAVEPOINT is a mark with in a transaction that allows for a partial rollback.

How Multiple Transactions can be controlled?


By using SAVEPOINT

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 : It scans through entire rows and displays only unique values.
SUM : Sum total of a numerical column.
COUNT : Count of the total number of rows satisfied by some query condition.
MIN : Returns the minimum value of exp.
MAX : Returns the maximum value of exp.
AVG : Returns the average value of exp.
ABS : Returns the absolute value of value.
POWER : Returns m raised to the nth power, n must be an integer, else an error is
returned.
Syntax : POWER(3,2)
ROUND : It is used to define the round value for the expr.
TRUNC : Returns a number truncated to a certain number of decimal places.
CEIL : Returns the smallest integer value that is greater than or equal to a
number.
FLOOR : Returns the largest integer value that is equal to or less than a number.
MOD : Returns remainder of a first number divided by second number.
SQRT : Returns square root of given number.
EXP : Returns exponential value for the given number.
LEAST : Returns the lowest value in a list.
GREATEST : Returns the greatest value in a list.
LOWER : Converts a string to all lowercase letters.
UPPER : Converts a string to all UPPERCASE letters.
INITCAP : Returns a string with the first letter of each word in upper case.
SUBSTR : Returns a portion of characters.
Syntax : SUBSTR (<string>,<start_position>,[<length>])
INSTR : Returns the location of a substring in a string.
Syntax : INSTR(<string>,<searching char>,<search position>,<occurrence>)
ASCII : Returns the number code that represents the specified character.
EXTRACT : Returns a value extracted from a date or an interval value. A date can
be used only to extract year, month and day.
EX: SELECT extract (year from date ‘2004-07-02') year from dual;
LTRIM : Removes characters from the left of char with initial characters
removed up to the first character
RTRIM : It is used to remove spaces after the string.
TRIM : Removes all specified characters from the beginning or the ending of a
string.
LPAD : Returns char1 left padded to length n with the sequence of characters
specified in char2. If char2 is not specified oracle uses blanks by
default.
RPAD : Returns char1 right padded to length n with the sequence of characters
specified in char2. If char2 is not specified oracle uses blanks by
default.
TRANSLATE : It replace char by char in a given string.
REPLACE : It replace word by word.
LENGTH : It returns no of characters in a given string.
TO_CHAR : Converts a DATE value or a NUMBER value into a character string.
TO_DATE : Converts a character string into a DATE value.
TO_NUMBER : Converts a character string or DATE into a number (ascii conversion).
ADD_MONTH : Returns date after adding the number of months specified in the
function
LAST_DAY : Returns the last date of the month specified in the function.
MONTHS_BETWEEN : Returns number of months between two dates.
NEXT_DAY : Returns the date of the first weekday named by char that is after the
date named by date.
VSIZE : Returns the number of bytes in the internal representation of an
expression.
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 : Decode is a function in sql it works like an IF-ELSE statement.

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.

What for NVL () Function?


NVL Function helps in substituting a value in place of a NULL.

What is the use of NVL2?


It lets you determine the value returned by a query based on whether a specified expression is null or
not null. If exp1 is not null then nvl2 returns exp2. If exp1 is null then nvl2 returns exp3.
What is the use of NULLIF?
It compares two strings expr, if they are equal then the function returns null. If they are not equal then
the function returns exp1.
Ex: SELECT e.ename,nullif(e.job,j.job) FROM emp e,emp j
WHERE e.empno = j.empno;

What is the use of COALESCE?


It returns the first not null expr in the expression list. At least one expr must not be the null. If all the
occurrences of expr evaluate to null then the function return null.
Ex: COALESCE (exp1,exp2,exp3,----)
If exp1 is null then exp2
If exp2 is null then exp3 and so on

For which relational operators in where clause, index is not used?


<>, like '% ...' is NOT functions, field +constant, field || ''

What is the difference between TO_DATE () and TO_CHAR () conversion Functions?


To_date converts character date to date format whereas
To_char function converts date or numerical values to characters.

What is the use of DECODE?


Decode statement is used to translate one value to another. Decode compares expr to each search value
one by one. If expr is equal to search then Oracle returns the corresponding result. If no match is
found then Oracle returns default.
Example:
SELECT ename,
sal,
decode(job,'marketing',0.10*sal,'clerk',0.5*sal,sal) "salary"
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;

What is the difference between MAX () and GREATEST () Functions?


MAX is an aggregate function which takes only one column name of a table as parameter whereas
Greatest is a general function which can take any number of values and column names from dual and
table respectively.

What is the use of ROLLUP?


ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified
group of dimensions. It also calculates a Grand Total.
Example:
SELECT deptno,
job,
sum(sal)
FROM emp
GROUP BY ROLLUP(deptno,job);

What is the use of CUBE?


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 deptno, job, sum(sal)
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 : all rows selected by either query, restricts the Duplicate rows.
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.

What are the various types of queries?


(i) Normal Queries
(ii) Sub Queries
(iii) Co-related queries
(iv) Compound queries

What is a Sub Query?


A sub query is a query with in a query. These sub query can reside in where clause, from clause or
select clause. It is also called nested query.
(i) A sub query used in the from clause of a select statement is called INLINE VIEW.
(ii) A sub query used in the where clause of a select statement is called NESTED sub Query.
What are the Limitations of sub query?
(i) Data displayed only from parent table.
(ii) Parent query can use only one table.

Special operators used for sub query:


EXISTS : 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 : All compares a value to every value returned by a sub query.

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
INNER JOIN dept d
ON e.deptno = d.deptno;

What is NON-EQUI JOIN?


It is used for range of values when one column of a table falls in the range of two columns of other
table. Here <, >, between operators used.
Ex: SELECT e.ename, e.job, e.sal, g.grade
FROM emp e, salgrade g
WHERE e.sal between g.losal and g.hisal
What is OUTER JOIN?
An inner join's ON condition retrieves only those records that satisfy the join condition. An outer join
does the same thing but with the addition of returning records for one table in which there were no
matching records in the other table
(i) LEFT OUTER JOIN : This join returns all the rows from the first table even if there are no
matches in the second table.
Ex: SELECT e.empno,e.ename,d.dname
FROM emp e LEFT OUTER JOIN detp d
ON e.deptno = d.deptno
[or]
SELECT e.empno,e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno = d.deptno(+)
(ii) RIGHT OUTER JOIN : This join returns all the rows from the second table even if there are no
matches in the first table.
Ex: SELECT e.empno,e.ename,d.dname
FROM emp e RIGHT OUTER JOIN detp d
ON e.deptno = d.deptno
(or)
SELECT e.empno,e.ename,d.dname
FROM emp e, dept d
WHERE e.deptno(+) = d.deptno
(iii) FULL OUTER JOIN : 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.

Ex: SELECT e.empno, e.ename, d.dname


FROM emp e FULL OUTER JOIN detp d
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.

NOT NULL Constraint - Disallows NULL values in a table's column.


UNIQUE Constraint - Disallows duplicate values in a column or set of columns.
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 - Disallows values that do not satisfy the logical expression of
the constraint.

What is difference between UNIQUE and PRIMARY KEY constraints?


A table can have only one PRIMARY KEY where as it can have number of UNIQUE KEYS.
PRIMARY KEY is a combination of UNIQUE KEY and NOT NULL.

What is ON DELETE CASCADE?


When this key word is included in the definition of a child table then whenever the records from the
parent table is deleted automatically the corresponding values in the child table will be deleted.

Where the integrity constraints are stored in Data Dictionary?


The integrity constraints are stored in USER_CONSTRAINTS.
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

What are CYCLE/NO CYCLE in a sequence?


When you create a sequence with cycle option, when the sequence reaches its MAXVALUE it will
start over at the MINVALUE. This is not recommended if sequence is for primary key creation.
When you create a sequence with no cycle option, when the sequence reaches its MAXVALUE it will
not start over at the MINVALUE. This option is safest if sequence is for primary key creation. When
the sequence reaches its MAXVALUE an oracle error will shown.

Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference
we get the next number 2. Suppose at this point we issue a rollback and again issue a nextval.
What will the output be?
The output will be 3

What is a view?
View is a logical table based on one or more tables or views. It contains no data, it contains only
SELECT statement. The view is logically & physically independent from table.
Syntax : CREATE or REPLACE view <view_name> AS select * from <table name>;
• Provide an additional level of table security by restricting access to a predetermined set of
rows and/or columns of a table
• Hide data complexity
• Simplify commands for the user
• Present the data in a different perspective from that of the base table
• Isolate applications from changes in definitions of base tables
• Express a query that cannot be expressed without using a view

What are the advantages of VIEW?


(i) To protect some of the columns of a table from other users.
(ii) To hide complexity of a query.
(iii) To hide complexity of calculations.
What is the difference between SIMPLE and COMPLEX VIEWS?
Simple views can be modified whereas Complex views (created based on more than one table) cannot
be modified.

How to update COMPLEX VIEW?


Using 'INSTEAD OF' TRIGGERS Complex views can be updated.

What are the types of views?


There are 4 types of views
(i) Inline view : When we write a query inside of another query from clause
then we will call it as inline view.
(ii) Updateable view : if the view is created from a single table and if doesn't contain
any aggregate functions then that view is called as 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 : MATERIALISED view definition includes any no of
aggregates as well as any no of joins in several ways. Behaves
like an index. It is used to increase the query execution
performance.

How can you find out View is updatable or not?


We can find out the view is up datable or not by seeing the definition of that 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 Materialized View
1. View can be created based on 1. Materialized can be creates based on
Tables, Sequences and other Tables, Views and other Materialized
views. views.
2. View will have only the select 2. Materialized view will have the result of
statement. the query
3. If the source table dropped 3. If the source table dropped then
then view will be invalid. Materialized View will exist.
4. Manipulations on view will be 4. Manipulations on this view will be
reflected automatically in table. reflected in table by using ‘REFRESH' on
commit option only.

What is the difference between view and table?


View is a virtual table. Every view has a Query attached to it. It has only structure, data is not there in
views. It gets data from base table.
A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of
the user accessible data. Table data is stored in rows and columns.

Can a trigger written for a view?


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 : A Snap Shot is a replication of master table from a single point-in-time
Snapshots are updated by one or more master tables via individual
batch updates are known as refresh.
MATERIALIZED VIEW : Materialized view will be created to access the base table information
and it is not possible to do DML operations on that

What is the difference between view and Snapshot?


View stores the select statement only. View is a virtual table to join one or more table or to prevent
access from users on complete data on table. Whenever we will access the view that brings the data
from tables only, not from view(it won't store any kind of data).
The snapshot stores the query result data. Usually we will use to get remote data to replicate the
changes made at remote site.

What is a SYNONYM?
A synonym is an alternative name for objects such as tables, views, sequences, stored procedures and
other database objects. Generally when we have more than one schema and we wish to access an
object of a different schema then we create synonyms for that object in the schema where we wish to
access the object.
It is used to hide the information, some times we create synonym to give short name of the object.
Types of synonym:
 Private – created by user--default
 Public – created by DBA
Syntax: CREATE synonym <synonym_name> for <object_name>

What is the difference between PRIVATE AND PUBLIC SYNONYM?


Only the user or table owner can reference Private synonym whereas any user can reference the Public
synonym.

What is the difference between alias and synonym?


Alias is temporary and used with one query. Synonym is permanent and not used as alias

If we delete the base table whether the synonym will exists or not? If we use that synonym what
type of error we will get?
The SYNONYM will be exists even though the Table was dropped.
If we use that synonym the following errors will come
ORA-00980: synonym translation is no longer valid
ORA-00903: invalid table name
ORA-04043: object SCOTT.T1 does not exist

What is the difference between a view and a synonym?


Synonym is just a second name of table used for multiple link of database. Synonym can be created
based on one table and we cannot use any conditions.
View can be created with many tables, and with virtual columns and with conditions.

Can database trigger written on synonym of a table and if it can be then what would be the
effect if original table is accessed.
Yes, database trigger would fire.

You might also like