Professional Documents
Culture Documents
SQL 100 Questions
SQL 100 Questions
When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.
Underscore (_) for single character substitution & % for multi-character substitution.
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.
6. What is the parameter substitution symbol used with INSERT INTO command?
&
Ans: TROUBLETHETROUBLE.
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.
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
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?
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain
a false statement as in the following.
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
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?
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.
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.
SELECT MAX (FIELD1) FROM TNAME1 WHERE FIELD1=(SELECT MAX (FIELD1) FROM
TNAME1 WHERE FIELD1<(SELECT MAX (FIELD1) FROM TNAME1);
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
LIKE operator
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;
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:
- 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
Union will remove the duplicate rows from the result set while Union all doesn’t
Example:
TO SCOTT/TIGER@ORCL92-
CREATE NEW_EMP –
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.
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?
43. Which is the subset of the SQL commands used to manipulate Oracle database
structures?
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:
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.
47. Which system table contains information on constraints on all the tables created?
USER_CONSTRAINTS
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
50. How to write a SQL statement to query the result set and display row as columns and
columns as row?
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:
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).
1 Akhtar 0
2 Bilal 1
3 Faheem 2
** 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,
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?
For ex,
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:
Nested Sub-query:
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.
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.
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;
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.
DELETE FROM TABNAME WHERE ROWID NOT IN (SELECT MAX (ROWID) FROM
TABNAME GROUP BY NAME;
Reference cursor is dynamic cursor used with SQL statement like For select* from emp;
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.
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?
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.
71. What is the difference between ORACLE, SQL, and SQL SERVER?
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)
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?
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.
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
EMPLOYEEMASTER A , DEPARTMENTMASTER B
This is the example of equijoin whereas with a Union allows you to select the similar data based
on different conditions eg
UNION
76. How to find out the database name from SQL*PLUS command prompt?
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.