Dear Readers, Welcome to SQL Server Interview Questions and Answers have been designed specially to get you acquainted with the nature of questions you may encounter during your Job interview for the subject of SQL Server. These SQL Server Questions are very important for campus placement test and job interviews. As per my experience good interviewers hardly plan to ask any particular questions during your Job interview and these model questions are asked in the online technical test and interview of many IT companies.
SQL - Structured query language is the standard command set used to communicate with the relational database management system.
Sql server - is commonly used as the backend system for websites and corporate CRMs and can support thousands of concurrent users.SQL Server is much more robust and scalable than a desktop database management system such as Microsoft Access.
Master - Stores system level information such as user accounts, configuration settings, and info on all other databases.
Model - database is used as a template for all other databases that are created
Msdb - Used by the SQL Server Agent for configuring alerts and scheduled jobs etc
Tempdb - Holds all temporary tables, temporary stored procedures, and any other temporary storage requirements generated by SQL Server.
TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE.
Online Transaction Processing (OLTP) relational databases are optimal for managing changing data. When several users are performing transactions at the same time, OLTP databases are designed to let transactional applications write only the data needed to handle a single transaction as quickly as possible.
Normalisation is an essential part of database design. A good understanding of the semantic of data helps the designer to built efficient design using the concept of normalization.
A Clustered index is a special type of index that reorders the way in which each records in the table are physically stored.
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 on disk.
Master
Model
Msdb
Tempdb
Resource
Denormalization is the process of attempting to optimize the performance of a database by adding redundant data or by grouping data.Denormalization is the reverse process of normalization.
Single row subquery
Multiple row subquery
Correralted row subquery
Constraints is a rule or restriction concerning a piece of data that is enforced at the data level. A Constraint clause can constrain a single column or group of columns in a table.
There are five types of Constraint namely
Null / Not Null
Primary Key
Unique
Check or Validation
Foreign Key or References Key
In SQL Server 2005 Backup Types are
Full
Transaction Log
Differential
Partial
Differential Partial
File and Filegroup
Copy Only Database Backups.
This is the physical storage for all of the data on disk. Pages are read into the buffer cache when users request data for viewing or modification. After data has been modified in memory (the buffer cache), it is written back to the data file during the checkpoint process.
The primary key is the columns used to uniquely identify each row of a table.
A table can have only one primary key.
No primary key value can appear in more than one row in the table.
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.
Implicit cursors
Explicit cursors
Paramaeteried cursors
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later.
Unique key is a one or more column that must be unique for each row of the table.
It is similar to primary key. Primary key column will not accept a null. Whereas the unique key column will accept a null values.
A Join combines columns and data from two or more tables (and in rare cases, of one table with itself).
Index is a general term for an Oracle/SQL features used to primarily to speed execution and imposes uniqueness upon certain data.
The most important of an index is to ensure uniqueness of rows and help in speedy retrieval of data.
The primary key is the columns used to uniquely identify each row of a table.A table can have only one primary key.
Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship between tables.
Clustering is a method of storing tables that are intimately related and often joined together into the same area on disk.
A cluster contains one or more tables, which have one or more column in common among them.
Atomicity
Consistency
Isolation
Durability
Synonym is an alternative method to creating a view that includes the entire table or view from another user it to create a synonym.
A synonym is a name assigned to a table or view that may thereafter be used to refer to it.
Active database is a database that includes active rules, mostly in the form of ECA rules(Event Condition rules). Active database systems enhance traditional database functionality with powerful rule processing cabalities, providing a uniform and efficient mechanism for database system applications.
HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
Minimize redundancy in data.
Remove insert, delete and update anamoly during the database activities.
Reduce the need to reorganize data it is modified or enhanced.
Normalisation reduces a complex user view to a set of small and stable subgroups of fields or relations.
Self join means joining one table with itself.
The self join can be viewed as a join of two copies of the same table.
Union will remove the duplicate rows from the result set while Union all does’nt.
The different phases of transaction are :
Case sensitivity
Accent sensitivity
Kana Sensitivity
Width sensitivity
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF›s can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
A Local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.
A Global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection are closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.
A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.
Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server.
A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table.
A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table.
Normalisation is an essential part of database design. A good understanding of the semantic of data helps the designer to built efficient design using the concept of normalization.
Stored Procedures are called by the programmer wherever it wants to fire but triggers fired automatically when insert,delete,update occured. And triggers can be implemented to tables & views only where as stored procedure used in the database independently.
A subquery must be enclosed in the parenthesis.
A subquery must be put in the right hand of the comparison operator
A subquery cannot contain a ORDER-BY clause.
A query can contain more than one sub-queries.
They get stored in master db in the sysxlogins table.
There are two types of replication in sql server are :
Push
Pull
Restores your previous execution context.If you have changed your execution context with EXECUTE AS, the REVERT statement will restore the last context prior to the EXECUTE AS.
The value NULL means UNKNOWN; it does not mean (empty string). Assuming ANSI_NULLS are on in your SQL Server database, which they are by default, any comparison to the value NULL will yield the value NULL.
First Normal Form
Second Normal Form
Third Normal Form
Boyce’s Normal Form
Fourth Normal Form
Fifth Normal Form
Pages are contained in extent. Every extent will have around eight data pages. But all the eight data pages are not created at once; they are created depending on data demand. So when a page becomes full it creates a new page, this process is called as “Page Split”.
Identity is a column that automatically generates numeric values.
Both SET and SELECT can be used to assign values to variables. It is recommended that SET @local_variable be used for variable assignment rather than SELECT @local_variable.
Examples
declare @i int
set @i=1
This is used to assign constant values.
select @i=max(column_name)from table_name
for ex.
select @i=max(emp_id) from table_emp.
char(n)Fixed length non unicode character data with length of n bytes.n must be a value from 1 through 8,000.
varchar(n)variable length non unicode character data with length of n bytes.
nvarchar(n)variable length unicode character data of n characters. n must be a value from 1 through 4,000.
There are three types of triggers.
DML Triggers
--> AFTER Triggers
--> INSTEAD OF Triggers
DDL Triggers
CLR Triggers
I. Use where clause
II. Select only required fields
III. Do join on indexed key fields
Stored Procedure:
A Stored procedure is a set of sql statements with a given name , which is physically stored in database in the compiled form. Once the stored procedure has been “stored”, client applications can execute the stored procedure over and over again without sending it to the database server again and without compiling it again. Stored procedures improve performance by reducing network traffic and CPU load.
1. CREATE PROCEDURE SPName
2. @param1 int,
3. @param2 int OUTPUT,
4. @param3 varchar(50) INOUT
5. AS
6. BEGIN
7. ----Sql statemt(s)----
8. END
User Defined Function(UDF):
User defined function is a database object which encapsulates one or more sql statements for reuse , which can accept zero or more parameters and return either a value or table. User defined fuctions contain useful logic for using another quaries or other database objects like stored procedures.
01. CREATE FUNCTION FunName (
02. @param1 int,
03. @param2 varchar(50),
04. )
05. RETURNS int
06. AS
07. BEGIN
08. Declare @RetVal int
09. ---sql statement(s)—
10. Return @RetVal
11.
END
Differences:
1. Procedures can accept input(default), output and inout type parameters for it.
Functions can accept only input type parameters.
2. Procedures may or may not return a value or may return more than one value using the OUTPUT and/or INOUT parameters. A procedure may return upto 1024 values through OUTPUT and/or INOUT parameters.
Function always returns only one value.
3. Stored procedure returns always integer value by default zero.
Function return type could be scalar or table or table values.
4. Stored procs can create a table but can’t return table.
Functions can create, update and delete the table variable. It can return a table
5. Stored Procedures can affect the state of the database by using insert, delete, update and create operations.
Functions cannot affect the state of the database which means we cannot perform insert, delete, update and create operations operations on the database.
6. Stored procedures are stored in database in the compiled form.
Function are parsed and conpiled at runtime only.
7. Stored procs can be called independently using exec keyword. Stored procedure cannot be used in the select/where/having clause.
Function are called from select/where/having clause. Even we can join two functions.
8. Normally stored procedure will be used for perform specific tasks.
Functions will be used for computing value.
9. Stored procedure allows getdate () or other non-deterministic functions can be allowed.
Function won’t allow the non-deterministic functions like getdate().
10. In Stored procedures we can use transaction statements. We can’t use in functions.
11. The stored procedures can do all the DML operations like insert the new record, update the records and delete the existing records.
The function won’t allow us to do the DML operations in the database tables like in the stored procedure. It allows us to do only the select operation. It will not allow to do the DML on existing tables. But still we can do the DML operation only on the table variable inside the user defined functions.
12. Temporary tables (derived) can be created in stored procedures.
It is not possible in case of functions.
13. when sql statements encounters an error, T-SQL will ignore the error in a SPROC and proceed to the next statement in the remaining code.
In case of functions, T-SQL will stop execution of next statements.
SP are precompiled and contain an execution plan with it. Hence, they are faster.
Only one. In case of Oracle, we can have multiple NULL values in a Unique key field.
select empno,ename from emp where deptno in(select deptno from dept where dept.deptno=emp.deptno)
when inner subquery has an reference to outer query then this is know as Correlated sub-query.
Indexes in databases are very much similar to Indexes in Books. Indexes help in searching data faster.
Types: Clustered Index
Non-Clustered Index
Clustered Index:
1 Only one clustered index allowed per table
2 Physically rearranges the data
3 For use on columns that are frequently searched for range of data
Non-clustered Index:
1 Upto 249 non-clustered index allowed per table
2 Doesn’t rearrange the data. Keeps a pointer to the data.
3 For use on columns that are searched for single value.
Joins are used to retrieve data from multiple tables.Following are the types of joins:
Inner join
Left outer join
Right outer join
Full outer join
Cross join
A SQL transaction is a sequence of operations performed as a single unit of work. If all the tasks are completed successfully, then the transaction is committed (saved). If a single task fails, the transaction is rolled back (discarded).
A SQL transaction must exhibit ACID property, i.e Atomicity, Consistency, Isolation, and Durability.
Atomicity: A transaction is always treated as a single unit of work, i.e. either all the tasks are performed or none of them, no intermediate stage.
Consistency: When a transaction is completed, it must leave all data in a consistent state.
Isolation: Modifications made by a transaction must be isolated from the modifications made by other transactions.
Durability: After a transaction is completed, it’s effects are permanently in place in the system.
When we perform a SELECT, INSERT, UPDATE or DELETE query, it returns a COUNT (number of rows affected) when SET NOCOUNT OFF. If SET NOCOUNT ON, it doesn’t return the COUNT.
There are many ways. Simplest answer is:
i. Let the table tab1 contains duplicate records.
ii. Insert distinct records from tab1 in a temporary table #temp
INSERT INTO #temp
SELECT DISTINCT * FROM tab1
iii. Delete all rows from original table tab1
DELETE FROM tab1
iv. Insert from temporary table
INSERT INTO tab1
SELECT * FROM #temp
Try other solutions yourself.
The query below demonstrates how to find the 5th highest salary. Replace 5 with any integer to get nth salary.
SELECT TOP 1 SALARY
FROM (SELECT DISTINCT TOP 5 SALARY
FROM EMPLOYEE ORDER BY SALARY DESC) a
ORDER BY SALARY ASC