SQL Interview Questions With Answers
Download SQL Interview Questions With Answers...
SQL Interview Questions with Answers http://sql-plsql.blogspot.com/2009/04/sql-interviewquestions.html Category:
Published on: 9th Jan 2011 | 1307800 people have read this article.
Thanks to site Visitor Vicky for sharing the SQL Interview Questions.
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
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?
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. 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. 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. 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. 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"
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. 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.
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.
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
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?
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
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
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
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: *
* Transactional replication (with immediate updating subscribers, with queued updating
* 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
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 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
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 CASE
salary salary salary
+ + +
5000 7000 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. 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
[HAVING [ORDER BY order__expression [ASC | DESC] ]
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
OUTER JOINs are further classified as LEFT
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
@@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 TSQL, 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
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
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.
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 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
INSERT emp SELECT 5,2,'Sourabh' SELECT FROM
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
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 INSERT INSERT INSERT INSERT
INTO INTO INTO INTO INTO
Employee_Test Employee_Test Employee_Test Employee_Test Employee_Test
VALUES VALUES VALUES VALUES VALUES
('Anees',1000); ('Rick',1200); ('John',1100); ('Stephen',1300); ('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
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 insert insert insert insert insert insert
into into into into into into into
photo_test photo_test photo_test photo_test photo_test photo_test photo_test
values(17,16,'photo/cricket1.jpg'); values(17,17,'photo/base1.jpg'); values(18,18,'photo/forest1.jpg'); values(18,19,'photo/tree1.jpg'); values(18,20,'photo/flower1.jpg'); values(19,21,'photo/laptop1.jpg'); 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:pgm_main_category_id 17 17 18 18 19 19
Collapse | Copy Code
pgm_sub_category_id 15 16 18 19 21 22
file_path photo/bb1.jpg photo/cricket1.jpg photo/forest1.jpg photo/tree1.jpg photo/laptop1.jpg 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:CREATE TABLE Employee_Test1
Collapse | Copy Code
( Emp_ID INT, Emp_name Varchar(100), Emp_Sal Decimal (10,2) ) INSERT INSERT INSERT INSERT INSERT INSERT INSERT
INTO INTO INTO INTO INTO INTO INTO
Employee_Test1 Employee_Test1 Employee_Test1 Employee_Test1 Employee_Test1 Employee_Test1 Employee_Test1
VALUES VALUES VALUES VALUES VALUES VALUES VALUES
(1,'Anees',1000); (2,'Rick',1200); (3,'John',1100); (4,'Stephen',1300); (5,'Maria',1400); (6,'Tim',1150); (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:Emp_ID 1 2 3 4 5 6
Emp_name Anees Rick John Stephen Maria Tim
Collapse | Copy Code
Emp_Sal 1000 1200 1100 1300 1400 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:-
Collapse | Copy Code
Emp_ID 1 2 3 4 5 6
Emp_name Anees Rick John Stephen Maria Tim
Emp_Sal 1000 1200 1100 1300 1400 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.
What is the advantage to use trigger in your PL?
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 an interface to relational database systems. It was developed by IBM in the 1970s for
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. instead the leaf node contains index rows.
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
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 INNER JOIN 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? SELECT DATENAME(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 1 2
EmpName Raja Rani
Gender Male 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 E1.Salary) Query to Find the 2nd Maximum Salary
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
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
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, >, >=, 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; Ques: 11 How can I get the sum of a column?
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. Ex . DROP TABLE employer;
Ques: 23 How can I drop the database? Ans: When we like to drop Database thn we use DROP DATABASE command followed by database name : Ex. DROP DATABASE emp; Ques: 24 How can I know max value of numeric column in the table ? Ans: Using the Max function, we can know the average value of a numeric column. Ex. SELECT MAX(SAL) employer; Ques: 25 How can I know Min value of numeric column in the table ? Ans: Using the Min function, we can know the average value of a numeric column. Ex. SELECT MIN(SAL) employer; Ques: 26 How can I know Avg value of numeric column in the table ? Ans: Using the Avg function, we can know the average value of a numeric column. Ex. SELECT Avg(SAL) employer; Ques: 27 What do you mean by SELECT DISTINCT Statement in Sql? Ans: Distinct Statement is bassically use when in the table some of the columns may contain duplicate values. It is not a problem .some time we want to be these type of values like : ex. if we have a any table , and we wold like to know the name of those persons who are from same place. that time we use this statement : Syntax : SELECT DISTINCT column_name(s) FROM table_name Ex . SELECT DISTINCT City FROM employer; Ques: 28 How can i use the TOP Clause in the SQL? Ans: We are using Top clause becouse if we like to know some limit of rows see in the output or some %age of the table we would like to show then we use this clause like : > If we would like to see select only the two first records in the table above : Ex. SELECT TOP 2 * FROM wmployer; > If we would like to see select only 50% records in the table above : Ex. SELECT TOP 50 PERCENT * FROM empoyer; Ques: 29 How can i use the % Wildcard ? Ans: This wild card we use when we want to show which name who start from some special char like : Ex. we want to select the persons living in a city that starts with "Ka" from the "employer" table. Ex. SELECT * FROM empoyer WHERE City LIKE 'ka%'; Ques: 30 How can I use _ Wildcard? Ans: we want to select the employer with a first name that starts with any character, followed by "Ka" from the "employer" table. Ex. SELECT * FROM employer WHERE FirstName LIKE '_ka'; > Now we want to select the emplyer with a last name that starts with "R", followed by any character, followed by "end", followed by any character, followed by "on" from the "employer" table. Ex. SELECT * FROM employer WHERE LastName LIKE 'R_end_on'; Ques: 31 How can i use [charlist] Wildcard? Ans: Now we want to select the employer with a last name that starts with "A" or "n" or "k" from the "employer" table. Ex. SELECT * FROM employer WHERE LastName LIKE '[ank]%'; Ques: 32 What the use of SQL Alias In sql query? Ans: SQL Alias is the bassically use for the make a easier to the query, I mean when
you have a very long or complex table names or column names. Then we can use this function like : Ex. Assume we have a table called "Employer" and another table called "Product_Orders". We will give the table aliases of "e' an "po" respectively. Now we would like to list all the orders that "Modi groups" is responsible for : SELECT Statement With Alias: SELECT po.OrderID, e.LastName, e.FirstName FROM Employer AS e , Product_Orders AS po WHERE p.LastName='Modi' WHERE p.FirstName='Groups' Now SELECT Statement with out Alias : SELECT Product_Orders.OrderID, Employer.LastName, Employer.FirstName FROM Employer, Product_Orders WHERE Employer.LastName='Modi' WHERE Emloyer.FirstName='Groups'; Now we can see that with alias query is so easy . Ques: 33 How can use The INNER JOIN Keyword in Sql? Ans: The INNER JOIN bassically use for the return rows when there is at least one match in both tables. Systax : SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name Ques: 34 How can I use LEFT JOIN Keyword? Ans: In some databases LEFT JOIN is called LEFT OUTER JOIN. The LEFT JOIN keyword is bassicaly a use for the returning the all rows from the left table (table_name1), even if there are no matches in the right table (table_name2). Syntax :
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name Ques: 35 What is the use of RIGHT JOIN Keyword? Ans: In some databases RIGHT JOIN is called RIGHT OUTER JOIN. The RIGHT JOIN keyword is bassically use for the Returning to the all rows from the right table (table_name2), even if there are no matches in the left table (table_name1). Syntax :
SELECT column_name(e) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name Ques: 36 How can i use FULL JOIN Keyword? Ans: The FULL JOIN keyword is bassically use for returning rows when there is a match in one of the tables. Syntax :
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name Ques: 37 How can I use the UNION Operator? Ans: The UNION operator is used to combine the result-set of two or more SELECT statements. each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. Syntax for UNION : SELECT column_name(e)FROM
UNION SELECT column_name(e) FROM table_name2 SQL UNION ALL Syntax SELECT column_name(e) FROM table_name1 UNION ALL SELECT column_name(e) FROM table_name2 Ques: 38 How can i use INTO Statement ? Ans: The SQL SELECT INTO statement bassically for the use in many fields and It can be used to create backup copies of tables.The SELECT INTO statement is use for the selects data from one table and It can also be inserts it into a different table. The SELECT INTO statement is mostly use for the backup copies of tables. Syntax : SELECT *INTO new_table_name [IN externaldatabase] FROM old_tablename > we can select only the columns we want into the new table : SELECT column_name(e)INTO new_table_name [IN externaldatabase] FROM old_tablename Ques: 39 HOw can i create the Database? Ans: DATABASE statement is bassically crate the The CREATE DATABASE Comand. Syntax : CREATE DATABASE database_name Ques: 40 How do we use NOT NULL Constraint? Ans: Not NUll Constraints is bassically means that we cann't insert a new record, or also cant be update a record without adding a value to this field. The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. For the example The following SQL enforces the "E_Id" column and the "LastName" column to not accept NULL values : CREATE TABLE Employer(E_Id int NOT NULL,LastName varchar(255)NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))
Page 3 Ques: 41 How can I create the Index? Ans: The CREATE INDEX statement is bassically use for the create indexes in tables. Its mainly Indexes allow the database application to find data fast, without reading the whole table. Syntax : CREATE INDEX index_name ON table_name (column_name) > When we would like to Unique Index then sysntax is .....but its have not alowed duplicacy : Syntax : CREATE UNIQUE INDEX index_name ON table_name (column_name) Ques: 42 What is the use of FIRST() Function? Ans: The FIRST() function is used to the returning the first value of the selected column. Syntax : SELECT FIRST(column_name) FROM table_name Ques: 43 What is the use of LAST() Function? Ans: The LAST() function is mainly use for the returning the Last value of the selected column. Syntax : SELECT FIRST(column_name) FROM table_name Ques: 44 What is the use of UCASE() Function?
Ans: The UCASE() function is bassically use for the convert the value of a field to uppercase. Syntax: SELECT UCASE(column_name) FROM table_name Ques: 45 What is the use of LCASE() Function? Ans: The LCASE() function is basscially use for the converts the field to Lowercase. Syntax : SELECT UCASE(column_name) FROM table_name Ques: 46 What is the use of MID() Function? Ans: The MID() function is bassically use for the eaxtract the charectors from the txt feilds. Syntax :SELECT MID(column_name,start[,length]) FROM table_name Ques: 47 what is the use of LEN() Function? Ans: The LEN() function is basically use for the returning the value of length of the value in a text field. Syntax : SELECT LEN(column_name) FROM table_name Ques: 48 HOW can i use the ROUND() Function? Ans: The ROUND() function is bassically use for the round a numeric field to the number of decimals specified. Syntax : SELECT ROUND(column_name,decimals) FROM table_name Ques: 49 How can i use to the NOW() Function? Ans: The NOW() function is using for the returning the current system date and time. Syntax : SELECT NOW() FROM table_name Ques: 50 How can i use to the FORMAT() Function? Ans: The FORMAT() function is basscially used to format how a field is to be displayed. > Syntax : SELECT FORMAT(column_name,format) FROM table_name
1. What is normalization? – Well a relational database is basically composed of tables that contain related data. So the Process of organizing this data into tables is actually referred to as normalization. 2. What is a trigger? – Triggers are basically used to implement business rules. Triggers are also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database. 3. What is an Index? – When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index. What are the types of indexes available with SQL Server? – There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered. 4. What is the basic difference between clustered and a non-clustered index? – The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of nonclustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.
5. What are cursors? – Well cursors help us to do an operation on a set of data that we retrieve by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retrieval one by one and remove rows which have duplicate values. 6. When do we use the UPDATE_STATISTICS command? – This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. 7. Which TCP/IP port does SQL Server run on? – SQL Server runs on port 1433 but we can also change it for better security. 8. Can you tell me the difference between DELETE & TRUNCATE commands? - Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. 9. Can we use Truncate command on a table which is referenced by FOREIGN KEY? – No. We cannot use Truncate command on a table with Foreign Key because of referential integrity. 10. What is the use of DBCC commands? – DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks. 11. What command do we use to rename a db? How could you rename a column through SQL? sp_renamedb ‘oldname’ , ‘newname’ Well sometimes sp_reanmedb may not work you know because if someone is using the db it will not accept this command so what do you think you can do in such cases? – In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode. 12. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? – Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. 13. What do you mean by COLLATION? – Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary – case insensitive and binary. 14. What is a Linked Server? - Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. Can you link only other SQL Servers or any database servers such as Oracle? - We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group. 15. How do you troubleshoot SQL Server if its running very slow? - First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes 16. Let’s say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot? - First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection ——Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues. 17. What are the authentication modes in SQL Server? – Windows mode and mixed mode (SQL & Windows).
18. Where do you think the users names and passwords will be stored in sql server? – They get stored in master db in the sysxlogins table. 19. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? – For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER –m which will basically bring it into the maintenance mode after which we can restore the master db. 20. What is BCP? When do we use it? BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same. 1. What is the use of the Except clause? EXCEPT clause is similar to the MINUS operation in Oracle. The EXCEPT query and MINUS query returns all rows in the first query that are not returned in the second query. Each SQL statement within the EXCEPT query and MINUS query must have the same number of fields in the result sets with similar data types. 2. What does the NOLOCK clause do in a T-SQL statement? Using the NOLOCK query optimizer hint is generally considered good practice in order to improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) lock. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay (blocking). 3. What is SQLCMD? SQLCMD is the enhanced version of the isql and osql and it provides way more functionality than other two options. In other words sqlcmd is better replacement of isql (which will be deprecated eventually) and osql (not included in SQL Server 2005 RTM). sqlcmd can work two modes ‐ i) BATCH and ii) interactive modes. 4. What does integration of .NET Framework mean for SQL Server 2005? SQL Server 2005 introduces a new array of possibilities because of its tight integration with the .NET Framework. It allows you to write stored procedures, triggers, and other such objects in a .NET-compliant language such as C# and VB.NET, compile them as a dynamic link library, and register them inside SQL Server. 5. What is Full Text Search? How does it get implemented in SQL server 2005? SQL Server 2008 provides the functionality for applications and users to issue full-text queries against character-based data in SQL Server tables. Before full-text queries can be run on a given table, the database administrator must create a full-text index on the table. The full-text index includes one or more character-based columns in the table.
These columns can have any of the following data types: char, varchar, nchar, nvarchar, text, ntext, image, xml, varbinary, or varbinary(max). 6. What is the support of Web Services in SQL Server? Microsoft SQL Server 2005 provides a standard mechanism for accessing the database engine using SOAP via HTTP. Prior to SQL Server 2005, the only mechanism available to connect to SQL Server was through a custom binary protocol named Tabular Data Stream (TDS). Providing SOAP/HTTP access enables a broader range of clients to access SQL Server, including "zero foot print" clients, because there is no longer a need to have a Microsoft Data Access Components (MDAC) stack installed on the client device trying to connect to SQL Server. It facilitates interoperability with .NET, SOAP Toolkit, Perl, and more on a variety of platforms. Since the SOAP/HTTP access mechanism is based on well-known technologies such as XML and HTTP, it inherently promotes interoperability and access to SQL Server in a heterogeneous environment. Any device that can parse XML and submit HTTP requests can now access SQL Server. 7. What is Database Partitioning in SQL Server? Partitioning allows you to improve SQL Server read/write performance by distributing a table over multiple databases hosted on different hard drives and/or servers. 8. What are the New Data types introduced in SQL Server 2005? varchar(max), nvarchar(max), varbinary(max), and xml 9. What is SQL Service Broker in SQL Server 2005? With Service Broker, a feature in Microsoft SQL Server 2005, internal or external processes can send and receive guaranteed, asynchronous messages by using extensions to Transact-SQL Data Manipulation Language (DML). Messages can be sent to a queue in the same database as the sender, to another database in the same SQL Server instance, or to another SQL Server instance either on the same server or on a remote server. 10. What is COMMIT & ROLLBACK statement in SQL? The commit option is used to commit a transaction or statement of work to the database and the rollback option to rollback any work since the last commit. 11. The DML component of SQL comprises four basic statements. What are they? The DML component of SQL comprises four basic statements: SELECT to get rows from tables UPDATE to update the rows of tables DELETE to remove rows from tables INSERT to add new rows to tables 12. What is the difference between UNION ALL Statement and UNION? UNION – The UNION command is used to select related information from two related tables much like the join command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL- The UNION ALL command is equal to the UNION command except that UNION ALL selects all values. 13. What are the different types of LOCKS? Shared locks, Update locks and Exclusive locks Shared locks are used for operations that do not change or update data, such as a SELECT statement. 1. What is a NOLOCK? Using the NOLOCK query optimizer hint is generally considered good practice in order to improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is read. The result is a Dirty Read, which means that another process could be updating the data at the exact time you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) lock. This means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the reads have completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay (blocking). 2. What are three SQL keywords used to change or set someone’s permissions? Grant – This keyword is used to grant access to a particular DB Deny - Denies permission to a user. Prevents that user from inheriting the permission through its group or role memberships. Revoke – This keyword is used to take away permissions to a particular DB. 3. Using query analyzer, name 3 ways you can get an accurate count of the number of records in a table? 1. Select count(*) from 2. Select count_big(*) from 3. Select rows from sysindexes where id=? 4. What is an execution plan? When would you use it? How would you view the execution plan? When it comes time to analyze the performance of a specific query, one of the best methods is to view the query execution plan. A query execution plan outlines how the SQL Server query optimizer actually ran (or will run) a specific query. This information is very valuable when it comes time to find out why a specific query is running slow. There are several different ways to view a query‘s execution plan. They include: · From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down menu). If you turn this option on, then whenever you run a query in Query Analyzer, you will get a query execution plan (in graphical format) displayed in a separate window.
If you want to see an execution plan, but you don‘t want to run the query, you can choose the option "Display Estimated Execution Plan" (located on the Query
drop-down menu). When you select this option, immediately an execution plan (in graphical format) will appear. The difference between these two (if any) is accountable to the fact that when a query is really run (not simulated, as in this option), current operations of the server are also considered. In most cases, plans created by either method will produce similar results. When you create a SQL Server Profiler trace, one of the events you can collect is called: MISC: Execution Plan. This information (in text form) shows the execution plan used by the query optimizer to execute the query. From within Query Analyzer, you can run the command SET SHOWPLAN_TEXT ON. Once you run this command, any query you execute in this Query Analyzer sessions will not be run, but a text-based version of the query plan will be displayed. If the query you are running uses temp tables, then you will have to run the command, SET STATISTICS PROFILE ON before running the query.
5. What is the difference between Function and Stored Procedure? Both functions and stored procedures are sequence of SQL statements stored in the database for future access. Difference between them is that: Procedures are parsed and compiled. They are stored in compiled format in the database where as Functions are compiled and executed runtime. 6. What is data integrity? Explain constraints? Data integrity refers to the accuracy, consistency, and correctness of the data. Rules are set up in the database to help ensure the validity of the data. Data integrity falls into the following categories: Domain integrity, also known as column integrity, specifies a set of data values that are valid for a column. This can be defined by the data type, format, data length, nullability, default value, and range of allowable values. Entity integrity, also known as table or row integrity, requires that all of the rows in a table have a unique identifier, enforced by either a PRIMARY KEY or UNIQUE constraint. Referential integrity ensures that the relationships between tables are maintained. Every FOREIGN KEY value in the referencing table must either be NULL, match a PRIMARY KEY value, or match a UNIQUE key value in an associated referenced table. The referenced row cannot be deleted if a FOREIGN KEY refers to the row, nor can key values be changed if a FOREIGN KEY refers to it. Also, you cannot insert or change records in a referencing table if there is not an associated record in the primary referenced table. User-defined integrity lets you define business rules that do not fall under one of the other integrity categories, including column-level and table-level constraints. 7. What is a job? SQL Server job is a collection of steps executed by the database engine by SQL Server Agent. The job can perform many different functions within it that can save time and effort on the part of employees. For example, a job can be created to import a daily update file internally or externally via an FTP server. Another job can be configured to handle routine maintenance tasks as well as handling one-time production updates that may be needed in the future. 8. What are the type of joins? When do we use Outer and Self joins?
Cross Join 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. The common example is when company wants to combine each product with a pricing table to analyze each product at each price. Inner Join A join that displays only the rows that have a match in both joined tables is known as inner Join. This is the default type of join in the Query and View Designer. Outer Join A join that includes rows even if they do not have related rows in the joined table is an Outer Join. You can create three different outer join to specify the unmatched rows to be included: Left Outer Join: In Left Outer Join all rows in the first‐named table i.e. "left" table, which appears leftmost in the JOIN clause are included. Unmatched rows in the right table do not appear. Right Outer Join: In Right Outer Join all rows in the second‐named table i.e. "right" table, which appears rightmost in the JOIN clause are included. Unmatched rows in the left table are not included. Full Outer Join: In Full Outer Join all rows in all joined tables are included, whether they are matched or not. Self Join This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. 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. The common example is when company has a hierarchal reporting structure whereby one member of staff reports to another. Self Join can be Outer Join or Inner Join. 9. What are the different editions of SQL Server 2005 available? a) Express Edition b) Mobile Edition c)Workgroup Edition d) Developer Edition e) Standard Edition f) Enterprise Edition 10. What are database snapshots?
Database Snapshots is a new feature introduced in SQL Server 2005 which enables you to take a point-in-time, read-only snapshot of a database. A database snapshot can be queried as if it were just another user database and can exist for as long as needed. When you‘re done using it, the database snapshot can be deleted or restored back onto the source database. 11. What are the differences between the varchar and nvarchar data types. Which one of these is more space efficient? Varchar(n) – Variable-length non-Unicode character data with a length of n characters, where n is a value from 1 through 8,000, or max. max indicates a maximum storage size of 2^31–1 bytes. (varchar(max) is preferred over the use of the depreciated text data type). Size -: Actual length of data entered + 2 bytes nvarchar(n) -Variable-length Unicode data of n characters, where n is a value from 1 through 4,000, or max. max indicates a maximum storage size of 2^31-1 bytes. (nvarchar(max) is preferred over the use of the depreciated ntext data type) Size -: 2* Actual length of data entered + 2 bytes 12. What are DMV’s ? Give an example. Return information on server state or database state that can be used for monitoring the health of a server instance and databases, and diagnose performance problems. DMVs can be identified by their name, which begins with ‖dm_,‖ plus an abbreviation of what category the DMV is a part, then a description of what the view returns. For example, dm_db_file_space_usage is part of the database category of DMVs and returns information on file space usage. 13. Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible? Yes. Because Transact‐SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels. 14. What is Log Shipping? 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. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval. 15. What is the difference between a Local and a Global temporary table?
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 is 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. 16. What are the basic functions for master, msdb, model, tempdb and resource databases? The master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care. The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping. The tempdb holds temporary objects such as global and local temporary tables and stored procedures. The model is essentially a template database used in the creation of any new user database created in the instance. The resource Database is a read‐only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata. 17. What are Common Table Expressions (CTE)? What are the Advantages of using CTE? CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Advantages of using CTE :Using CTE improves the readability and makes maintenance of complex queries easy. The query can be divided into separate, simple, logical building blocks which can be then used to build more complex CTEs until final result set is generated. CTE can be defined in functions, stored procedures, triggers or even views. After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data. Sql Server (25 questions) - New
Can you explain about buffer cash and log Cache in sql server? Latest answer: Buffer Cache: Buffer cache is a memory pool in which data pages are read. It performance of the buffer cache is indicated as follows:............. Read answer
What is a Trace frag? Where do we use it? Latest answer: Temporary setting of specific server characteristics is done by trace tags. DBCC TRACEON is the command to set the trace flags. Once activated, trace flag will be in effect until the server is restarted............... Read answer
SSIS interview questions Difference between control flow and data flow?, If you want to send some data from Access database to SQL server database. What are different component of SSIS will you use?, Explain why variables called the most powerful component of SSIS?.................. Read answer
Describe how to use Linked Server. Latest answer: MS SQL Server supports the connection to different OLE DB on an ad hoc basis. This persistent connection is referred as Linked Server.............. Read answer
Explain how to send email from database. Latest answer: SQL Server has a feature for sending mail. Stored procedures can also be used for sending mail on demand. With SQL Server 2005, MAPI client is not needed for sending mails................ Read answer
Explain how to make remote connection in database Latest answer: The following is the process to make a remote connection in database: - Use SQL Server Surface Area Configuration Tool for enabling the remote connection in database................... Read answer
Difference between cross join and Full outer join. Latest answer: Cross Join : No join conditions are specified. Results in pairs of rows. Results in Cartesian product of two tables............... Read answer
Explain the purposes of OPENXML clause sql server stored procedure. Latest answer: OPENXML parses the XML data in SQL Server in an efficient manner. It‟s primary ability is to insert XML data to the RDB. It is also possible to query the data by using OpenXML................ Read answer
What is the order in which the SQL query is executed? Latest answer: The following is the order of executing SQL query: The query goes to the shared pool that has information like parse tree and execution plan for the corresponding statement............... Read answer
Explain how to store pdf file in sql server. Latest answer: Create a column as type „blob‟ in a table. Read the content of the file and save in „blob‟ type column in a table............... Read answer
Explain the concepts and capabilities of SQL Server. Latest answer: Microsoft SQL server is a relational database management system. It uses MS- SQL as the query language. SQL Server offers a high level of security, reliability and scalability depending on the business needs.............. Read answer
SQL Server interview questions for freshers and experienced SQL Server 2008 interview questions Explain inline variable assignment in sql server 2008 with an example. What is Compound Operators in sql server 2008? Explain with an example SQL Server 2008 introduces automatic auditing. Explain its benefits............. Read answer
Explain the use of keyword WITH ENCRYPTION. Create a Store Procedure with Encryption. Latest answer: WITH ENCRYPTION Indicates that SQL Server will convert the original text of the CREATE PROCEDURE statement to an encrypted format. Users that have no access to system................ Read answer
What is a linked server in SQL Server? Latest answer: A linked server allows remote access. Using this, we can issue distributed queries, update, commands, and transactions across different data sources................ Read answer
Features and concepts of Analysis Services Latest answer: Analysis service provides a combined view of the data used in OLAP or Data mining. Services here refer to OLAP, Data mining. Analysis services assists in creating, designing........... Read answer
What is Analysis service repository? Latest answer: Each server running analysis service has a repository to store objects of the computer running Analysis Services an Analysis service repository stores the information about the............. Read answer
What is SQL service broker? Latest answer: SQL service broker provides asynchronous queuing functionality to SQL server. Once message is sent to the SQL server................ Read answer
What is user defined datatypes and when you should go for them? Latest answer: User defined datatypes is created by using base SQL Server data type by providing a descriptive name................. Read answer
What is bit datatype? Latest answer: Bit datatype is used to store boolean information................ Read answer
What is lock escalation? Latest answer: Lock escalation from SQL Server 7.0 onwards, is dynamically managed by SQL Server. It is.......... Read answer
What is blocking? Latest answer: Blocking happens when one connection from an application holds a lock and a second............ Read answer
What is Public Role in SQL Server? Latest answer: Every database has a public role which holds all the default permissions for the users in a database................. Read answer
Discuss about SQL Server Login. Latest answer: SQL server login is used to connect to SQL server. This used when login in through the windows login credentials is not existent............. Read answer
Discuss about Builtin\Administrator. Latest answer: The built in Administrator Account is basically used during some setup to join some machine in the domain............ Read answer
Failover clustering overview Latest answer: Failover clustering is mainly used for data availability. Typically in a failover cluster, there are two machines. One machine provides the basic services and the second is available to run.................. Read answer
Describe the XML support SQL server extends. Latest answer: SQL server can return XML document using FOR XML clause................. Read answer
Explain in brief how SQL server enhances scalability of the database system. Latest answer: SQL Server has efficient ways to enhance scalability of the database system............... Read answer
What is SQL Server English Query? Latest answer: SQL Server English Query helps to build applications that can accept query............. Read answer
What is the purpose of SQL Profiler in SQL server? Latest answer: SQL Profiler captures SQL Server events from a server. The events are saved................. Read answer
What are the ways available in SQL Server to execute SQL statements? Latest answer: SQL Server uses different ways to execute SQL statements which are listed below................ Read answer
Explain Full-Text Query in SQL Server. Latest answer: SQL Server supports searches on character string columns using Full-Text Query............... Read answer
Explain the phases a transaction has to undergo. Latest answer: The several phases a transaction has to go through are listed here. Database.............. Read answer
What is XPath? Latest answer: XPath is a language defined by the W3C, used to select nodes from XML documents.............. Read answer
Define the rules for designing Files and File groups in SQL Server. Latest answer: A file or file group can only be used by one database. For example, the files abc.mdf and abc.ndf contains................. Read answer
What are the Authentication Modes in SQL Server? Latest answer: SQL Server supports two security (authentication) modes................ Read answer
Explain Data Definition Language, Data Control Language and Data Manipulation Language. Latest answer: Data definition language is used to define and manage all attributes and properties of a database.............. Read answer
What are the steps to process a single SELECT statement? Latest answer: SQL Server uses the following steps to process a single SELECT statement............ Read answer
What are the restrictions while creating batches in SQL Server? Latest answer: CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TRIGGER, and CREATE VIEW statements.............. Read answer
Explain GO Command. Latest answer: GO Command is used to signal the end of a batch............... Read answer
What is the significance of NULL value and why should we avoid permitting null values? Latest answer: Null means no entry has been made. It implies that the value is either unknown or undefined............ Read answer
What is the difference between UNION and UNION ALL? Latest answer: UNION command selects distinct and related information from two tables. On the other hand.............. Read answer
What is use of DBCC Commands? Latest answer: Database Consistency Checker Commands give details in form of statistics about the SQL Server.............. Read answer
What is Log Shipping? Latest answer: UNION command selects distinct and related information from two tables. On the other hand............. Read answer
What is the difference between a Local and a Global temporary table? Latest answer: A local temporary table lives until the connection is valid or until the duration of a compound statement......... Read answer
What is the STUFF and how does it differ from the REPLACE function? Latest answer: STUFF function is used to insert a string into another string by deleting some characters specified............. Read answer
Sql Server interview - May 7, 2011 by Swati Parakh Explain various data region available in SSRS with their use. Data regions are report items used to display data from a single dataset. You can perform grouping, sorting and various aggregate functions on data in data region. In SSRS 2005, there were 4 data regions:1. Table 2. Matrix
3. List 4. Chart While in SSRS 2008, there are one additional data region namely Gauge. Let‟s explain each one of them: 1. Table - Table Data region has fixed tabular structure i.e. fixed number of columns. It is useful for displaying data grouped by row. You can have maximum of 1 report item per cell. The size of table depends on number of rows dataset fetches i.e., if number of rows returned by dataset is more; it can expand to multiple pages. 2. Matrix – A matrix data region display data in pivot table format, hence also popularly known as pivot table or crosstab report. It has minimum of one row group and one column group. The size of matrix data region depends on columns and rows fetched. 3. List - A list data region is free layout. It is useful for complex reporting resign. The list can be used to display multiple table and matrix. Each getting data from different dataset. 4. Chart – This data region is for displays the data graphically i.e., in form of chart. A various chart types are available in SSRS 2008 namely line, pie chart, columns etc. 5. Gauge - This can be used in a table or matrix to show the relative value of a field in a range of values in the data region. You can also add a gauge to the design surface to show a single relative value.
What are various ways to enhance the SSRS report? Explain. There are various ways in which you can enhance your report: 1. Display your data in graphic format using Chart Region. 2. Use sorting. 3. If couple of reports are related, you can make them interactive using connect them using bookmark link, hyper link or drill through report link. 4. Adding sub-report. Sub-report is a stand-alone report which can be link to another report based on its content using parameter. 5. Add custom fields. Custom fields provide with same functionality as alias columns provide in SQL server query. It is the timing of the operation that differs from the alias columns. The calculation is performed on dataset by report server. 6. Using expression. 7. Using custom code. SSRS allows including custom code written in VB.Net. 8. Add document map (navigational links to report item once report is rendered) to report.
Sql Server interview - July 7, 2011 by Swati Parakh What are various aggregate functions that are available? The following are various aggregate functions available:1. SUM 2. AVG 3. COUNT 4. COUNTDISTINCT 5. MAX 6. MIN 7. STDEV 8. STDEVP 9. VAR 10. VARP By default, SUM is the aggregate function used for numeric data type.
How do you integrate the SSRS reports in your application? There are 3 ways in which you can integrate reports into your application:1. Navigating to URL i.e. https:\\servername\reportservername\reportname – This is simplest and most popular way. A separate login might be required since we are directly calling the report from report server. Address of report server gets expose to user. 2. Using IFrame, Browser control or Report Viewer Control – In this approach, we embed the URL of report server in our application, hence address of reportserver is not exposed. No separate window opens. A user does not come to know that he has moved to different server. 3. Programmatically sending a web request using SOAP to report server.
Explain use of Expression builder. Expressions provide us with flexibility to customize our report. It is written in Visual basic and is used throughout the report to to retrieve, calculate, display, group, sort, filter, parameterize, and format the data in a report. They start with equal sign (=).
Property, Context and Dialog Expression Box
Format data in a text box depending on value
Colour for a placeholder inside =IIF(Fields!TotalDue.Value < of a text box in the details row 10000,"Red","Black") for a Tablix
Dynamic page header or footer content.
Value for a placeholder inside of a text box that is placed in the page header or footer.
Specify page breaks for every 20 rows in a Group expression for a group Tablix with no other in a Tablix. groups.
Shows the user ID of the person running the Value report
To get first day of the month
To get the current date Value
To get last day of the month
="Page " & Globals!PageNumber & " of " & Globals!TotalPages
Sql Server interview - July 10, 2011 by Swati Parakh Difference between drill down and drill through report. Both the drill down and drill through report provide interactive functionality to the SSRS report. The differences are as follows:-
Data retrieved at the same time as main report
Data retrieved one click on link of drill through report
Is processed and rendered when
With the main report
When link is clicked
Slower since retrieves all data with main report
Faster (but does not retrieve all data with main report)
Within main report
Separately either in separate window or tab
What’s the use of custom fields in report? Custom fields can be defined as alias column of the report since the operation is performed on report server rather than on database server. The custom field is very useful for the data manipulation like adding some fields whose value can be calculated based on expression, text e.g. instead of CName fetched from database, I want the dataset to display Customer Name etc. We can add custom fields as right click on dataset, select add in Dataset window. The New field dialog box will open, we can add name of custom field and also mention whether it is database field or calculated one. If it is calculated, then we can mention the computation in this window.
Can we use custom code in SSRS? If so, explain how we can do. Yes, we can. SSRS allows developer to add custom code in your report. You can write the code directly into embedded VB.Net and call it using property expression or you can write a custom class library and refer it in report server. The advantage of first method is that it is simple and easy to use but disadvantage is that it is available for that report only. While the second method has advantage of being available for multiple reports but it has much of configuration overhead. To write custom code, right click on Report Designer outside report body and select Properties and go to Code tab and you can write custom code here. To add custom class library, right click on Report Designer outside report body and select Properties and go to Reference tab and add the reference by browsing to the assembly of your class library. Note that you need to create class library and then compile it before referencing it in your SSRS report.
Sql Server interview - July 16, 2011 by Swati Parakh Difference between report and query parameter. Why do we need different type of parameter? Query Parameter
Automatically if database query or stored procedure has a parameter
Automatically if report has some query parameter and is mapped to query
On Database Server
On Report Server
Filtering of Data, Security of Data
Manipulate data, interconnect reports, filtering data
Number of records presented is based on query. Note- Records processed on Number of records returned is based report parameter would be same as on query parameter records returned based on query parameter.
Filtering data based on them
Performance is good
Full set of records is retrieved then filtered. Hence, performance is low
How does your SSRS maintain security? Reporting services maintain role based security. When a user logs into reporting services, a Report Manager (whose duty is to maintain security of Reporting Services) first checks the identity of user and then determine what rights he have to perform on report. Report Manager manages the security at 2 levels – 1. System-level – Administer the report server globally 2. Item-level – Security at report and dataset level System-level roles are:1. System Administrator – can manage report server and report manager security 2. Site User - view basic information like report properties and schedules. Item-level roles – User can use any of predefined item-level roles or create their own roles by using combination of predefined item-level roles. Pre-defined Item-level roles are:1. Browser – can navigate to report and run them. 2. My Reports – these users‟ rights is restricted to reports present in their MyReports folder. However, they can create, view and manage reports in their folder. 3. Publisher – As name suggest, publisher user has rights to publish reports to Reporting Server database. 4. Content Manager – has all permission at item-level.
Test your sql server knowledge with our multiple choice questions! Next>> Part 1 | Part 2 | Part 3 | Part 4 | part 5 | part 6 | part 7 | part 8 | part 9
Write your comment - Share Knowledge and Experience Discussion Board
SQL Server interview questions and answers What is Lock Escalation? Lock escalation is the process of reducing the overhead of the system by converting many fine grain locks into
fewer coarse grain locks. Lock escalation threshold is determined dynamically by SQL server. It doesn‟t require any configuration hassles as SQL Server choose to keep lock on both row and column for the page query. What is RAID and what are different types of RAID levels? RAID stands for Redundant array of independent disks which was earlier called as Redundant array of inexpensive disks. It is a storage technology that has one logical unit consisting of multiple disk drive components. It increases the performance by replicating and dividing the data through many levels between multiple physical drives. There are 12 Raid Levels which are as follows: - Level 0: it is a 'striped' disk array (provides data stripping) without fault tolerance. - Level 1: It is used in system for “mirroring” and “duplexing” purpose. - Level 2: in this error correction takes place - Level 3: it provides byte level stripping also called as “bit-interleaved parity” - Level 4: is used as “dedicated parity drive” and it provides block level striping - Level 5: is “block interleaved distributed parity” - Level 6: is “independent data disks with double parity. - Level 0+1: is “a mirror of stripes” and used for replication and sharing of data among disks - Level 10: is “a stripe of mirrors”. Multiple mirrors are created and then stripes over it. - Level 7: It adds caching to Level 3 or 4. - Level 50: implemented as striped array with fault tolerance - RAID S: it is proprietary striped parity RAID system
Rohit Sharma 12-7-2011 07:06 AM SQL Server interview questions and answers What's the difference between a primary key and a unique key? - Primary key is a combination of columns which uniquely specify a row whereas a unique key is related to the superkey and can uniquely identify each row in the table. - Primary can only be one in each table as it is one of the special cases of the unique key whereas a unique key can be many. - Primary key enforces the NOT NULL constraint whereas unique key doesn‟t. Due to this values in the unique key columns may or may not be NULL. What is bit data type and what's the information that can be stored inside a bit column? - Bit data type is the smallest type used in a language. It is used to store the boolean information of the form 1 (true) or 0 (false). The former versions of SQL server doesn‟t support NULL type in this but recent version such as SQL server 7.0 onwards it supports NULL state as well. Define candidate key, alternate key, and composite key. - Candidate Key is a key which provides the uniqueness of the column(s). It identifies each row of a table as unique. It can become the primary key of the table as well. Every tabular relationship will have atleast one candidate key. - Alternate Key is a type of candidate key which is formed when there are more than one candidate key and one of them is a primary key then other keys will act as an alternate keys. Unique keys also termed as alternate keys which prevent incorrect data from entering the table. - Composite Key is a special type of candidate key as it is formed by combining two or more columns. This gives assurance of uniqueness of data when the columns are joined together. What are ACID properties? ACID is used in database and it includes the following properties such as atomicity, consistency, isolation and durability. These properties allow easy, reliable and secure database transaction. Example: Transfer of money from one bank account to another. It is used to manage the concurrency in the database table. What is the difference between Locking and multi-versioning? Locking is a means of not allowing any other transaction to take place when one is already in progress. In this the data is locked and there won‟t be any modification taking place till the transaction either gets successful or it fails. The lock has to be put up before the processing of the data whereas Multi-versioning is an alternate to locking to control the concurrency. It provides easy way to view and modify the data. It allows two users to view and read the data till the transaction is in progress.
Rohit Sharma 12-7-2011 07:06 AM SQL Server interview questions and answers What's the difference between a primary key and a unique key? - Primary key is a combination of columns which uniquely specify a row whereas a unique key is related to the superkey and can uniquely identify each row in the table. - Primary can only be one in each table as it is one of the special cases of the unique key whereas a unique key can be many. - Primary key enforces the NOT NULL constraint whereas unique key doesn‟t. Due to this values in the unique key columns may or may not be NULL. What is bit data type and what's the information that can be stored inside a bit column? - Bit data type is the smallest type used in a language. It is used to store the boolean information of the form 1 (true) or 0 (false). The former versions of SQL server doesn‟t support NULL type in this but recent version such as SQL server 7.0 onwards it supports NULL state as well.
Rohit Sharma 12-7-2011 07:05 AM SQL Server interview questions and answers What is normalization? Explain different forms of normalization? Normalization is a process of organizing the data to minimize the redundancy in the relational database management system (RDBMS). The use of normalization in database is to decompose the relations with anomalies to produce well structured and smaller relations. There are 6 forms of normalization which are as follows:- 1NF represents a relation with no repeating groups - 2NF represents no non-prime attribute in the table - 3NF defines that every non-prime attribute is non-transitively dependent on every candidate key - 4NF defines that every non-trival multi-valued dependency in table is dependent on superkey. - 5NF defines that every non-trival join dependency in table is implied by superkey in table. - 6NF defines that a table features no non-trival join dependency. What is de-normalization and what are some of the examples of it? De-normalization is used to optimize the readability and performance of the database by adding redundant data. It covers the inefficiencies in the relational database software. De-normalization logical data design tend to improve the query responses by creating rules in the database which are called as constraints. Examples include the following: - Materialized views for implementation purpose such as: - Storing the count of “many” objects in one-to-many relationship - Linking attribute of one relation with other relations - To improve the performance and scalability of web applications
Rohit Sharma 12-7-2011 07:04 AM SQL Server interview questions What are the different index configurations a table can have? No indexes A clustered index A clustered index and many nonclustered indexes A nonclustered index
Many nonclustered indexes
What is BCP? It is used to copy huge amount of data from tables and views. It does not copy the structures same as source to destination. Dheeraj 12-6-2011 01:38 AM