. What is SQL Injection ?

SQL Injection is one of the the techniques uses by hackers to hack a website by injecting SQL commands in data fields.

. What is DBMS ?

The database management system is a collection of programs that enables user to store, retrieve, update and delete information from a database.

. What is RDBMS ?

Relational Database Management system (RDBMS) is a database management system (DBMS) that is based on the relational model. Data from relational database can be accessed or reassembled in many different ways without having to reorganize the database tables. Data from relational database can be accessed using an API , Structured Query Language (SQL).

. What is SQL ?

Structured Query Language(SQL) is a language designed specifically for communicating with databases. SQL is an ANSI (American National Standards Institute) standard.

. What are the different type of SQL’s statements ?

This is one of the frequently asked SQL Interview Questions to freshers. SQL statements are broadly classified into three. They are

1. DDL – Data Definition Language DDL is used to define the structure that holds the data. For example, Create, Alter, Drop and Truncate table.

2. DML– Data Manipulation Language DML is used for manipulation of the data itself. Typical operations are Insert, Delete, Update and retrieving the data from the table. Select statement is considered as a limited version of DML, since it can’t change data in the database. But it can perform operations on data retrieved from DBMS, before the results are returned to the calling function.

3. DCL– Data Control Language DCL is used to control the visibility of data like granting database access and set privileges to create tables etc. Example – Grant, Revoke access permission to the user to access data in database.

. What are the Advantages of SQL ?

1. SQL is not a proprietary language used by specific database vendors. Almost every major DBMS supports SQL, so learning this one language will enable programmers to interact with any database like ORACLE, SQL ,MYSQL etc.

2. SQL is easy to learn. The statements are all made up of descriptive English words, and there aren’t that many of them. 3. SQL is actually a very powerful language and by using its language elements you can perform very complex and sophisticated database operations.

. what is a field in a database ?

A field is an area within a record reserved for a specific piece of data. 

Examples: Employee Name, Employee ID etc

. What is a Record in a database ?

A record is the collection of values / fields of a specific entity: i.e. an Employee, Salary etc.


. What is a Table in a database ?

A table is a collection of records of a specific type. For example, employee table, salary table etc.

. What is a database transaction?

Database transaction takes database from one consistent state to another. At the end of the transaction the system must be in the prior state if the transaction fails or the status of the system should reflect the successful completion if the transaction goes through.


. What are properties of a transaction?

Expect this SQL Interview Questions as a part of an any interview, irrespective of your experience. Properties of the transaction can be summarized as ACID Properties.

1. Atomicity A transaction consists of many steps. When all the steps in a transaction gets completed, it will get reflected in DB or if any step fails, all the transactions are rolled back.

2. Consistency The database will move from one consistent state to another, if the transaction succeeds and remain in the original state, if the transaction fails.

3. Isolation Every transaction should operate as if it is the only transaction in the system.

4. Durability Once a transaction has completed successfully, the updated rows/records must be available for all other transactions on a permanent basis.

. What is a Database Lock ?

Database lock tells a transaction, if the data item in questions is currently being used by other transactions.

. What are the type of locks ?

1. Shared Lock When a shared lock is applied on data item, other transactions can only read the item, but can’t write into it.

2. Exclusive Lock When an exclusive lock is applied on data item, other transactions can’t read or write into the data item.

. What are the different type of normalization?

In database design, we start with one single table, with all possible columns. A lot of redundant data would be present since it’s a single table. The process of removing the redundant data, by splitting up the table in a well defined fashion is called normalization.

1. First Normal Form (1NF) A relation is said to be in first normal form if and only if all underlying domains contain atomic values only. After 1NF, we can still have redundant data.

2. Second Normal Form (2NF) A relation is said to be in 2NF if and only if it is in 1NF and every non key attribute is fully dependent on the primary key. After 2NF, we can still have redundant data.

3. Third Normal Form (3NF) A relation is said to be in 3NF, if and only if it is in 2NF and every non key attribute is non-transitively dependent on the primary key.

. What is a primary key?

A primary key is a column whose values uniquely identify every row in a table. Primary key values can never be reused. If a row is deleted from the table, its primary key may not be assigned to any new rows in the future. To define a field as primary key, following conditions had to be met : 1. No two rows can have the same primary key value. 2. Every row must have a primary key value 3. The primary key field cannot be null 4. Values in primary key columns can never be modified or updated

. What is a Composite Key ?

A Composite primary key is a type of candidate key, which represents a set of columns whose values uniquely identify every row in a table.

For example – if “Employee_ID” and “Employee Name” in a table is combined to uniquely identify a row its called a Composite Key.

. What is a Composite Primary Key ?

A Composite primary key is a set of columns whose values uniquely identify every row in a table. What it means is that, a table which contains composite primary key will be indexed based on the columns specified in the primary key. This key will be referred in Foreign Key tables.

For example – if the combined effect of columns, “Employee_ID” and “Employee Name” in a table is required to uniquely identify a row, its called a Composite Primary Key. In this case, both the columns will be represented as primary key.

. What is a Foreign Key ?

When a “one” table’s primary key field is added to a related “many” table in order to create the common field which relates the two tables, it is called a foreign key in the “many” table. For example, the salary of an employee is stored in salary table. The relation is established via foreign key column “Employee_ID_Ref” which refers “Employee_ID” field in the Employee table.

. What is a Unique Key ?

Unique key is same as primary with the difference being the existence of null. Unique key field allows one value as NULL value.

. Define SQL Insert Statement ?

SQL INSERT statement is used to add rows to a table. For a full row insert, SQL Query should start with “insert into “ statement followed by table name and values command, followed by the values that need to be inserted into the table. The insert can be used in several ways: 1. To insert a single complete row. 2. To insert a single partial row.

. Define SQL Update Statement ?

SQL Update is used to update data in a row or set of rows specified in the filter condition. The basic format of an SQL UPDATE statement is, Update command followed by table to be updated and SET command followed by column names and their new values followed by filter condition that determines which rows should be updated.

. Define SQL Delete Statement ?

SQL Delete is used to delete a row or set of rows specified in the filter condition. The basic format of an SQL DELETE statement is, DELETE FROM command followed by table name followed by filter condition that determines which rows should be updated.

. What are wild cards used in database for Pattern Matching ?

SQL Like operator is used for pattern matching. SQL ‘Like’ command takes more time to process. So before using “like” operator, consider suggestions given below on when and where to use wild card search.

1) Don’t overuse wild cards. If another search operator will do, use it instead.
2) When you do use wild cards, try not to use them at the beginning of the search pattern, unless absolutely necessary. Search patterns that begin with wild cards are the slowest to process.
3) Pay careful attention to the placement of the wild card symbols. If they are misplaced, you might not return the data you intended.

. What is a view?

The views are virtual tables. Unlike tables that contain data, views simply contain queries that dynamically retrieve data when used.

. What is a materialized view?

Materialized views are also a view but are disk based. Materialized views get updates on specific duration, base upon the interval specified in the query definition. We can index materialized view.

. What are the advantages and disadvantages of views in a database?


1. Views don’t store data in a physical location.

2. The view can be used to hide some of the columns from the table.

3. Views can provide Access Restriction, since data insertion, update and deletion is not possible with the view.


1. When a table is dropped, associated view become irrelevant.

2. Since the view is created when a query requesting data from view is triggered, its a bit slow.

3. When views are created for large tables, it occupies more memory.\

. What is a stored procedure?

Stored Procedure is a function which contains a collection of SQL Queries. The procedure can take inputs , process them and send back output.

. What are the advantages a stored procedure?

Stored Procedures are precomplied and stored in the database. This enables the database to execute the queries much faster. Since many queries can be included in a stored procedure, round trip time to execute multiple queries from source code to database and back is avoided.

 . Explain the difference between DELETE , TRUNCATE and DROP commands?

Once delete operation is performed, Commit and Rollback can be performed to retrieve data. Once the truncate statement is executed, Commit and Rollback statement cannot be performed. Where condition can be used along with delete statement but it can’t be used with truncate statement. Drop command is used to drop the table or keys like primary,foreign from a table.


. What is Union, minus and Interact commands?

MINUS operator is used to return rows from the first query but not from the second query. INTERSECT operator is used to return rows returned by both the queries.

 What is SQL?

SQL stands for structured query language. It is a database language used for database creation, deletion, fetching rows and modifying rows etc. sometimes it is pronounced as se-qwell.

 When SQL appeared?

It appeared in 1974.

 What are the usages of SQL?

  • To execute queries against a database
  • To retrieve data from a database
  • To inserts records in a database
  • To updates records in a database
  • To delete records from a database
  • To create new databases
  • To create new tables in a database
  • To create views in a database

 Does SQL support programming?

No, SQL doesn’t have loop or Conditional statement. It is used like commanding language to access databases.

 What are the subsets of SQL?

  1. Data definition language (DDL)
  2. Data manipulation language (DML)
  3. Data control language (DCL)

 What is data definition language?

Data definition language(DDL) allows you to CREATE, ALTER and DELETE database objects such as schema, tables, view, sequence etc.

 What is data manipulation language?

Data manipulation language makes user able to access and manipulate data. It is used to perform following operations.

  • Insert data into database
  • Retrieve data from the database
  • Update data in the database
  • Delete data from the database

 What is data control language?

Data control language allows you to control access to the database. It includes two commands GRANT and REVOKE.

GRANT: to grant specific user to perform specific task.

REVOKE: to cancel previously denied or granted permissions.

 What are the type of operators available in SQL?

  1. Arithmetic operators
  2. Logical operators
  3. Comparison operator

 What is the SQL query to display current date?

There is a built in function in SQL called GetDate() which is used to return current timestamp.

 Which types of join is used in SQL widely?

The knowledge of JOIN is very necessary for an interviewee. Mostly used join is INNER JOIN and (left/right) OUTER JOIN.

 What is self join and what is the requirement of self join?

Self join is often very useful to convert a hierarchical structure to a flat structure. It is used to join a table to itself as like if that is the second table.

 What are set operators in SQL?

Union, intersect or minus operators are called set operators.

 What is a constraint? Tell me about its various levels.

Constraints are representators of a column to enforce data entity and consistency. There are two levels :

  1. column level constraint
  2. table level constraint

 Write an SQL query to find names of employee start with ‘A’?

  1. SELECT * FROM Employees WHERE EmpName like ‘A%’

 Write an SQL query to get third maximum salary of an employee from a table named employee_table.

  1. SELECT TOP 1 salary
  2. FROM (
  3. SELECT TOP 3 salary
  4. FROM employee_table
  5. ORDER BY salary DESC ) AS emp
  6. ORDER BY salary ASC;

 What is the difference between DELETE and TRUNCATE statement in SQL?

The main differences between SQL DELETE and TRUNCATE statements are given below:

1) DELETE is a DML command. TRUNCATE is a DDL command.
2) We can use WHERE clause in DELETE command. We cannot use WHERE clause with TRUNCATE
3) DELETE statement is used to delete a row from a table TRUNCATE statement is used to remove all the rows from a table.
4) DELETE is slower than TRUNCATE statement. TRUNCATE statement is faster than DELETE statement.
5) You can rollback data after using DELETE statement. It is not possible to rollback after using TRUNCATE statement.


: SQL Query to find second highest salary of Employee

Answer : There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery :

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );

: SQL Query to find Max Salary from each department.


SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID.
This questions become more interesting if Interviewer will ask you to print department name instead of department id,

SELECT DeptName, MAX(Salary) FROM Employee e RIGHT JOIN Department d ON e.DeptId = d.DeptID GROUP BY DeptName;

: Write SQL Query to display current date.

Answer : SQL has built in function called GetDate() which returns current timestamp. This will work in Microsoft SQL Server, other vendors like Oracle and MySQL also has equivalent functions.

SELECT GetDate();

Write an SQL Query to check whether date passed to Query is date of given format or not.

Remember ISDATE() is a MSSQL function and it may not work on Oracle, MySQL or any other database but there would be something similar.

It will return 0 because passed date is not in correct format.

: Write a SQL Query to print the name of distinct employee whose DOB is between 01/01/1960 to 31/12/1975.


SELECT DISTINCT EmpName FROM Employees WHERE DOB BETWEEN ‘01/01/1960’ AND ‘31/12/1975’;

: Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to 31/12/1975.

SELECT COUNT(*), sex from Employees WHERE DOB BETWEEN ’01/01/1960′ AND ’31/12/1975′ GROUP BY sex;

 find all Employee records containing the word “Joe”, regardless of whether it was stored as JOE, Joe, or joe.

SELECT * from Employees WHERE UPPER(EmpName) like ‘%JOE%’;

 Write a SQL Query to find  year from date.

Here is how you can find Year from a Date in SQL Server 2008

: Write SQL Query to find duplicate rows in a database? and then write SQL query to delete them?

SELECT * FROM emp a WHERE rowid = (SELECT MAX(rowid) FROM EMP b WHERE a.empno=b.empno)
to Delete:
DELETE FROM emp a WHERE rowid != (SELECT MAX(rowid) FROM emp b WHERE a.empno=b.empno);

 : There is a table which contains two column Student and Marks, you need to find all the students, whose marks are greater than average marks i.e. list of above average students.

SELECT student, marks from table where marks > SELECT AVG(marks) from table)

 How do you find all employees which are also manager? .

You have given an standard employee table with an additional column mgr_id, which contains employee id of manager.

Answer : You need to know about self join to solve this problem. In Self Join, you can join two instances of same table to find out additional details as shown below

SELECT e.name, m.name FROM Employee e, Employee m WHERE e.mgr_id = m.emp_id;
this will show employee name and manger name in two column e.g.

name  manager_name
John   David

One follow-up is to modify this query to include employees which doesn’t have manager. To solve that, instead of using inner join, just use left outer join, this will also include employees without managers.

: You have a composite index of three columns, and you only provide value of two columns in WHERE clause of a select query? Will Index be used for this operation?

For example if Index is on EmpId, EmpFirstName and EmpSecondName and you write query like

SELECT * FROM Employee WHERE EmpId=2 and EmpFirstName=’Radhe’
If the given two columns are secondary index column then index will not invoke, but if the given 2 columns contain primary index(first col while creating index) then index will invoke. In this case Index will be used because EmpId and EmpFirstName are primary columns.


. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.

One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

. What’s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but nique key allows one NULL only.

. What is bit datatype and what’s the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

. Define candidate key, alternate key, composite key

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

. What are defaults? Is there a column to which a default can’t be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can’t have defaults bound to them. See CREATE DEFUALT in books online.


. Explain different isolation levels

An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.

. What’s the maximum size of a row?

8060 bytes. Don’t be surprised with questions like ‘what is the maximum number of columns per table’. Check out SQL Server books online for the page titled: “Maximum Capacity Specifications”.

. Explain Active/Active and Active/Passive cluster configurations

Hopefully you have experience setting up cluster servers. But if you don’t, at least be familiar with the way clustering works and the two clustering configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site.

. Explain the architecture of SQL Server

This is a very important question and you better be able to answer it if consider yourself a DBA. SQL Server books online is the best place to read about SQL Server architecture. Read up the chapter dedicated to SQL Server Architecture.

. What is lock escalation?

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it’s dynamically managed by SQL Server.

. Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

. What are constraints? Explain different types of constraints

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.


For an explanation of these constraints see books online for the pages titled: “Constraints” and “CREATE TABLE”, “ALTER TABLE”


. What is RAID and what are different types of RAID configurations?

RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory board’s homepage.


. What are the steps you will take, if you are tasked with securing an SQL Server?

Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, database and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.

. What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other’s piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user’s process.

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

. What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions.


. As a part of your job, what are the DBCC commands that you commonly use for database maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.


. What are the different ways of moving data/databases between servers and databases in SQL Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT…SELECT, SELECT…INTO, creating INSERT scripts to generate data.

. Explain different types of BACKUPs available in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?

Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.

. What is database replication? What are the different types of replication you can set up in SQL Server?

Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:

o Snapshot replication

o Transactional replication (with immediate updating subscribers, with queued updating subscribers)

o Merge replication

See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.

. How to determine the service pack currently installed on SQL Server?

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row processing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 — 5000 hike
Salary between 40000 and 55000 — 7000 hike
Salary between 55000 and 65000 — 9000 hike

In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don’t have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row.


. Can you have a nested transaction?


. What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL,just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy.

. What is the system function to get the current user’s user id?

USER_ID().Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

Write Sql syntax to create Oracle Trigger before insert of each row in employee table

seq_no number(12);
select EMPLOYEE_ID_SEQ.nextval into seq_no from dual ;
:new EMPLOYEE_ID :=seq_no;

What is “TRIGGER” in SQL?

Trigger allows you to execute a batch of SQL code when an insert, update or delete command is executed against a specific table.

Actually triggers are special type of stored procedures that are defined to execute automatically in place or after data modifications.

. What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there’s no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.

 There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

. What is a trigger?

Database triggers are sets of commands that get executed when an event(Before Insert, After Insert, On Update, On delete of a row) occurs on a table, views.

. Oracle Procedure81. Oracle View

An example oracle view script is given below create view Employee_Incentive as select FIRST_NAME,max(INCENTIVE_AMOUNT) INCENTIVE_AMOUNT from EMPLOYEE a, INCENTIVES b where a.EMPLOYEE_ID=b.EMPLOYEE_REF_ID group by FIRST_NAME

. Oracle materialized view – Daily Auto Refresh


. Oracle materialized view – Fast Refresh on Commit

Create materialized view log for fast refresh. Following materialized view script wont get executed if materialized view log doesn’t exists CREATE MATERIALIZED VIEW MAT_Employee_Incentive_Refresh BUILD IMMEDIATE REFRESH FAST ON COMMIT AS select FIRST_NAME,max(INCENTIVE_AMOUNT) from EMPLOYEE a, INCENTIVES b where a.EMPLOYEE_ID=b.EMPLOYEE_REF_ID group by FIRST_NAME


CREATE INDEX myIndex ON myTable(myColumn)

What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

What is the difference between clustered and non clustered index in SQL?

There are mainly two type of indexes in SQL, Clustered index and non clustered index. The differences between these two indexes is very important from SQL performance perspective.

1) One table can have only one clustered index but it can have many non clustered index. (approximately 250).

2) clustered index determines how data is stored physically in table. Actually clustered index stores data in cluster, related data is stored together so it makes simple to retrieve data.

3) reading from a clustered index is much faster than reading from non clustered index from the same table.

4) clustered index sort and store data rows in the table or view based on their key value, while non cluster have a structure separate from the data row.

. What is the difference between Cluster and Non cluster Index?

A clustered index reorders the way records in the table are physically stored. There can be only one clustered index per table. It makes data retrieval faster.

A non clustered index does not alter the way it was stored but creates a completely separate object within the table. As a result insert and update command will be faster.

. What is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it’s row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.


Related image

Related image

Related image

Related image


Agenda Difference between aggregate and analytic  functions Introduction to various analytic functions Functions that a...

Aggregates vs. Analytics Aggregate functions   Rows are collapsed. One row per group   Non-Group-By columns not allowed...

Analytics vs. other methods Show the dept, empno, sal and the sum of all salaries  in their dept Three possible ways   ...

Anatomy of an analytic funcion function (arg1, ..., argN) OVER ([partition_by_clause]    [order_by_clause [windowing_clau...

Types of analytical functions Ranking functions FIRST_VALUE/LAST_VALUE/NTH_VALUE Windowing functions Reporting functio...


Ranking Functions ROW_NUMBER() RANK() – Skips ranks after duplicate ranks DENSE_RANK() – Doesnt skip rank after duplica...

FIRST_VALUE/LAST_VALUE/NTH_VALUE Returns the first/last/nth value from an ordered set FIRST_VALUE(expr, [IGNORE NULLS]) ...

Window functions Used for computing cumulative/running totals (YTD, MTD,    QTD), moving/centered averages   function(ar...

ROWS type windows Physical offset. Number of rows before or after current    row   Non deterministic results if rows are...

RANGE type Windows Logical offset non-unique rows treated as one logical row Only one column allowed in ORDER BY clause...

Reporting function Computes the ratio of a value to the sum of a set of  values RATIO_TO_REPORT(arg) OVER ([PARTITION BY...

LAG/LEAD Gives the ability to access other rows without self-join. Allows you to treat cursor as an array Useful for ma...

FIRST/LAST Very different from FIRST_VALUE/LAST_VALUE Returns the results of aggregate/analytic function applied    on c...

Above/Below average calculation Find the list of employees whose salary is higher than  the department average. above_av...

Top-N queries Find the full details of "set of" employees with the top-  N salaries Find the two most recent hires in ea...

Top-N% queries List the top 5% of the customers by revenue top_np.sql

Multi Top-N queries For each customer, find out   the maximum sale in the last 7 days   the date of that sale   the ma...

De-Duping Deleting duplicate records dedup.txt

Hypothetical Ranking CUME_DIST, DENSE_RANK, RANK,  PERCENT_RANK Used for what-if analysis hypothetical_rank.sql

Inverse Percentile functions Return the value corresponding to a certain    percentile (opposite of CUME_DIST)   PERCENT...

String Aggregation: LISTAGG, STRAGG Concatenated string of values for a particular group    (e.g. employees working in a ...

Pivoting/Unpivoting Pivoting   transposes rows to columns   DECODE/CASE and GROUP BY used Unpivoting   Converts colum...

Data Densification Data normally stored in sparse form (e.g. No rows    if there is no sales for a particular period)   ...

When not to use analytics When a simple group by would do the job when_not_to_use_analytics.sq

Drawback of analytics Lot of sorting. Set  PGA_AGGREGATE_TARGET/SORT_AREA_SIZE  appropriately New versions reduce the n...

Recap of Analytic Functions Analytic Functions:   Were introduced in 8.1.6 (~1998)   Are supported within PL/SQL only f...

Advanced Aggregation GROUP BY col1, col2 GROUP BY ROLLUP(col1, col2) GROUP BY CUBE(col1, col2) GROUP BY GROUPING SETS ...

ROLLUP GROUP BY ROLLUP(col1, col2) Generates subtotals automatically Generally used in hierarchical dimensions (region,...

CUBE GROUP BY CUBE(col1, col2) Gives subtotals automatically for every possible combination Used in cross-tabular repor...

Grouping Sets GROUP BY GROUPING SETS (col1, (col1, col2)) Explicitly lists the needed groupings GROUPING, GROUPING_ID, ...

Composite Columns Treat multiple columns as a single column Composite_columns.sql

Concatenated Groupings GROUP BY GROUPING SETs (a,b), GROUPING  SETS (c,d) The above is same as GROUP BY GROUPING SETS  (...



Read more: http://java67.blogspot.com/2013/04/10-frequently-asked-sql-query-interview-questions-answers-database.html#ixzz3ghgjB12g

Advanced SQL Interview Questions and Answers





select DEPARTMENT,max(SALARY) MaxSalary from employee group by DEPARTMENT order by MaxSalary asc

select 1
windows analytcal
aggregate vs windows
store proc
date times
ansi vs join condition

update statement
oracle functions
white spaces
escape squesnces
extract year month day
regular expression
wild charcter
coorelated sub quer y subquery
casr stament
if else
delete no join
update statement joining query wont work.