Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 14

SQL INTERVIEW QUESTIONS

1. What is the use of CASCADE CONSTRAINTS?

When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.

2. What are the different categories of SQL statements?

DDL, DML, DCL, Session Control, System Control.

3. What are the wildcards used for pattern matching?

Underscore (_) for single character substitution & % for multi-character substitution.

4. Why does the following command give a compilation error?


DROP TABLE &TABLE_NAME;

Variable names should start with an alphabet. Here the table name starts with ‘&'
symbol. Any table name must start with alphabet. Table names starting with special characters
are considered to be invalid hence give error.

5. How can I hide a particular table name of our schema?

You can hide the table name by creating synonyms.

(e.g.) You can create a synonym y for table x

create synonym y for x;

6. What is the parameter substitution symbol used with INSERT INTO command?

&

7. What will be the output of the following query?

SELECT REPLACE (TRANSLATE (LTRIM (RTRIM ('!!ATHEN!!','!'),'!'),'AN','**'),'*','TROUBLE')


FROM DUAL;

Ans: TROUBLETHETROUBLE.

8. Difference between VARCHAR and VARCHAR2?

Varchar means fixed length character data (size) i.e., min size-1 and max-2000.
Varchar2 means variable length character data i.e., min-1 to max-4000.

Varchar assigns total length to data. Suppose we have name [20], now with the case of
if we entered NARINDER, totally 20 cells will be occupied. But in case of varchar2, 8 cells of
memory coz there are 8 elements in that data.

9. What is the difference between DBMS and RDBMS?

1.RDBMS = DBMS + Referential Integrity

2. An RDBMS is one that follows 12 rules of CODD.

10. When we give SELECT * FROM EMP; How does oracle respond?

When u give SELECT * FROM EMP; the server check all the data in the EMP file and it
displays the data of the EMP file. When we give select * from emp it will shows the records of
table emp if the table contain records. If it hasn't any records then it will shows no rows
selected.

11. Which system table contains information on privileges granted and privileges
obtained?

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

12. Which system table contains information on constraints on all the tables created?

USER_CONSTRAINTS

13. What is the output of the following query SELECT TRUNC(1234.5678, -2) FROM DUAL;

1200

14. What is the use of DESC in SQL?

DESC has two purposes. It is used to describe a schema as well as to retrieve rows
from table in descending order.

Explanation:

The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output
sorted on ENAME in descending order.

15. State True or False: EXISTS, SOME, ANY are operators in SQL?

True

16. There are two tables, Employee and Department. There are few records in employee
table, for which, the department is not assigned. The output of the query should contain
all the employees’ names and their corresponding departments, if the department is
assigned otherwise employee names and null value in the place department name. What
is the query?

What you want to use here is called a left outer join with Employee table on the left side.
A left outer join as the name says picks up all the records from the left table and based on the
joint column picks the matching records from the right table and in case there are no matching
records in the right table, it shows null for the selected coloumns of the right table. eg in this
query which uses the key-word LEFT OUTER JOIN. syntax though varies across databases. In
DB2/UDB it uses the key word LEFT OUTER JOIN, in case of Oracle the connector is
Employee_table.Dept_id *= Dept_table.Dept_id

SQL Server/Sybase :

Employee_table.Dept_id(+) = Dept_table.Dept_id

17. What command is used to create a table by copying the structure of another table?

CREATE TABLE.. AS SELECT command

Explanation:

To copy only the structure, the WHERE clause of the SELECT command should contain
a false statement as in the following.

CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;

If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied
to the new table.

18. State True or False: !=, <>, ^= all denotes the same operation?

True

19. Which function is used to find the largest integer less than or equal to a specific
value?

FLOOR

20. What does the following query do?


SELECT SAL + NVL (COMM, 0) FROM EMP;

This displays the total salary of all employees. The null values in the commission column
will be replaced by 0 and added to salary.

21. There is Eno and Gender in a table. Eno has primary key and Gender has a check
constraints for the values 'M' and 'F'. While inserting the data into the table, M was
misspelled as F and F as M. What is the update statement to replace F with M and M with
F?
UPDATE <TABLENAME> SET GENDER= CASE WHERE GENDER='F' THEN 'M'
WHERE GENDER='M' THEN 'F';

22. What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table.

23. What is the difference between TRUNCATE and DELETE command?

Both will result in deleting all the rows in the table. TRUNCATE call cannot be rolled
back as it is a DDL command and all memory space for that table is released back to the server
TRUNCATE is much faster. Whereas DELETE call is an DML command and can be rolled back.

24. Consider the below statements,


TRUNCATE TABLE EMP;
DELETE FROM EMP;
Will the outputs of the above two commands differ?

Both will result in deleting all the rows in the table EMP.

25. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?

The privilege receiver can further grant the privileges he/she has obtained from the
owner to any other user.

26. Which date function is used to find the difference between two dates?

MONTHS_BETWEEN

27. Why you need indexing? Where that is stored and what you mean by schema object?
For what purpose we are using view?

We can’t create an Index on Index. Index is stored in user_index table. Every object that
has been created on Schema is Schema Object like Table, View etc. If we want to share the
particular data to various users we have to use the virtual table for the Base table. So that is a
view. Indexing is used for faster search or to retrieve data faster from various table. Schema
containing set of tables, basically schema means logical separation of the database. View is
crated for faster retrieval of data. It's customized virtual table. we can create a single view of
multiple tables. Only the drawback is, view needs to be getting refreshed for retrieving updated
data.

28. How to find second maximum value from table?

SELECT MAX (FIELD1) FROM TNAME1 WHERE FIELD1=(SELECT MAX (FIELD1) FROM
TNAME1 WHERE FIELD1<(SELECT MAX (FIELD1) FROM TNAME1);

Field1- Salary field


Tname= Table name.

29. How can we backup the SQL files?

You can backup the SQL files through backup utilities or some backup command in SQL. SAP
is ERP software for the organization to integrate the software.

30. How to find out the 10th highest salary in SQL query?

Table - Tbl_Test_Salary
Column - int_salary

SELECT MAX (INT_SALARY)


FROM TBL_TEST_SALARY
WHERE INT_SALARY IN
(SELECT TOP 10 INT_SALARY FROM TBL_TEST_SALARY ORDER BY INT_SALARY)

31. What operator performs pattern matching?

LIKE operator

32. What is Database?

A database is a collection of data that is organized so that itscontents can easily be


accessed, managed and updated.

33. What is the value of Comm & Sal after executing the following query if the initial value
of 'Sal' is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL * 0.1;

Sal = 11000, Comm = 1000

34. What is the advantage to use trigger in your PL?

Triggers are fired implicitly on the tables/views on which they are created. There are various
advantages of using a trigger. Some of them are:

- Suppose we need to validate a DML statement (insert/Update/Delete) that modifies a table


then we can write a trigger on the table that gets fired implicitly whenever DML statement is
executed on that table.

- Another reason of using triggers can be for automatic updating of one or more tables
whenever a DML/DDL statement is executed for the table on which the trigger is created.

- Triggers can be used to enforce constraints. For eg : Any insert/update/ Delete statements
should not be allowed on a particular table after office hours. For enforcing this constraint
Triggers should be used.

- Triggers can be used to publish information about database events to subscribers. Database
event can be a system event like Database startup or shutdown or it can be a user even like
User login in or user logoff.

35. Which command displays the SQL command in the SQL buffer, and then executes it?

You set the LIST or L command to get the recent one from SQL Buffer

36. What the difference between UNION and UNION ALL?

Union will remove the duplicate rows from the result set while Union all doesn’t

37. How to store directory structure in a database?

We can do it by the following command,

CREATE OR REPLACE DIRECTORY AS 'C:\TMP'

38. How to copy SQL table?

COPY FROM DATABASE TO DATABASE ACTION -

DESTINATION_TABLE (COLUMN_NAME, COLUMN_NAME...) USING QUERY

Example:

COPY FROM SCOTT/TIGER@ORCL92 -

TO SCOTT/TIGER@ORCL92-

CREATE NEW_EMP –

USING SELECT * FROM EMP;

39. Which command executes the contents of a specified file?

START <filename> or @<filename>

40. What are the different types of Normalization forms?

There are five normal forms. It is necessary for any database to be in the third normal
form to maintain referential integrity and non-redundancy.

First Normal Form


Every field of a table (row, column) must contain an atomic value.

Second Normal Form


All columns of a table must depend entirely on the primary key column.

Third Normal Form


All columns of a table must depend on all columns of a composite primary key.

Fourth Normal Form


A table must not contain two or more independent multi-valued facts. This normal form is
often avoided for maintenance reasons.

Fifth Normal Form


It is about symmetric dependencies.

Each normal form assumes that the table is already in the earlier normal form.

41. What command is used to get back the privileges offered by the GRANT command?

REVOKE

42. What are the privileges that can be granted on a table by a user to others?

INSERT, UPDATE, DELETE, SELECT, REFERENCES, INDEX, EXECUTE, ALTER, ALL

43. Which is the subset of the SQL commands used to manipulate Oracle database
structures?

Data Definition Language (DDL)

44. What is Materialized View?

A materialized view is a database object that contains the results of a query. They are
local copies of data located remotely or used to create summary tables based on aggregation of
a tables data. Materialized views, which store data based on the remote tables are also, know
as snapshots.

45. How to write a SQL statement to find the first occurrence of a Non-Zero value?

There is a slight chance the column "a" has a value of 0 which is not null. In that case,
you'll loose the information. There is another way of searching the first not null value of a
column:

SELECT COLUMN_NAME FROM TABLE_NAME WHERE COLUMN_NAME IS NOT NULL


AND ROWNUM<2;

46. Is there any query which is use to find the case sensitivity in each records in
database through visual basic?

For case sensitive string comparison in SQL one has to use substring() and ascii()
functions in the following way.

Get first character of both strings using substring function as substring(str1, 1, 1)


Find ascii value of both characters and compare.
Put statements 1 and 2 in loop to advance to next character
For example if (ascii(substring(str1, @pos, 1)) = ascii(substring(str2, @pos, 1)) then @pos =
@pos + 1.

47. Which system table contains information on constraints on all the tables created?

USER_CONSTRAINTS

48. What operator tests column for the absence of data?

IS NULL operator.

49. If DELETE ANY TABLE in back-end then what are the triggers will fire automatically
(Those triggers are back-end triggers only)?

Oracle has Schema triggers (CREATE OR REPLACE TRIGGER ... ON SCHEMA ... that will
file on DDL commands. You can do things like

CREATE OR REPLACE TRIGGER SAVE_OUR_DB


BEFORE DROP OR TRUNCATE ON SCHEMA

to stop/log attempts to drop a table.

50. How to write a SQL statement to query the result set and display row as columns and
columns as row?

TRANSFORM COUNT(ROLL_NO) AS COUNTOFROLL_NO SELECT ACADEMIC_STATUS


FROM TBL_ENR_STATUS GROUP BY ACADEMIC_STATUS PIVOT CURNT_STATUS;

51. What is difference between Oracle & MS Access? What are the disadvantages in
Oracle and MS Access? What are features in Oracle and MS Access?

Oracle's features for distributed transactions, materialized views and replication are not
available with MS Access. These features enable oracle to efficiently store data for multinational
companies across the globe. Also these features increase scalability of applications based on
Oracle.

52. What will be the output of the following query? SELECT DECODE (TRANSLATE
(‘A’,’1234567890’,’1111111111’), '1','YES', ‘NO’);?

No.

Explanation:

The query checks whether a given string is a numerical digit.

53. Given an employee and manager table, write a SQL syntax that could be used to find
out an employee's manager's manager, assuming all managers are in the employee
table?
It is assumed that u have created a single table for populating data of Employee and
Manager (.a Manager is also an Employee so s/he will be residing in the same table).

The sample data would be like this


EmployeeID ----- EmployeeName ------- ManagerID

1 Akhtar 0

2 Bilal 1

3 Faheem 2

** This query will return "Akhtar" for given EmployeeID = 3.

SELECT m.EmployeeName FROM #EmpTemp m WHERE m.EmloyeeID = (SELECT


e.ManagerID FROM #EmpTemp e WHERE e.EmloyeeID = (Select t.ManagerID
FROM #EmpTemp t WHERE t.EmloyeeID = 3))

** This is solution is workable in case of 3-levels only not even to 2-levels of hierarchy. An n-
level solution can be achieved by writing a Recursive stored procedure and that will also be
given soon.

The best query is to create the dummy table and then make the relations,

SELECT EMP.EMPLOYEEID, EMP.EMPLOYEENAME, EMP.MANAGERID,


EMPTEMP.EMPLOYEENAME MANAGER
FROM EMPLOYEES EMP ,EMPLOYEES EMPTEMP
WHERE EMP.MANAGERID=EMPTEMP.EMPLOYEEID

54. In sub-queries, which is efficient, the IN clause or EXISTS clause? Does they produce
the same result?

55. When using COUNT (DISTINCT) is it better to use a self-join or temp table to find
redundant data, and provide an example?

Instead of this we can use GROUP BY Clause with HAVING condition.

For ex,

SELECT COUNT(*),LASTNAME FROM TBLUSERS GROUP BY LASTNAME HAVING


COUNT(*)>1

This query return the duplicated lastnames values in the lastname column from tblUsers table.

56. What are the advantages and disadvantages of primary key and foreign key in SQL?

Primary key

Advantages
1) It is a unique key on which all the other candidate keys are functionally dependent

Disadvantage

1) There can be more than one keys on which all the other attributes are dependent on.

Foreign Key

Advantage

1) It allows referencing another table using the primary key for the other table.

57. What is difference between Co-related sub query and nested sub query?

Correlated sub-query runs once for each row selected by the outer query. It contains a
reference to a value from the row selected by the outer query.

Nested sub-query runs only once for the entire nesting (outer) query. It does not contain
any reference to the outer query row.

For example,

Correlated Sub-query:

SELECT E1.EMPNAME, E1.BASICSAL, E1.DEPTNO FROM EMP E1 WHERE E1.BASICSAL


= (SELECT MAX (BASICSAL) FROM EMP E2 WHERE E2.DEPTNO = E1.DEPTNO)

Nested Sub-query:

SELECT EMPNAME, BASICSAL, DEPTNO FROM EMP WHERE (DEPTNO, BASICSAL) IN


(SELECT DEPTNO, MAX(BASICSAL) FROM EMP GROUP BY DEPTNO)

58. What is the back end processes when we type "SELECT * FROM TABLE"?

First it will look into the System Global Area (SGA) weather the query is been executed
earlier. If it exists, it would retrieve the same output present in memory. If not the query we
typed is complied and the resulting parse tree and execution plan is been stored in SGA. Then
query gets executed and output is given to the application.

59. What is a Cursor?

To retrieve data with SQL one row at a time you need to use cursor processing. Not all
relational databases support this, but many do. Here I show this in Oracle with PL/SQL, which is
Procedural Language SQL. Cursor processing is done in several steps:1. Define the rows you
want to retrieve. This is called declaring the cursor.2. Open the cursor. This activates the cursor
and loads the data. Note that declaring the cursor doesn't load data, opening the cursor does.3.
Fetch the data into variables.4. Close the cursor.

60. How do I write a cron, which will run a SQL query and mail the results to a group?

Use DBMS_JOB for scheduling a cron job and DBMS_MAIL to send the results through email.

61. Can we call user-defined packages in SQL statements?

I do not agree that we can't call user- defined packages in the SQL statements. Instead
we can call user defined packaged functions in the SELECT statement.
e.g. SELECT pkg.test(10) FROM DUAL;

62. What is table space?

Table-space is a physical concept. It has pages where the record of the database is
stored with a logical perception of tables. So table space contains tables.

63. Explain normalization with examples?

Normalization is a process of eliminating the redundancy and increasing the integrity.

64. Given an unnormalized table with columns?

The query will be:

DELETE FROM TABNAME WHERE ROWID NOT IN (SELECT MAX (ROWID) FROM
TABNAME GROUP BY NAME;

Here tabname is the table name

65. What is Reference cursor?

Reference cursor is dynamic cursor used with SQL statement like For select* from emp;

66. What is the difference between SQL and SQL Server?

SQLServer is an RDBMS just like oracle, DB2 from Microsoft whereas Structured Query
Language (SQL), pronounced "sequel", is a language that provides an interface to relational
database systems. IBM developed it in the 1970s for use in System R. SQL is a de facto
standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on
RDBMS.

67. Difference between Store Procedure and Trigger?

Information related to Stored procedure you can see in,


USER_SOURCE, USER_OBJECTS (current user) tables

Information related to triggers stored in USER_SOURCE,USER_TRIGGERS (current


user) Tables.
Stored procedure can't be inactive but trigger can be Inactive.

68. I have a table with duplicate names in it. Write me a query which returns only
duplicate rows with number of times they are repeated?

SELECT COL1 FROM TAB1


WHERE COL1 IN
(SELECT MAX (COL1) FROM TAB1
GROUP BY COL1
HAVING COUNT (COL1) > 1 )

69. What is cluster? What is cluster index & non-cluster index?

Clustered Index: - A Clustered index is a special type of index that reorders the way records in
the table are physically stored. Therefore table may have only one clustered index. Non-
Clustered Index:- A Non-Clustered index is a special type of index in which the logical order of
the index does not match the physical stored order of the rows in the disk. The leaf nodes of a
non-clustered index do not consists of the data pages. Instead the leaf node contains index
rows.

70. How to display duplicate rows in a table?

71. What is the difference between ORACLE, SQL, and SQL SERVER?

Oracle is based on RDBMS.

SQL is Structured Query Language.

SQL Server is another tool for RDBMS provided by Microsoft.

72. How to retrieving the data from 11th column to nth column in a table?

SELECT * FROM EMP WHERE ROWID IN ( SELECT ROWID FROM EMP WHERE ROWNUM
<=&UPTO
MINUS
SELECT ROWID FROM EMP WHERE ROWNUM <&STARTFROM)

from this you can select between any range.

73. Difference between decode and case. In which case we are using case and in which
case we are using decode? Explain with an example?

First I will give one example using 'decode'

SQL>SELECT ENAME, SAL, DECODE (DEPTNO, 10, 'ACCOUNTING', 20,'RESEARCH',


30,'SALES', 40,'OPERATIONS','OTHERS') "DEPARTMENTS" FROM EMP;
I have used the decode function on 'deptno' column. It will give the user-friendly output.
instead of using 'accounting', ‘research’. We can use anything we want to get the friendly
outputs.

I have to check-out the 'case' function after that I will give an example using CASE
expression we can use all comparative operators (<, >, ==, etc), where as using DECODE we
should always use = condition.

74. What is the main difference between the IN and EXISTS clause in sub-queries?

The main difference between the IN and EXISTS predicate in sub-query is the way in
which the query gets executed.

IN -- The inner query is executed first and the list of values obtained as its result is used by the
outer query. The inner query is executed for only once.

EXISTS -- The first row from the outer query is selected, then the inner query is executed and ,
the outer query output uses this result for checking. This process of inner query execution
repeats as many no. of times as there are outer query rows. That is, if there are ten rows that
can result from outer query, the inner query is executed that many no. of times.

75. Difference between an equi-join and union?

Indeed both equi join and the Union are very different. Equi join is used to establish a condition
between two tables to select data from them.. eg

SELECT A.EMPLOYEEID, A.EMPLOYEENAME, B.DEPT_NAME FROM

EMPLOYEEMASTER A , DEPARTMENTMASTER B

WHERE A.EMPLOYEEID = B.EMPLOYEEID;

This is the example of equijoin whereas with a Union allows you to select the similar data based
on different conditions eg

SELECT A.EMPLOYEEID, A.EMPLOYEENAME FROM

EMPLOYEEMASTER A WHERE A.EMPLOYEEID >100 B.EMPLOYEEID

UNION

SELECT A.EMPLOYEEID, A.EMPLOYEENAME FROM

EMPLOYEEMASTER A WHERE A.EMPLOYEENAME LIKE 'B%'


the above is the example of Union where in we select employee name and Id for two different
conditions into the same record set and is used thereafter.

76. How to find out the database name from SQL*PLUS command prompt?

SELECT * FROM GLOBAL_NAME;

This will give the database name which you are currently connected to.

77. What is the difference between Single row sub-Query and Scalar sub-Query?

Single row sub-query returns a value that is used by where clause, whereas scalar sub-
query is a select statement used in column list can be thought of as an inline function in select
column list.

You might also like