Академический Документы
Профессиональный Документы
Культура Документы
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.
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?
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?
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?
8. What is DCL?
Fill Factor
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?
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.
This should remove all the duplicate columns from the table. Creation of tables for the
related data and identification of unique columns.
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.
This should meet all requirements of 2NF. Removing the columns which are not dependent
on primary key constraints.
Meeting all the requirements of third normal form and it should not have multi- valued
dependencies.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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?
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 -.
45. How can you create an empty table from an existing table?
Example will be -.
Here, we are copying student table to another table with the same structure with no rows
copied.
Records can be fetched for both Odd and Even row numbers -.
1 Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
1 Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1
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.
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.
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.
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.
Propose – Here is a standard approach one can adapt to boost the performance. However,
you can customize it further to maximize the benefits.
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
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.
Ans. While analyzing the explain plan, check the following areas.
1. Driving Table
2. Join Order
3. Join Method
7. Unused indexes
8. Access paths
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
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.
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.
6. CPU Costing – It’s the basic cost model for the optimizer (CPU+I/O), with the cost unit as
time optimizer notifies.
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.
Ans. The following high-level tuning indicators are available to establish if a database is
experiencing bottlenecks or not:
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.
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.
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.
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
4. Latch Waits
5. Top SQL
6. Instance Action
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?
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
Generic Questions
Answer:-
Select distinct Salary from Employee e1 where 2=Select count(distinct Salary) from Employee e2 where
e1.salary<=e2.salary;
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;
Answer:-
Answer:-
Answer:
Answer:
union
select * from (Select * from Employee e order by rowid desc) where rownum <=5;
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;
select * from (Select Dense_Rank() over ( order by salary desc) as Rnk,E.* from Employee E) where
Rnk=3;
minus
15.How Can i create table with same structure with data of Employee table?
Intersect
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’
I/p:ORACLE
O/p:
Answer:
22.How to fetch all the records from Employee whose joining year is 2017?
Answer:
Oracle:
24.How Do you find all Employees with its managers?(Consider there is manager id also in Employee
table)