• No results found

SQL Interview Questions With Answers

N/A
N/A
Protected

Academic year: 2021

Share "SQL Interview Questions With Answers"

Copied!
55
0
0

Loading.... (view fulltext now)

Full text

(1)

SQL Interview Questions with Answers

http://sql-plsql.blogspot.com/2009/04/sql-interview-questions.html

Category: Interview Articles

Published on: 9th Jan 2011 | 1307800 people have read this article.

Thanks to site Visitor Vicky for sharing the SQL Interview Questions.

Ads

What is normalization? Explain different levels of normalization?

Check out the article Q100139 from Microsoft knowledge base and of course, there's much more information available in the net. It will be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is de-normalization and when would you go for it?

As the name indicates, de-normalization is the reverse process of normalization. It is the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

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.

It will be a good idea to read up a database designing fundamentals text book. What's the difference between a primary key and a unique key?

(2)

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 non-clustered index by default. Another major difference is that, primary key does not allow NULLs, but unique key allows one NULL only.

What are user defined data types and when you should go for them?

User defined data types let you extend the base SQL Server data types by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined data type called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

What is bit data type and what's the information that can be stored inside a bit column?

Bit data type is used to store Boolean information like 1 or 0 (true or false). Until SQL Server 6.5 bit data type could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit data type 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 cannot 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 DEFAULT in books online.

(3)

A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.

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.

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 maximum size of a row?

8060 bytes. Do not 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 do not, 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.

(4)

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.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it will not log the deletion of each row, instead it logs the de-allocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more information. What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time of your interview)? What changed between the previous version of SQL Server and the current version?

This question is generally asked to see how current is your knowledge. Generally there is a section in the beginning of the books online titled "What's New", which has all such information. Of course, reading just that is not enough, you should have tried those things to better answer the questions. Also check out the section titled "Backward Compatibility" in books online which talks about the changes that have taken place in the new version.

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.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

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

(5)

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 create 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 time, 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.

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 to improve performance of a poor performing query?

This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables.

(6)

 SET SHOWPLAN_ALL ON,  SET SHOWPLAN_TEXT ON,  SET STATISTICS IO ON,  SQL Server Profiler,

 Windows NT /2000 Performance monitor,  Graphical execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft web site. 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 multi-protocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server security best practices

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. Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base.

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.

(7)

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

Explain CREATE DATABASE syntax

Many of us are used to creating databases from the Enterprise Manager or by just issuing the command:

CREATE DATABASE MyDB.

But what if you have to create a database with two file groups, one on drive C and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more information.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?

SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal configuration mode. Check out SQL Server books online for more parameters and their explanations.

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 statistics, under what circumstances they go out of date, how do you update them?

(8)

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:

1. If there is significant change in the key values in the index

2. If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3. Database is upgraded from a previous version

Look up SQL Server books online for the following commands:

UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

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,

Detaching 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?

(9)

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:

* Snapshot replication

* Transactional replication (with immediate updating subscribers, with queued

updating subscribers)

* Merge replication

See SQL Server books online for in-depth 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 SQL Server service packs and versions.

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.

(10)

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 round trip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, 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

END

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.

Write down the general syntax for a SELECT statements covering all the options.

Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by__expression] [HAVING search_condition]

(11)

What is a join and explain different types of joins?

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins:

INNER JOINs,

OUTER JOINs,

CROSS JOINs

OUTER JOINs are further classified as

LEFT OUTER JOINS,

RIGHT OUTER JOINS and

FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

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.

(12)

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().

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 cannot 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.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

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 inserted rows to it for some custom processing.

(13)

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.

Ads

What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp

(

empid int,

mgrid int,

empname char(10)

)

INSERT emp SELECT 1,2,'Vyas'

INSERT emp SELECT 2,3,'Mohan'

INSERT emp SELECT 3,NULL,'Shobha'

INSERT emp SELECT 4,2,'Shridhar'

INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]

FROM emp t1, emp t2

WHERE t1.mgrid = t2.empid

Here is an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]

FROM emp t1

(14)

emp t2 ON

t1.mgrid = t2.empid

INTRODUCTION

SQL queries most asked in .NET/SQL Server job interviews. These tricky queries may be required in your day to day database usage.

BACKGROUND

This article demonstrates some commonly asked SQL queries in a job interview. I will be covering some of the common but tricky queries like:-

(i) Finding the nth highest salary of an employee. (ii) Finding TOP X records from each group. (iii) Deleting duplicate rows from a table.

NOTE : All the SQL mentioned in this article has been tested under SQL Server 2005.

(i) Finding the nth highest salary of an employee.

Create a table named Employee_Test and insert some test data as:-

Collapse | Copy Code CREATE TABLE Employee_Test

(

Emp_ID INT Identity, Emp_name Varchar(100), Emp_Sal Decimal (10,2) )

INSERT INTO Employee_Test VALUES ('Anees',1000); INSERT INTO Employee_Test VALUES ('Rick',1200); INSERT INTO Employee_Test VALUES ('John',1100); INSERT INTO Employee_Test VALUES ('Stephen',1300); INSERT INTO Employee_Test VALUES ('Maria',1400);

It is very easy to find the highest salary as:-

Collapse | Copy Code

--Highest Salary

select max(Emp_Sal) from Employee_Test

Now, if you are asked to find the 3rd highest salary, then the query is as:-

Collapse | Copy Code

--3rd Highest Salary

select min(Emp_Sal) from Employee_Test where Emp_Sal in

(select distinct top 3 Emp_Sal from Employee_Test order by Emp_Sal desc)

The result is as :- 1200

To find the nth highest salary, replace the top 3 with top n (n being an integer 1,2,3 etc.) Collapse | Copy Code

--nth Highest Salary

select min(Emp_Sal) from Employee_Test where Emp_Sal in

(select distinct top n Emp_Sal from Employee_Test order by Emp_Sal desc)

(ii) Finding TOP X records from each group

(15)

Create a table named photo_test and insert some test data as :-

Collapse | Copy Code create table photo_test

(

pgm_main_Category_id int, pgm_sub_category_id int, file_path varchar(MAX) )

insert into photo_test values (17,15,'photo/bb1.jpg');

insert into photo_test values(17,16,'photo/cricket1.jpg'); insert into photo_test values(17,17,'photo/base1.jpg'); insert into photo_test values(18,18,'photo/forest1.jpg'); insert into photo_test values(18,19,'photo/tree1.jpg'); insert into photo_test values(18,20,'photo/flower1.jpg'); insert into photo_test values(19,21,'photo/laptop1.jpg'); insert into photo_test values(19,22,'photo/camer1.jpg');

insert into photo_test values(19,23,'photo/cybermbl1.jpg'); insert into photo_test values

(17,24,'photo/F1.jpg');

There are three groups of pgm_main_category_id each with a value of 17 (group 17 has four records),18 (group 18 has three records) and 19 (group 19 has three records). Now, if you want to select top 2 records from each group, the query is as follows:-

Collapse | Copy Code select pgm_main_category_id,pgm_sub_category_id,file_path from

(

select pgm_main_category_id,pgm_sub_category_id,file_path,

rank() over (partition by pgm_main_category_id order by pgm_sub_category_id asc) as rankid

from photo_test ) photo_test

where rankid < 3 -- replace 3 by any number 2,3 etc for top2 or top3. order by pgm_main_category_id,pgm_sub_category_id

The result is as:-

Collapse | Copy Code pgm_main_category_id pgm_sub_category_id file_path

17 15 photo/bb1.jpg 17 16 photo/cricket1.jpg 18 18 photo/forest1.jpg 18 19 photo/tree1.jpg 19 21 photo/laptop1.jpg 19 22 photocamer1.jpg

(iii) Deleting duplicate rows from a table

A table with a primary key doesn‘t contain duplicates. But if due to some reason, the keys have to be disabled or when importing data from other sources, duplicates come up in the table data, it is often needed to get rid of such duplicates.

This can be achieved in tow ways :- (a) Using a temporary table.

(b) Without using a temporary table.

(a) Using a temporary or staging table

Let the table employee_test1 contain some duplicate data like:-

Collapse | Copy Code CREATE TABLE Employee_Test1

(16)

(

Emp_ID INT,

Emp_name Varchar(100), Emp_Sal Decimal (10,2) )

INSERT INTO Employee_Test1 VALUES (1,'Anees',1000); INSERT INTO Employee_Test1 VALUES (2,'Rick',1200); INSERT INTO Employee_Test1 VALUES (3,'John',1100); INSERT INTO Employee_Test1 VALUES (4,'Stephen',1300); INSERT INTO Employee_Test1 VALUES (5,'Maria',1400); INSERT INTO Employee_Test1 VALUES (6,'Tim',1150); INSERT INTO Employee_Test1 VALUES (6,'Tim',1150);

Step 1: Create a temporary table from the main table as:-

Collapse | Copy Code select top 0* into employee_test1_temp from employee_test1

Step2 : Insert the result of the GROUP BY query into the temporary table as:-

Collapse | Copy Code insert into employee_test1_temp

select Emp_ID,Emp_name,Emp_Sal from employee_test1

group by Emp_ID,Emp_name,Emp_Sal Step3: Truncate the original table as:-

Collapse | Copy Code truncate table employee_test1

Step4: Fill the original table with the rows of the temporary table as:-

Collapse | Copy Code insert into employee_test1

select * from employee_test1_temp

Now, the duplicate rows from the main table have been removed.

Collapse | Copy Code select * from employee_test1

gives the result as:-

Collapse | Copy Code Emp_ID Emp_name Emp_Sal

1 Anees 1000 2 Rick 1200 3 John 1100 4 Stephen 1300 5 Maria 1400 6 Tim 1150

(b) Without using a temporary table

Collapse | Copy Code ;with T as

(

select * , row_number() over (partition by Emp_ID order by Emp_ID) as rank from employee_test1

)

delete

from T

where rank > 1

The result is as:-

(17)

Emp_ID Emp_name Emp_Sal 1 Anees 1000 2 Rick 1200 3 John 1100 4 Stephen 1300 5 Maria 1400 6 Tim 1150

CONCLUSION

I hope that these queries will help you for Interviews as well as in your day database activities.

SQL Interview Questions and Answers :

What is the difference between oracle,sql and sql server ?

 Oracle is based on RDBMS.

 SQL is Structured Query Language.

 SQL Server is another tool for RDBMS provided by MicroSoft.

why you need indexing ? where that is stroed and what you mean by schema object? For what purpose we are using view?

We cant create an Index on Index.. Index is stoed in user_index table.Every object that has been created on Schema is Schema Object like Table,View etc.If we want to share the particular data to various users we have to use the virtual table for the Base table...So tht is a view.

indexing is used for faster search or to retrieve data faster from various table. Schema containing set of tables, basically schema means logical separation of the database. View is crated for faster retrieval of data. It's customized virtual table. we can create a single view of multiple tables. Only the drawback is..view needs to be get refreshed for

retrieving updated data.

Difference between Store Procedure and Trigger?

 we can call stored procedure explicitly.

 but trigger is automatically invoked when the action defined in trigger is done. ex: create trigger after Insert on

 this trigger invoked after we insert something on that table.  Stored procedure can't be inactive but trigger can be Inactive.

 Triggers are used to initiate a particular activity after fulfilling certain condition.It need to define and can be enable and disable according to need.

(18)

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

 Suppose we need to validate a DML statement(insert/Update/Delete) that modifies a table then we can write a trigger on the table that gets fired implicitly whenever DML statement is executed on that table.

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

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

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

What the difference between UNION and UNIONALL?

Union will remove the duplicate rows from the result set while Union all does'nt.

What is the difference between TRUNCATE and DELETE commands?

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

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

yes,

USER_CONSTRAINTS,

system table contains information on constraints on all the tables created

Explain normalization ?

Normalisation means refining the redundancy and maintain stablisation. there are four types of normalisation :

first normal forms, second normal forms, third normal forms and fourth Normal forms.

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

Select * from global_name;

This will give the datbase name which u r currently connected to...

What is the difference between SQL and SQL Server ? SQLServer is an RDBMS just like oracle,DB2 from Microsoft

whereas

Structured Query Language (SQL), pronounced "sequel", is a language that provides

(19)

use in System R. SQL is a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on RDBMS.

What is diffrence between Co-related sub query and nested sub query?

Correlated subquery runs once for each row selected by the outer query. It contains a

reference to a value from the row selected by the outer query.

Nested subquery runs only once for the entire nesting (outer) query. It does not

contain any reference to the outer query row. For example,

Correlated Subquery:

select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno)

Nested Subquery:

select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno)

WHAT OPERATOR PERFORMS PATTERN MATCHING?

Pattern matching operator is LIKE and it has to used with two attributes 1. % and

2. _ ( underscore )

% means matches zero or more characters and under score means mathing exactly one character

1)What is difference between Oracle and MS Access? 2) What are disadvantages in Oracle and MS Access?

3) What are feratures&advantages in Oracle and MS Access?

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

What is database?

A database is a collection of data that is organized so that itscontents can easily be accessed, managed and updated. open this url :

http://www.webopedia.com/TERM/d/database.html

What is cluster.cluster index and non cluster index ?

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

(20)

How can i hide a particular table name of our schema?

you can hide the table name by creating synonyms. e.g) you can create a synonym y for table x

create synonym y for x;

What is difference between DBMS and RDBMS?

The main difference of DBMS & RDBMS is

RDBMS have Normalization. Normalization means to refining the redundant and maintain the stablization.

the DBMS hasn't normalization concept.

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

Primary key

Advantages

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

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

Foreign Key

Advantage

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

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

datediff

for Eg: select datediff (dd,'2-06-2007','7-06-2007') output is 5

SQL Server Interview Questions

Posted: January 20, 2008 in Important SQL Query, Interview Questions, SQL Server, Utlities

Tags: Interview, SQL Joins, SQL Performance, SQL Query, SQL Server, SQL Server Interview questions

22

Few Interesting Questions and concepts

There are 3 tables Titles, Authors and Title-Authors (check PUBS db). Write the query to get the author name and the number of books written by that author, the result should start from the author who has written the maximum number

(21)

of books and end with the author who has written the minimum number of books.

SELECT authors.au_lname, COUNT(*) AS BooksCount FROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id INNERJOIN titles ON titles.title_id = titleauthor.title_id GROUP BY authors.au_lname ORDER BY BooksCount DESC

Write a SQL Query to find first day of month?

SELECTDATENAME(dw, DATEADD(dd, -DATEPART(dd, GETDATE())+ 1,GETDATE())) AS FirstDay

There is a table day_temp which has three columns dayid, day and temperature. How do I write a query to get the difference of temperature among each other for seven days of a week?

SELECT a.dayid, a.dday, a.tempe, a.tempe - b.tempe AS Difference FROM day_temp a INNER JOIN day_temp b ON a.dayid = b.dayid + 1

or this query

Select a.day, a.degree-b.degree from temperature a, temperature b where a.id=b.id+1 There is a table which contains the names like this. a1, a2, a3, a3, a4, a1, a1, a2 and their salaries. Write a query to get grand total salary, and total salaries of individual employees in one query.

SELECT empid, SUM(salary) AS salaryFROM employeeGROUP BY empid WITH ROLLUP ORDER BY empid

Update With Case

EmpID EmpName Gender

1 Raja Male

2 Rani Female

In the above table using one query u need to change Gender male to female and who is female need to change male.

UPDATE Emp1 SET Gender=CASE Gender WHEN ‘Male’ THEN ‘Female’WHEN ‘female’ THEN ‘Male’END;

Query to find the maximum salary of an employee

Select * from Employee where salary = (Select max(Salary) from Employee) Query to Find the Nth Maximum Salary

Select * From Employee E1 Where (3-1) = (Select

Count(Distinct(E2.Salary)) From Employee E2 Where E2.Salary > E1.Salary)

(22)

SELECT SALARY FROM EMPLOYEEWHERE SALARY=(SELECT MAX(SALARY)

FROM EMPLOYEE WHERE SALARY <> (SELECT MAX (SALARY) FROM EMPLOYEE)) select max(salary) as Salary from Emplo where salary!=(select max(salary) from Emplo)

SELECT MAX(E1.salary) FROM emplo E1 , emplo E2WHERE E1.salary< E2.salary

Creating a foreign-key constraint between columns of two tables defined with two different datatypes will produce an error

Ans : Yes

Important concepts

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 unique key allows one NULL only.

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 is a transaction and what are ACID properties?

A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book. 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. Read

Committed – A transaction operating at the Read Committed level cannot see changes made by other transactions until those transactions are committed. At this level of isolation, dirty reads are not possible but nonrepeatable reads and phantoms are possible. Read Uncommitted – A transaction operating at the Read Uncommitted level can see uncommitted changes made by other transactions. At this level of isolation, dirty reads, nonrepeatable reads, and phantoms are all possible. Repeatable Read – A

transaction operating at the Repeatable Read level is guaranteed not to see any changes made by other transactions in values it has already read. At this level of isolation, dirty reads and nonrepeatable reads are not possible but phantoms are possible. Serializable – A transaction operating at the Serializable level guarantees that all concurrent

transactions interact only in ways that produce the same effect as if each transaction were entirely executed one after the other. At this isolation level, dirty reads,

nonrepeatable reads, and phantoms are not possible.

What’s the difference between DELETE TABLE and TRUNCATE TABLE commands? DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won‘t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. TRUNCATE TABLE is functionally identical to DELETE statement with no

(23)

WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table‘s data, and only the page deallocations are recorded in the transaction log. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE TABLE may not be used on tables participating in an indexed view

What are the steps you will take to improve performance of a poor performing query?

This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables. Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer

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. Check out SET DEADLOCK_PRIORITY and ―Minimizing Deadlocks‖ in SQL Server books online

What are statistics, under what circumstances they go out of date, how do you update them?

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version. Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

Index Optimization tips

• Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the number of indexes should not be very much. Try to use maximum 4-5 indexes on one table, not more. If you have read-only table, then the number of indexes may be

(24)

increased.

• Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index.

• Try to create indexes on columns that have integer values rather than character values. • If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the leftmost of the key.

• If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns.

• Create surrogate integer primary key (identity for example) if your table will not have many insert operations.

• Clustered indexes are more preferable than nonclustered, if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY.

• If your application will be performing the same query over and over on the same table, consider creating a covering index on the table.

• You can use the SQL Server Profiler Create Trace Wizard with ―Identify Scans of Large Tables‖ trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index.

• You can use sp_MSforeachtable undocumented stored procedure to rebuild all indexes in your database. Try to schedule it to execute during CPU idle time and slow production periods.

sp_MSforeachtable @command1=‖print ‗?‘ DBCC DBREINDEX (‗?‘)‖

Explain about Clustered and non clustered index? How to choose between a Clustered Index and a Non-Clustered Index?

There are clustered and nonclustered indexes. A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.

A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf nodes of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

Consider using a clustered index for:

o Columns that contain a large number of distinct values.

o Queries that return a range of values using operators such as BETWEEN, >, >=, <, and <=.

o Columns that are accessed sequentially. o Queries that return large result sets.

Non-clustered indexes have the same B-tree structure as clustered indexes, with two significant differences:

o The data rows are not sorted and stored in order based on their non-clustered keys. o The leaf layer of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Each index row contains the non-clustered key value and one or more row locators that point to the data row (or rows if the index is not unique) having the key value.

o Per table only 249 non clustered indexes How many types of Joins?

Joins can be categorized as:

• Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables. • Outer joins. Outer joins can be a left, a right, or full outer join.

(25)

specified in the FROM clause:

• LEFT JOIN or LEFT OUTER JOIN -The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

• RIGHT JOIN or RIGHT OUTER JOIN – A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

• FULL JOIN or FULL OUTER JOIN – A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

• Cross joins – Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. (A Cartesian join will get you a Cartesian product. A Cartesian join is when you join every row of one table to every row of another table. You can also get one by

joining every row of a table to every row of itself.

What are the difference between a function and a stored procedure? Functions can be used in a select statement where as procedures cannot

Procedure takes both input and output parameters but Functions takes only input parameters

Functions cannot return values of type text, ntext, image & timestamps where as procedures can

Functions can be used as user defined datatypes in create table but procedures cannot ***Eg:-create table <tablename>(name varchar(10),salary getsal(name))

Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function get‘s executed and the return

Type is returned as the result set.

What is the basic functions for master, msdb, tempdb databases? Microsoft® SQL Server 2000 systems have four system databases:

• master – The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. master is the database that records the existence of all other databases, including the location of the database files.

• tempdb – tempdb holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server. tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database.

By default, tempdb autogrows as needed while SQL Server is running. If the size defined for tempdb is small, part of your system processing load may be taken up with

autogrowing tempdb to the size needed to support your workload each time to restart SQL Server. You can avoid this overhead by using ALTER DATABASE to increase the size of tempdb.

• model – The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, then the remainder of the new database is filled with empty pages. Because tempdb is created every time SQL Server is started, the model database must always exist on a SQL Server system.

• msdb – The msdb database is used by SQL Server Agent for scheduling alerts and jobs, and recording operators.

(26)

1st Normal Form (1NF)

Definition: A table (relation) is in 1NF if 1. There are no duplicated rows in the table.

2. Each cell is single-valued (i.e., there are no repeating groups or arrays). 3. Entries in a column (attribute, field) are of the same kind.

Note: The order of the rows is immaterial; the order of the columns is immaterial. Note: The requirement that there be no duplicated rows in the table means that the table has a key (although the key might be made up of more than one column—even, possibly, of all the columns).

Rule 1: Eliminate Repeating Groups. Make a separate table for each set of related attributes, and give each table a primary key.

2nd Normal Form (2NF)

Definition: A table is in 2NF if it is in 1NF and if all non-key attributes are dependent on all of the key.

Note: Since a partial dependency occurs when a non-key attribute is dependent on only a part of the (composite) key, the definition of 2NF is sometimes phrased as, ―A table is in 2NF if it is in 1NF and if it has no partial dependencies.‖

Rule 2: Eliminate Redundant Data. If an attribute depends on only part of a multi-valued key, remove it to a separate table.

3rd Normal Form (3NF)

Definition: A table is in 3NF if it is in 2NF and if it has no transitive dependencies. Rule 3: Eliminate Columns Not Dependent on Key. If attributes do not contribute to a description of the key, remove them to a separate table.

Boyce-Codd Normal Form (BCNF)

Definition: A table is in BCNF if it is in 3NF and if every determinant is a candidate key. 4th Normal Form (4NF)

Definition: A table is in 4NF if it is in BCNF and if it has no multi-valued dependencies. Rule 4: Isolate Independent Multiple Relationships. No table may contain two or more l:n or n:m relationships that are not directly related.

5th Normal Form (5NF)

Definition: A table is in 5NF, also called ―Projection-Join Normal Form‖ (PJNF), if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table.

Rule 5: Isolate Semantically Related Multiple Relationships. There may be practical constraints on information that justify separating logically related many-to-many relationships.

Domain-Key Normal Form (DKNF)

Definition: A table is in DKNF if every constraint on the table is a logical consequence of the definition of keys and domains.

Top 10 Developer Interview Questions About SQL

Server

Written on June 18, 2009 by Brent Ozar PLF Team in SQL Server, SQLServerPedia Syndication

Knowing good SQL questions to ask during an interview with a developer can help you filter out the best candidates from the ones who aren‟t the most qualified. There‟s a huge difference between “It worked on my machine” and “It scales well in production.” These interview questions will help you filter out the bad apples before you hire them.

(27)

I like to phrase this interview question this way because I‟m not saying the DBA is right – I‟m just asking the developer to explain the DBA‟s point of view. I don‟t have a problem with the developer rolling their eyes as they explain the answer, but I have a problem with the developer being surprised by the question.

The candidate gets bonus points if they seem even vaguely aware of the terms “set-based processing” and “row-based processing”, but that‟s purely a bonus. (I wish I could say that these concepts are requirements, but in today‟s economic market, companies don‟t always want to pay top dollar to get the best candidates.)

9. Where do you like business logic – in the app or in the database? Why?

Personally, I like stored procedures because they‟re easier for us DBAs to test, tune and tweak. On the other hand, the developer community isn‟t always as fond of stored procs. For their side, see these posts by Jeff Atwood:

 Who Needs Stored Procedures, Anyway?  Stored Procedures vs Ad-Hoc SQL  My Database is a Web Service

I don‟t mind what arguments the coder candidate uses, but I want to see „em put some thought into it. No matter which angle they take, I‟ll play the devil‟s advocate and prod them with arguments just to see how they react.

8. Explain when and how transactions should be used.

Not In The Oprah Book Club, Oddly

Start with just that open-ended interview question, and if they have trouble getting started, give them a scenario.

(28)

“Say we‟ve got a table for Orders, and a table for OrderDetails. Someone places an order for two books – Bacon: A Love Story and the hit bestseller Eat What You Want and Die Like A Man. Tell me what happens.”

After they‟ve answered, ask them when transactions should not be used. I don‟t want my developers wrapping anything inside a transaction unless it absolutely needs to be. (Unlike bacon, which should be used as often as possible for wrapping purposes.)

7. Explain referential integrity and where it can be enforced.

If they stumble on the question, circle back to the Orders and OrderDetails tables we used as examples earlier. What‟s an orphan? How do we make sure that we don‟t end up with OrderDetails for records with no matching Order record? Where are all the places we could enforce referential integrity? (Think foreign keys, triggers, the application, or not at all.) Have you worked in places where there was no referential integrity, and what problems did you run into?

6. What‟s the fastest way to get a thousand records into the database?

I‟m not looking for the best answers – I‟m just looking to hear that they‟ve done some work to performance tune their queries. If they‟re doing fully logged individual record inserts, one at a time, into a data warehouse-size system, we‟re going to have problems down the road. (Yes, I‟ve actually worked with a BI developer that did millions of individual inserts per night in full recovery mode and thought the performance was the database‟s fault.)

Bonus points if they link back to the previous interview question and talk about whether or not they should disable constraints or referential integrity during data loads. (I don‟t care what their final answer is, but I just want them to know the pros and cons.)

5. What‟s the difference between a primary key and a clustered index?

This is almost a bonus question. Most of the time, the candidate doesn‟t know because it‟s a function of the data modeler or architect, not the developer. However, I want to see how the candidate reacts to tough questions. Ideally, they say in a relaxed tone of voice, “I‟m not sure, but I know who I‟d ask.” If they don‟t mention where they‟d go, ask them where they go for SQL Server

(29)

Bonus Points for This Candidate

4. What‟s your StackOverflow name?

I don‟t need to see a high reputation, but I do want to see an awareness of the site. This interview question serves two purposes: it finds out if they‟re serious enough to be active in the community, and it shows them that you‟re okay with their community activity. Start a conversation with them about the level of internet time that you find acceptable in the office, and encourage them to share their

knowledge with their peers. This sells the candidate on your shop.

3. Tell me about a time when a DBA got mad at you.

This is a spin on the classic interview question, “Tell me about a time when you failed.” Implemented a user-defined function, trigger, CLR in the database, or something else that made the DBA freak out? I want to hear that the candidate listened to what the DBA had to say, good or bad.

If they say it‟s never happened, rest assured it‟s going to happen soon.

2. How can you tell if a query will scale for production?

I want to hear that they do things like load tests or maybe look at execution plans.

I‟m sometimes comfortable when a senior developer says things like, “I can pretty well tell when something isn‟t going to scale, because I know the production boxes really well.” The key is asking a followup question about times when things didn‟t scale.

SUB Interview Questions And Answers

Page 1

Ques: 1 How You create the Table ? Ans:

(30)

data-type of each table field. We can also specify PRIMARY KEY and any other constraint like NOT NULL. For example:

CREATE TABLE employer

(NAME VARCHAR(80) PRIMARY NOT NULL,DSGN VARCHAR(5),AGE INTEGER,PAY INTEGER); Ques: 2 How can I Insert some data into the created table.

Ans:

When i would like to insert the data then we use to the 'INSERT INTO' command followed by table name and values to be inserted.

> If we need to insert a row with values for all columns, then use the following command :

INSERT INTO employer VALUES('Ram','MGR',25,25000);

> If we need to insert values for selected columns only, then we need to specify those column names also in the command as shown :

INSERT INTO employer (NAME) VALUES (\'Ramesh\'); Ques: 3 How can I Update the table?

Ans:

We have a two ways for upadating the table, Which is shown here : > Use UPDATE command with SET and name-value pairs like:

UPDATE Employer SET pay=40000;

> For updating a particular row, Then We use WHERE clause in UPDATE command like :

UPDATE Employer SET pay = 25000 WHERE NAME= 'Ram'; Ques: 4 How can I see the whole Table ?

Ans:

When we would like to see our table then we Use SELECT command to retrieve the data.

SELECT * FROM employer;

Ques: 5 How can i short list to the table with resect to the column? Ans:

When we would like to get the sorted listed of the data with respect to any coulmns , Then we can use ORDER BY clause :

For the example We can shortlist of the table with respect to columns Name as shown :

SELECT * FROM employer ORDER BY name;

Ques: 6 How can I retrieve few columns of all rows? Ans:

To retrieve few columns of all rows: SELECT name FROM employer;

Ques: 7 How can I retrieve all columns of a particular row ? Ans:

To retrieve all columns of a particular row: SELECT * FROM employer where name = 'Ramesh';

Ques: 8 How can I retrieve selected columns of a particular row? Ans:

To retrieve selected columns of a particular row: SELECT pay FROM employer WHERE name = 'Ram';

Ques: 9 How can I retrieve a row with columns having a particular pattern? Ans:

To retrieve a row with columns having a particular pattern. For the Example pay of all those employees whose name starts with A :

SELECT pay FROM Employer WHERE name like 'A%';

Ques: 10 How can I count number of records in the table? Ans:

To count number of records in the table .

For example we want to know How many employers are in the table : SELECT COUNT(*) FROM employer;

(31)

Ans:

To get the sum of a column .

For example we want to know total pay to be paid : SELECT SUM(PAY) FROM employer;

Ques: 12 How can I Use AND/OR in WHERE clause to retrieve data based on multiple condition?

Ans:

Use AND/OR in WHERE clause to retrieve data based on multiple condition : Ex. SELECT * FROM employer WHERE name LIKE 'A%' AND pay > 10000;

Ques: 13 How can I got group the results? Ans:

To group the results, use GROUP BY as in following: Ex.

SELECT * FROM employer GROUP BY dsgn; Ques: 14 How can I Having Clouse? Ans:

HAVING cause is using for the show groups satisfying a criteria, Ex. SELECT * FROM employer GROUP BY dsgn HAVING pay > 10000; Ques: 15 How Can I use IN Clause?

Ans:

IN clause uses when we would like to get results if a field has any of the given value :

Ex. SELECT * FROM employer where name IN ('Ramesh','Ram'); Ques: 16 How can I Add a column to the table?

Ans:

When we add a columns in the table we can done through ALTER command like : Ex. ALTER TABLE employer ADD exp INTEGER;

Ques: 17 How can I set an alias for person table using few columns only? Ans:

For this query we can use AS command as defined below: Ex.

SELECT NAME,DSGN FROM Employer AS employees;

Ques: 18 How can I delete a particular record in the Table ? Ans:

For delete a particular record, use DELETE command with WHERE clause like: Ex.

DELETE * FROM employer WHERE name='Ram';

Ques: 19 How can I delete all records of the table ? Ans:

For delete all records, We can use : Ex.

DELETE FROM Employer;

Ques: 20 How can I delete all records for using TRUNCATE command? Ans:

We can also delete all records using TRUNCATE command such as : Ex.

TRUNCATE TABLE employer

SUB Interview Questions And Answers

Page 2

Ques: 21 How can I drop the column added in step 10 above? Ans:

When we want to be do for like this then we can use ALTER command with DROP like this :

Ex. ALTER TABLE employer DROP exp;

Ques: 22 How can I drop the created table? Ans:

When i wold like to drop the create table then we Use DROP TABLE command followed by table name.

References

Related documents

As a consequence of the different water availability, the stomatal fraction of the ozone flux absorbed by vegetation varied from a range of 40 to 50% of the total flux in the

PostgreSQL DELETE statement allows you to delete one task more rows from the table then following shows basic.. DELETE records from search table in Teradata DELETE FROM tablename

Using empirical transaction data from FX markets and adopting an event-based time scale (known as intrinsic time), the spectral anal- ysis shows that various parts of the whole

– Interestingly, federal respondents were more likely to believe a private cloud model would best meet their organization‘s needs (37.0% compared to 23.6% state and local

[r]

Does not truncate does no trigger or if you might be deleted rows in sql commands will trigger is considered a where clause in truncate sql command with the delete command

Specify multiple methods, sql drop everything and sql delete based on its unique key used for closing this will assume no schema.. DROP TABLE emp;

In computer networking a routing table or routing information base RIB is a data table stored in a router or a network host that lists the routes to particular network destinations