Вы находитесь на странице: 1из 28

 How can we retrieve alternate records from a table in Oracle?

 Given a list of student names and grade. Write a query to print a comma separated
list of student names in a grade.
 Write SQL Query to get Student Name and number of Students in same grade.
 Write SQL query to delete duplicate rows in a table?
 Write SQL query to get the second highest salary among all Employees?
 Write SQL Query to get Employee Name, Manager ID and number of employees in
the department?
 Write SQL query to get the nth highest salary among all Employees.
 Given an Employee table with Manager_ID as column, print First name, Manager
ID and Level of employees in Organization Structure?
 Why is the difference between NVL and NVL2 functions in SQL?
 What is the difference between UNION and UNION ALL?
 What are the reasons for de-normalizing the data?
 What is a Pseudocolumn?
 How can you find 10 employees with Odd number as Employee ID?
 What is the difference between DELETE and TRUNCATE in SQL?
 Which SQL feature can be used to view data in a table sequentially?
 What are the differences between CASE and DECODE in SQL?
 Write a SQL Query to get the Quarter from date.

1. What are the two authentication modes in SQL Server?

There are two authentication mode

 Windows mode
 Mixed mode
2. What is the difference between Clustered and Non-Clustered Index?

Clustered index

 The leaf level pages are the actual data pages of the table. The data pages are
arranged accordingly based on the clustered index key. There can only be one
Clustered index on a table.
Non- Clustered Index

 The leaf node of a Non-clustered index does not consist of the data pages. Instead,
the leaf nodes contain index.
3. What is SQL server agent?

 SQL is a component of Microsoft SQL server.


 SQL server agent plays a vital role in day to day task.
 Server agent purpose is to implement the task easily with the scheduler engine. It
allows our jobs and handles other automated scheduled date and time.
4. What is Trigger?

 Trigger is a database object that is attaches to the table.


 There are many aspects in its similar way to store a procedure.
 It is executed with automatically modified data, insert, delete, and update
operations.
 Trigger consists of event an insert, delete, update and an action.
 Triggers are used to preserve data integrity by checking on or changing data in a
consistent manner.
5. What are the different index configurations a table can have?

 Index configuration
 No indexes
 Clustered indexes
 Clustered index and many non-clustered indexes
 Non-clustered indexes
 Many non-clustered indexes
6. What are the properties and different Types of Sub-Queries?

Properties of sub Query

 A sub-query must be enclosed in the parenthesis.


 A sub-query must be put in the right hand of the comparison operator.
 A sub-query cannot contain an ORDER-BY clause.
 A query can contain more than one sub-query.
Types of sub Query

 Single Row Sub Query: The sub query returns only one row.
 Multiple Row Sub Query: The sub query returns multiple rows.
 Multiple column Sub Query: The sub query returns multiple columns.
7. Can we check locks in database?

Yes,we can check locks in database.

8. What is DCL?

DCL is stands for Data Control Language.

9. What is fill factor and its value?

Fill Factor

 Fill Factor is a setting that is applicable to Indexes in SQL Server.


 The fill factor value determines how much data is written to an index page when it
is created or rebuilt.
Value

 Default the fill factor value is set to 0


10. What the different Topologies in which Replication can be configured?

 Replication can be configured in any topology depending keeping in view of the


complexity and the workload of the entire Replication.
 It can be any of the following Publisher, Distributor and Subscriber on the same
SQL Instance.
 Publisher and Distributor on the same SQL Instance and Subscriber on a separate
Instance.
 Publisher, Distributor and Subscriber on individual SQL Instances.
11. What are the different ways you can create Databases in SQL Server?

 T-SQL; Create Database command.


 Using Management Studio
 Restoring a database backup
 Copy Database wizard
12. What are the new features in SQL Server 2005 when compared to SQL
Server 2000?

 Database Partitioning
 Dynamic Management Views
 System Catalogue Views
 Resource Database
 Database Snapshots
 SQL Server Integration Services
 Support for Analysis Services on Failover Cluster.
 Profiler being able to trace the MDX queries of the Analysis Server.
 Peer-toPeer Replication
 Database Mirroring
13. What are the different types of database compression introduced in SQL
Server 2008?

 Row compression
 Page compression
14. What are the advantages of using Stored Procedures?

 Stored procedure can reduced network traffic and latency, boosting application
performance.
 Stored procedure execution plans can be reused, staying cached in SQL Server’s
memory, reducing server overhead.
 Stored procedures help promote code reuse.
 Stored procedures can encapsulate logic. You can change stored procedure code
without affecting clients.
 Stored procedures provide better security to your data.
15. Can SQL Servers linked to other servers like Oracle?

 SQL server can be linked to any server provided.


 It has OLE –DB provider from Microsoft allow to a link.

12. What is Denormalization.

DeNormalization is a technique used to access the data from higher to lower normal forms
of database. It is also process of introducing redundancy into a table by incorporating data
from the related tables.

13. What are all the different normalizations?


The normal forms can be divided into 5 forms, and they are explained below -.

First Normal Form (1NF):.

This should remove all the duplicate columns from the table. Creation of tables for the
related data and identification of unique columns.

Second Normal Form (2NF):.

Meeting all requirements of the first normal form. Placing the subsets of data in separate
tables and Creation of relationships between the tables using primary keys.

Third Normal Form (3NF):.

This should meet all requirements of 2NF. Removing the columns which are not dependent
on primary key constraints.

Fourth Normal Form (3NF):.

Meeting all the requirements of third normal form and it should not have multi- valued
dependencies.

14. What is a View?

A view is a virtual table which consists of a subset of data contained in a table. Views are
not virtually present, and it takes less space to store. View can have data of one or more
tables combined, and it is depending on the relationship.

15. What is an Index?

An index is performance tuning method of allowing faster retrieval of records from the table.
An index creates an entry for each value and it will be faster to retrieve data.

16. What are all the different types of indexes?

There are three types of indexes -.

Unique Index.

This indexing does not allow the field to have duplicate values if the column is unique
indexed. Unique index can be applied automatically when primary key is defined.

Clustered Index.

This type of index reorders the physical order of the table and search based on the key
values. Each table can have only one clustered index.

NonClustered Index.

NonClustered Index does not alter the physical order of the table and maintains logical
order of data. Each table can have 999 nonclustered indexes.
17. What is a Cursor?

A database Cursor is a control which enables traversal over the rows or records in the table.
This can be viewed as a pointer to one row in a set of rows. Cursor is very much useful for
traversing such as retrieval, addition and removal of database records.

18. What is a relationship and what are they?

Database Relationship is defined as the connection between the tables in a database.


There are various data basing relationships, and they are as follows:.

 One to One Relationship.


 One to Many Relationship.
 Many to One Relationship.
 Self-Referencing Relationship.
19. What is a query?

A DB query is a code written in order to get the information back from the database. Query
can be designed in such a way that it matched with our expectation of the result set. Simply,
a question to the Database.

20. What is subquery?

A subquery is a query within another query. The outer query is called as main query, and
inner query is called subquery. SubQuery is always executed first, and the result of
subquery is passed on to the main query.

21. What are the types of subquery?

There are two types of subquery – Correlated and Non-Correlated.

A correlated subquery cannot be considered as independent query, but it can refer the
column in a table listed in the FROM the list of the main query.

A Non-Correlated sub query can be considered as independent query and the output of
subquery are substituted in the main query.

22. What is a stored procedure?

Stored Procedure is a function consists of many SQL statement to access the database
system. Several SQL statements are consolidated into a stored procedure and execute
them whenever and wherever required.

23. What is a trigger?

A DB trigger is a code or programs that automatically execute with response to some event
on a table or view in a database. Mainly, trigger helps to maintain the integrity of the
database.

Example: When a new student is added to the student database, new records should be
created in the related tables like Exam, Score and Attendance tables.
24. What is the difference between DELETE and TRUNCATE commands?

DELETE command is used to remove rows from the table, and WHERE clause can be used
for conditional set of parameters. Commit and Rollback can be performed after delete
statement.

TRUNCATE removes all rows from the table. Truncate operation cannot be rolled back.

25. What are local and global variables and their differences?

Local variables are the variables which can be used or exist inside the function. They are
not known to the other functions and those variables cannot be referred or used. Variables
can be created whenever that function is called.

Global variables are the variables which can be used or exist throughout the program.
Same variable declared in global cannot be used in functions. Global variables cannot be
created whenever that function is called.

26. What is a constraint?

Constraint can be used to specify the limit on the data type of table. Constraint can be
specified while creating or altering the table statement. Sample of constraint are.

 NOT NULL.
 CHECK.
 DEFAULT.
 UNIQUE.
 PRIMARY KEY.
 FOREIGN KEY.
27. What is data Integrity?

Data Integrity defines the accuracy and consistency of data stored in a database. It can also
define integrity constraints to enforce business rules on the data when it is entered into the
application or database.

28. What is Auto Increment?

Auto increment keyword allows the user to create a unique number to be generated when a
new record is inserted into the table. AUTO INCREMENT keyword can be used in Oracle
and IDENTITY keyword can be used in SQL SERVER.

Mostly this keyword can be used whenever PRIMARY KEY is used.

29. What is the difference between Cluster and Non-Cluster Index?

Clustered index is used for easy retrieval of data from the database by altering the way that
the records are stored. Database sorts out rows by the column which is set to be clustered
index.

A nonclustered index does not alter the way it was stored but creates a complete separate
object within the table. It point back to the original table rows after searching.
30. What is Datawarehouse?

Datawarehouse is a central repository of data from multiple sources of information. Those


data are consolidated, transformed and made available for the mining and online
processing. Warehouse data have a subset of data called Data Marts.

31. What is Self-Join?

Self-join is set to be query used to compare to itself. This is used to compare values in a
column with other values in the same column in the same table. ALIAS ES can be used for
the same table comparison.

32. What is Cross-Join?

Cross join defines as Cartesian product where number of rows in the first table multiplied by
number of rows in the second table. If suppose, WHERE clause is used in cross join then
the query will work like an INNER JOIN.

33. What is user defined functions?

User defined functions are the functions written to use that logic whenever required. It is not
necessary to write the same logic several times. Instead, function can be called or executed
whenever needed.

34. What are all types of user defined functions?

Three types of user defined functions are.

 Scalar Functions.
 Inline Table valued functions.
 Multi statement valued functions.

Scalar returns unit, variant defined the return clause. Other two types return table as a
return.

35. What is collation?

Collation is defined as set of rules that determine how character data can be sorted and
compared. This can be used to compare A and, other language characters and also
depends on the width of the characters.

ASCII value can be used to compare these character data.

36. What are all different types of collation sensitivity?

Following are different types of collation sensitivity -.

 Case Sensitivity – A and a and B and b.


 Accent Sensitivity.
 Kana Sensitivity – Japanese Kana characters.
 Width Sensitivity – Single byte character and double byte character.
37. Advantages and Disadvantages of Stored Procedure?

Stored procedure can be used as a modular programming – means create once, store and
call for several times whenever required. This supports faster execution instead of
executing multiple queries. This reduces network traffic and provides better security to the
data.

Disadvantage is that it can be executed only in the Database and utilizes more memory in
the database server.

38. What is Online Transaction Processing (OLTP)?

Online Transaction Processing or OLTP manages transaction based applications which can
be used for data entry and easy retrieval processing of data. This processing makes like
easier on simplicity and efficiency. It is faster, more accurate results and expenses with
respect to OTLP.

Example – Bank Transactions on a daily basis.

39. What is CLAUSE?

SQL clause is defined to limit the result set by providing condition to the query. This usually
filters some rows from the whole set of records.

Example – Query that has WHERE condition

Query that has HAVING condition.

40. What is recursive stored procedure?

A stored procedure which calls by itself until it reaches some boundary condition. This
recursive function or procedure helps programmers to use the same set of code any
number of times.

41. What is Union, minus and Interact commands?

UNION operator is used to combine the results of two tables, and it eliminates duplicate
rows from the tables.

MINUS operator is used to return rows from the first query but not from the second query.
Matching records of first and second query and other rows from the first query will be
displayed as a result set.

INTERSECT operator is used to return rows returned by both the queries.

42. What is an ALIAS command?

ALIAS name can be given to a table or column. This alias name can be referred in WHERE
clause to identify the table or column.

Example-.
1 Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex. StudentID

Here, st refers to alias name for student table and Ex refers to alias name for exam table.

43. What is the difference between TRUNCATE and DROP statements?

TRUNCATE removes all the rows from the table, and it cannot be rolled back. DROP
command removes a table from the database and operation cannot be rolled back.

44. What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and return single values.
This can be calculated from the columns in a table. Scalar functions return a single value
based on the input value.

Example -.

Aggregate – max(), count – Calculated with respect to numeric.

Scalar – UCASE(), NOW() – Calculated with respect to strings.

45. How can you create an empty table from an existing table?

Example will be -.

1 Select * into studentcopy from student where 1=2

Here, we are copying student table to another table with the same structure with no rows
copied.

46. How to fetch common records from two tables?

Common records result set can be achieved by -.


1 Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam

47. How to fetch alternate records from a table?

Records can be fetched for both Odd and Even row numbers -.

To display even numbers-.

1 Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0

To display odd numbers-.

1 Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

from (Select rowno, studentId from student) where mod(rowno,2)=1.[/sql]

48. How to select unique records from a table?

Select unique records from a table by using DISTINCT keyword.

1 Select DISTINCT StudentID, StudentName from Student.


49. What is the command used to fetch first 5 characters of the string?

There are many ways to fetch first 5 characters of the string -.

1 Select SUBSTRING(StudentName,1,5) as studentname from student

1 Select RIGHT(Studentname,5) as studentname from student

50. Which operator is used in query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % – Matches zero or more characters.


2. _(Underscore) – Matching exactly one character.
Example -.

1 Select * from Student where studentname like ‘a%’

1 Select * from Student where studentname like ‘ami_’


Performance Related Questions

Q:-1. What is SQL Query Optimization?

Ans. Query Optimization is the process of writing the query in a way so that it could execute
quickly. It is a significant step for any standard application.

Q:-2. What are some tips to improve the performance of SQL queries?

Ans. Optimizing SQL queries can bring substantial positive impact on the performance. It
also depends on the level of RDBMS knowledge you have. Let’s now go over some of the
tips for tuning SQL queries.

1. Prefer to use views and stored procedures in spite of writing long queries. It’ll also help in
minimizing network load.

2. It’s better to introduce constraints instead of triggers. They are more efficient than triggers
and can increase performance.

3. Make use of table-level variables instead of temporary tables.

4. The UNION ALL clause responds faster than UNION. It doesn’t look for duplicate rows
whereas the UNION statement does that regardless of whether they exist or not.

5. Prevent the usage of DISTINCT and HAVING clauses.

6. Avoid excessive use of SQL cursors.

7. Make use of SET NOCOUNT ON clause while building stored procedures. It represents
the rows affected by a T-SQL statement. It would lead to reduced network traffic.
8. It’s a good practice to return the required column instead of all the columns of a table.

9. Prefer not to use complex joins and avoid disproportionate use of triggers.

10. Create indexes for tables and adhere to the standards.

Q:-3. What are the bottlenecks that affect the performance of a Database?

Ans. In a web application, the database tier can prove to be a critical bottleneck in achieving
the last mile of scalability. If a database has performance leakage, that can become a
bottleneck and likely to cause the issue. Some of the common performance issues are as
follows.

1. Abnormal CPU usage is the most obvious performance bottleneck. However, you can fix
it by extending CPU units or replacing with an advanced CPU. It may look like a simple
issue but abnormal CPU usage can lead to other problems.

2. Low memory is the next most common bottleneck. If the server isn’t able to manage the
peak load, then it poses a big question mark on the performance. For any application,
memory is very critical to perform as it’s way faster than the persistent memory. Also, when
the RAM goes down to a specific threshold, then the OS turns to utilize the swap memory.
But it makes the application to run very slow.

You can resolve it by expanding the physical RAM, but it won’t solve memory leaks if there
is any. In such a case, you need to profile the application to identify the potential leaks
within its code.
3. Too much dependency on external storage like SATA disk could also come as a
bottleneck. Its impact gets visible while writing large data to the disk. If output operations
are very slow, then it is a clear indication an issue becoming the bottleneck.

In such cases, you need to do scaling. Replace the existing drive with a faster one. Try
upgrading to an SSD hard drive or something similar.

Q:-4. What are the steps involved in improving the SQL performance?

Ans.

Discover – First of all, find out the areas of improvement. Explore tools like Profiler, Query
execution plans, SQL tuning advisor, dynamic views, and custom stored procedures.

Review – Brainstorm the data available to isolate the main issues.

Propose – Here is a standard approach one can adapt to boost the performance. However,
you can customize it further to maximize the benefits.

1. Identify fields and create indexes.

2. Modify large queries to make use of indexes created.

3. Refresh table and views and update statistics.

4. Reset existing indexes and remove unused ones.

5. Look for dead blocks and remove them.

Validate – Test the SQL performance tuning approach. Monitor the progress at a regular
interval. Also, track if there is any adverse impact on other parts of the application.
Publish – Now, it’s time to share the working solution with everyone in the team. Let them
know all the best practices so that they can use it with ease.

Back to top

Q:-5. What is a explain plan?

Ans. It’s a term used in Oracle. And it is a type of SQL clause in Oracle which displays the
execution plan that its optimizer plans for executing the
SELECT/UPDATE/INSERT/DELETE statements.

Q:-6. How do you analyze an explain plan?

Ans. While analyzing the explain plan, check the following areas.

1. Driving Table

2. Join Order

3. Join Method

4. Unintentional cartesian product

5. Nested loops, merge sort, and hash join

6. Full Table Scan

7. Unused indexes

8. Access paths

Q:-7. How do you tune a query using the explain plan?

Ans. The explain plan shows a complete output of the query costs including each subquery.
The cost is directly proportional to the query execution time. The plan also depicts the
problem in queries or sub-queries while fetching data from the query.
Q:-8. What is Summary advisor and what type of information does it provide?

Ans. Summary advisor is a tool for filtering and materializing the views. It can help in
elevating the SQL performance by selecting the proper set of materialized views for a given
workload. And it also provides data about the Materialized view recommendations.

Q:-9. What could most likely cause a SQL query to run as slow as 5 minutes?

Ans. Most probably, a sudden surge in the volume of data in a particular table could slow
down the output of a SQL query. So collect the required stats for the target table. Also,
monitor any change in the DB level or within the underlying object level.

Q:-10. What is a Latch Free Event? And when does it occur? Alos, how does the system
handles it?

Ans. In Oracle, Latch Free wait event occurs when a session requires a latch, attempts to
get it but fails because someone else has it.

So it sleeps with a wait eying for the latch to get free, wakes up and tries again. The time
duration for it was inactive is the wait time for Latch Free. Also, there is no ordered queue
for the waiters on a latch, so the one who comes first gets it.

Back to top

Q:-11. What is Proactive tuning and Reactive tuning?


Ans.

Proactive tuning – The architect or the DBA determines which combination of system
resources and available Oracle features fulfill the criteria during Design and Development.

Reactive tuning – It is the bottom-up approach to discover and eliminate the bottlenecks.
The objective is to make Oracle respond faster.

Q:-12. What are Rule-based Optimizer and Cost-based Optimizer?

Ans. Oracle determines how to get the required data for processing a valid SQL statement.
It uses one of following two methods to take this decision.

Rule-based Optimizer – When a server doesn’t have internal statistics supporting the
objects referenced by the statement, then the RBO method gets preference. However,
Oracle will deprecate this method in the future releases.

Cost-based Optimizer – When there is an abundance of the internal statistics, the CBO gets
the precedence. It verifies several possible execution plans and chooses the one with the
lowest cost based on the system resources.

Q:-13. What are several SQL performance tuning enhancements in Oracle?

Ans. Oracle provides many performance enhancements, some of them are:

1. Automatic Performance Diagnostic and Tuning Features


2. Automatic Shared Memory Management – It gives Oracle control of allocating memory
within the SGA.

3. Wait-model improvements – A number of views have come to boost the Wait-model.

4. Automatic Optimizer Statistics Collection – Collects optimizer statistics using a scheduled


job called GATHER_STATS_JOB.

5. Dynamic Sampling – Enables the server to enhance performance.

6. CPU Costing – It’s the basic cost model for the optimizer (CPU+I/O), with the cost unit as
time optimizer notifies.

7. Rule Based Optimizer Obsolescence – No more used.

8. Tracing Enhancements – End to End tracing which allows a client process to be identified
via the Client Identifier instead of using the typical Session ID.

Q:-14. What are the tuning indicators Oracle proposes?

Ans. The following high-level tuning indicators are available to establish if a database is
experiencing bottlenecks or not:

1. Buffer Cache Hit Ratio.

It uses the following formula.

Hit Ratio = (Logical Reads – Physical Reads) / Logical Reads

Action: Advance the DB_CACHE_SIZE (DB_BLOCK_BUFFERS prior to 9i) to improve the


hit ratio.

2. Library Cache Hit Ratio.


Action: Advance the SHARED_POOL_SIZE to increase the hit ratio.

Q:-15. What do you check first if there are multiple fragments in the SYSTEM tablespace?

Ans. First of all, check if the users don’t have the SYSTEM tablespace as their
TEMPORARY or DEFAULT tablespace assignment by verifying the DBA_USERS view.

Back to top

Q:-16. When would you add more Copy Latches? What are the parameters that control the
Copy Latches?

Ans. If there is excessive contention for the Copy Latches, check from the “redo copy” latch
hit ratio.

In such a case, add more Copy Latches via the initialization parameter
LOG_SIMULTANEOUS_COPIES to double the number of CPUs available.

Q:-17. How do you confirm if a tablespace has disproportionate fragmentation?

Ans. You can confirm it by checking the output of SELECT against the dba_free_space
table. If it points that the no. of a tablespaces extents is more than the count of its data files,
then it proves excessive fragmentation.
Q:-18. What can you do to optimize the %XYZ% queries?

Ans. First of all, set the optimizer to scan all the entries from the index instead of the table.
You can achieve it by specifying hints.

Please note that crawling the smaller index takes less time than to scan the entire table.

Q:-19. Where does the I/O statistics per table exist in Oracle?

Ans. There is a report known as UTLESTAT which displays the I/O per tablespace. But it
doesn’t help to find the table which has the most I/O.

Q:-20. When is the right time to rebuild an index?

Ans. First of all, select the target index and run the ‘ANALYZE INDEX VALIDATE
STRUCTURE’ command. Every time you run it, a single row will get created in the
INDEX_STATS view.

But the row gets overwritten the next time you run the ANALYZE INDEX command. So
better move the contents of the view to a local table. Thereafter, analyze the ratio of
‘DEL_LF_ROWS’ to ‘LF_ROWS’ and see if you need to rebuild the index.

Q:-21. What exactly would you do to check the performance issue of SQL queries?
Ans. Mostly the database isn’t slow, but it’s the worker session which drags the
performance. And it’s the abnormal session accesses which cause the bottlenecks.

1. Review the events that are in wait or listening mode.

2. Hunt down the locked objects in a particular session.

3. Check if the SQL query is pointing to the right index or not.

4. Launch SQL Tuning Advisor and analyze the target SQL_ID for making any performance
recommendation.

5. Run the “free” command to check the RAM usage. Also, use TOP command to identify
any process hogging the CPU.

Back to top

Q:-22. What is the information you get from the STATSPACK Report?

Ans. We can get the following statistics from the STATSPACK report.

1. WAIT notifiers

2. Load profile

3. Instance Efficiency Hit Ratio

4. Latch Waits

5. Top SQL

6. Instance Action

7. File I/O and Segment Stats

8. Memory allocation

9. Buffer Waits
Q:-23. What are the factors to consider for creating Index on Table? Also, How to select a
column for Index?

Ans. Creation of index depends on the following factors.

1. Size of table,

2. Volume of data

If Table size is large and we need a smaller report, then it’s better to create Index.

Regarding the column to be used for Index, as per the business rule, you should use a
primary key or a unique key for creating a unique index.

Q:-24. What is the main difference between Redo, Rollback, and Undo?

Ans.

Redo – Log that records all changes made to data, including both uncommitted and
committed changes.

Rollback – Segments to store the previous state of data before the changes.

Undo – Helpful in building a read consistent view of data. The data gets stored in the undo
tablespace.
Q:-25. How do you identify the shared memory and semaphores of a particular DB instance
if there are running multiple servers?

Ans. Set the following parameters to distinguish between the in-memory resources of a DB
instance.

1. SETMYPID

2. IPC

3. TRACEFILE_NAME

Use the ORADEBUG command to explore their underlying options.

Generic Questions

1.Query to find Second Highest Salary of Employee?(click for explaination)

Answer:-

Select distinct Salary from Employee e1 where 2=Select count(distinct Salary) from Employee e2 where
e1.salary<=e2.salary;

2.Query to find duplicate rows in table?(click here for explaination)

Answer :-

Select * from Employee a where row_id != select max(row_id) for Employee b where
a.Employee_num=b.Employee_num;

3.How to fetch monthly Salary of Employee if annual salary is given?(click here for Explaination)

Answer:-
Select Employee_name,Salary/12 as ‘Monthly Salary’ from employee;

Click here to get information on ROW_ID

4.What is the Query to fetch first record from Employee table?

Answer:-

Select * from Employee where Rownum =1;

Click here to get What is Rownum?

5.What is the Query to fetch last record from the table?

Answer:-

Select * from Employee where Rowid= select max(Rowid) from Employee;

Complex SQL Queries for Interview

Complex SQL Queries

Click here to get 20 interview questions on Perforance Tuning..

6.What is Query to display first 5 Records from Employee table?

Answer:

Select * from Employee where Rownum <= 5;

CLICK HERE TO GET INFORMATION ON NORMALIZATION

6.What is Query to display last 5 Records from Employee table?

Answer:

Select * from Employee e where rownum <=5

union
select * from (Select * from Employee e order by rowid desc) where rownum <=5;

Click Here to get What is Union?

7.What is Query to display Nth Record from Employee table?

Select * from Employee where rownum = &n;

8.How to get 3 Highest salaries records from Employee table?

select distinct salary from employee a where 3 >= (select count(distinct salary) from emp loyee b where
a.salary <= b.salary) order by a.salary desc;

9.How to Display Odd rows in Employee table?

Select * from(Select rownum as rno,E.* from Employee E) where Mod(rno,2)=1;

10.How to Display Odd rows in Employee table?

Select * from(Select rownum as rno,E.* from Employee) where Mod(rno,2)=0;

11.How to fetch 3rd highest salary using Rank Function?

select * from (Select Dense_Rank() over ( order by salary desc) as Rnk,E.* from Employee E) where
Rnk=3;

Click Here to Get Information on Rank and Dense_Rank

12.How Can i create table with same structure of Employee table?

Create table Employee_1 as Select * from Employee where 1=2;

13.Display first 50% records from Employee table?

Select rownum,E.* from Employee E where rownum<=(Select count(*/2) from Employee);


14.Display first 50% records from Employee table?

Select rownum,E.* from Employee E

minus

Select rownum,E.* from Employee E where rownum<=(Select count(*/2) from Employee);

15.How Can i create table with same structure with data of Employee table?

Create table Employee1 as select * from Employee;

16.How do i fetch only common records between 2 tables.

Select * from Employee;

Intersect

Select * from Employee1;

CLICK HERE TO GET INFORMATION ABOUT INTERSECT OPERATOR

17.Find Query to get information of Employee where Employee is not assigned to the department.

Select * from Employee where Dept_no Not in(Select Department_no from Employee);

18.How to get distinct records from the table without using distinct keyword.

select * from Employee a where rowid = (select max(rowid) from Employee b where
a.Employee_no=b.Employee_no);

19.Select all records from Employee table whose name is ‘Amit’ and ‘Pradnya’

Select * from Employee where Name in(‘Amit’,’Pradnya’);


20.Select all records from Employee table where name not in ‘Amit’ and ‘Pradnya’

select * from Employee where name Not in (‘Amit’,’Pradnya’);

Click Here to get 20 Interview Questions for Tech Mahindra….

21.how to write sql query for the below scenario

I/p:ORACLE

O/p:

i.e, splitting into multiple columns a string using sql.

Answer:

Select Substr(‘ORACLE’,Level,1) From Dual

Connect By Level<= Length(‘ORACLE’);

22.How to fetch all the records from Employee whose joining year is 2017?

Answer:

Oracle:

select * from Employee where To_char(Joining_date,’YYYY’)=’2017′;


MS SQL:

select * from Employee where substr(convert(varchar,Joining_date,103),7,4)=’2017′;

23.What is SQL Query to find maximum salary of each department?

Select Dept_id,max(salary) from Employee group by Dept_id;

24.How Do you find all Employees with its managers?(Consider there is manager id also in Employee
table)

Select e.employee_name,m.employee name from Employee e,Employee m where


e.Employee_id=m.Manager_id;

Вам также может понравиться