Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SQL Interview Questions

Fresher Interview Questions

Experience Interview Questions

Fresher Interview Questions

Experience Interview Questions

Fresher Interview Questions

Experience Interview Questions

Fresher Interview Questions

Experience Interview Questions

Fresher Interview Questions

Experience Interview Questions

Fresher Interview Questions

Experience Interview Questions

Fresher Interview Questions

Experience Interview Questions

Top 100+ SQL Interview Questions You Must Know in 2023

1. What is the difference between “Stored Procedure” and “Function”?

  1. A procedure can have both input and output parameters, but a function can only have input parameters.
  2. Inside a procedure we can use DML (INSERT/UPDATE/DELETE) statements. But inside a function we can’t use DML statements.
  3. We can’t utilize a Stored Procedure in a Select statement. But we can use a function in a Select statement.
  4. We can use a Try-Catch Block in a Stored Procedure but inside a function we can’t use a Try-Catch block.
  5. We can use transaction management in a procedure but we can’t in a function.
  6. We can’t join a Stored Procedure but we can join functions.
  7. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section. But we can use a function anywhere.
  8. A procedure can return 0 or n values (max 1024). But a function can return only 1 value that is mandatory.
  9. A procedure can’t be called from a function but we can call a function from a procedure.

2. What is difference between “Clustered Index” and “Non Clustered Index”?

  1. A Clustered Index physically stores the data of the table in the order of the keys values and the data is resorted every time whenever a new value is inserted or a value is updated in the column on which it is defined, whereas a non-clustered index creates a separate list of key values (or creates a table of pointers) that points towards the location of the data in the data pages.
  2. A Clustered Index requires no separate storage than the table storage. It forces the rows to be stored sorted on the index key whereas a non-clustered index requires separate storage than the table storage to store the index information.
  3. A table with a Clustered Index is called a Clustered Table. Its rows are stored in a BTree structure sorted whereas a table without any clustered indexes is called a nonclustered table. Its rows are stored in a heap structure unsorted.
  4. The default index is created as part of the primary key column as a Clustered Index.
  5. In a Clustered Index, the leaf node contains the actual data whereas in a nonclustered index, the leaf node contains the pointer to the data rows of the table.
  6. A Clustered Index always has an Index Id of 1 whereas non-clustered indexes have
    Index Ids > 1.
  7. A Table can have only 1 Clustered Index whereas prior to SQL Server 2008 only 249 non-clustered indexes can be created. With SQL Server 2008 and above 999 nonclustered indexes can be created.
  8. A Primary Key constraint creates a Clustered Index by default whereas A Unique Key constraint creates a non-clustered index by default.

3. What is the difference between the “DELETE” and “TRUNCATE” commands?

  1. The DELETE command is used to remove rows from a table based on a WHERE condition whereas TRUNCATE removes all rows from a table.
  2. So we can use a where clause with DELETE to filter and delete specific records whereas we cannot use a Where clause with TRUNCATE.
  3. DELETE is executed using a row lock, each row in the table is locked for deletion whereas TRUNCATE is executed using a table lock and the entire table is locked for removal of all records.
  4. DELETE is a DML command whereas TRUNCATE is a DDL command.
  5. DELETE retains the identity of the column value whereas in TRUNCATE, the Identify column is reset to its seed value if the table contains any identity column.
  6. To use Delete you need DELETE permission on the table whereas to use Truncate on a table you need at least ALTER permission on the table.
  7. DELETE uses more transaction space than the TRUNCATE statement whereas Truncate uses less transaction space than DELETE statement.
  8. DELETE can be used with indexed views whereas TRUNCATE cannot be used with indexed views.
  9. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row whereas TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
  10. Delete activates a trigger because the operation is logged individually whereas TRUNCATE TABLE can’t activate a trigger because the operation does not log individual row deletions.

4. What is the difference between the “WHERE” clause and the “HAVING” clause?

  1. WHERE clause can be used with a Select, Update and Delete Statement Clause but the HAVING clause can be used only with a Select statement.
  2. We can’t use an aggregate functions in the WHERE clause unless it is in a sub-query contained in a HAVING clause whereas we can use an aggregate function in the HAVING clause. We can use a column name in the HAVING clause but the column must be contained in the group by clause.
  3. WHERE is used before the GROUP BY clause whereas a HAVING clause is used to impose a condition on the GROUP Function and is used after the GROUP BY clause in the query.
  4. A WHERE clause applies to each and every row whereas a HAVING clause applies to summarized rows (summarized with GROUP BY).
  5. In the WHERE clause the data that is fetched from memory depending on a condition whereas in HAVING the completed data is first fetched and then separated depending on the condition.

5. What is the difference between “Primary Key” and “Unique Key”?

  1. We can have only one Primary Key in a table whereas we can have more than one Unique Key in a table.
  2. The Primary Key cannot have a NULL value whereas a Unique Key may have only one null value.
  3. By default, a Primary Key is a Clustered Index whereas by default, a Unique Key is a unique non-clustered index.
  4. A Primary Key supports an Auto Increment value whereas a Unique Key doesn’t support an Auto Increment value.

6. What is the difference between a “Local Temporary Table” and “Global Temporary Table”?

  1. A Local Temporary Table is created by giving it a prefix of # whereas a Global Temporary Table is created by giving it a prefix of ##.
  2. A Local Temporary Table cannot be shared among multiple users whereas a Global Temporary Table can be shared among multiple users.
  3. A Local Temporary Table is only available to the current DB connection for the current user and are cleared when the connection is closed whereas a Global Temporary Table is available to any connection once created. They are cleared when the last connection is closed.

7. What are super, primary, candidate and foreign keys?

A Super Key is a set of attributes of a relation schema upon which all attributes of the schema are functionally dependent. No two rows can have the same value of super key attributes.

A Candidate key is minimal super key, i.e., no proper subset of Candidate key attributes can be a super key.

A Primary Key is one of the candidate keys. One of the candidate keys is selected as most important and becomes the primary key. There cannot be more that one primary keys in a table.

Foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table.

8. What is the difference between primary key and unique constraints?

Primary key cannot have NULL value, the unique constraints can have NULL values. There is only one primary key in a table, but there can be multiple unique constrains.

9. What is database normalization?

It is a process of analyzing the given relation schemas based on their functional dependencies and primary keys to achieve the following desirable properties:

  1. Minimizing Redundancy
  2. Minimizing the Insertion, Deletion, And Update Anomalies
  3. Relation schemas that do not meet the properties are decomposed into smaller relation schemas that could meet desirable properties.

10. What is SQL?

SQL is Structured Query Language designed for inserting and modifying in a relational database management system.

11. What are the differences between DDL, DML and DCL in SQL?

Following are some details of three.

  • DDL stands for Data Definition Language. SQL queries like CREATE, ALTER, DROP and RENAME come under this.
  • DML stands for Data Manipulation Language. SQL queries like SELECT, INSERT and UPDATE come under this.
  • DCL stands for Data Control Language. SQL queries like GRANT and REVOKE come under this.

12. What is the difference between having and where clause?

HAVING is used to specify a condition for a group or an aggregate function used in select statement. The WHERE clause selects before grouping. The HAVING clause selects rows after grouping. Unlike HAVING clause, the WHERE clause cannot contain aggregate functions.

13.What is Join?

An SQL Join is used to combine data from two or more tables, based on a common field between them. For example, consider the following two tables.

Student Table

EnrollNo StudentName Address
1000 geek1 geeksquiz1
1001 geek2 geeksquiz2
1002 geek3 geeksquiz3

StudentCourse Table

CourseID EnrollNo
1 1000
2 1000
3 1000
1 1002
2 1003

Following is join query that shows names of students enrolled in different courseIDs.

SELECT StudentCourse.CourseID, Student.StudentName
FROM StudentCourse
INNER JOIN Customers
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID;

The above query would produce following result.

CourseID StudentName
1 geek1
1 geek2
2 geek1
2 geek3
3 geek1

14. What is Identity?

Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers; the value of this cannot be controlled. Identity/GUID columns do not need to be indexed.

15. What is a view in SQL? How to create one

A view is a virtual table based on the result-set of an SQL statement. We can create using create view syntax.

CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

16. What are the uses of view?

  • Views can represent a subset of the data contained in a table; consequently, a view can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table.
  • Views can join and simplify multiple tables into a single virtual table
  • Views can act as aggregated tables, where the database engine aggregates data (sum, average etc.) and presents the calculated results as part of the data
  • Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table.
  • Depending on the SQL engine used, views can provide extra security.

17. What is a Trigger?

A Trigger is a code that associated with insert, update or delete operations. The code is executed automatically whenever the associated query is executed on a table. Triggers can be useful to maintain integrity in database.

18. What is a stored procedure?

A stored procedure is like a function that contains a set of operations compiled together. It contains a set of operations that are commonly used in an application to do some common database tasks.

19. What is the difference between Trigger and Stored Procedure?

Unlike Stored Procedures, Triggers cannot be called directly. They can only be associated with queries.

20. What is a transaction? What are ACID properties?

A Database Transaction is a set of database operations that must be treated as whole, means either all operations are executed or none of them. An example can be bank transaction from one account to another account. Either both debit and credit operations must be executed or none of them. ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably.

21.What are indexes?

A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Data can be stored only in one order on disk. To support faster access according to different values, faster search like binary search for different values is desired, For this purpose, indexes are created on tables. These indexes need extra space on disk, but they allow faster search according to different frequently searched values.

22. What are clustered and non-clustered Indexes?

Clustered indexes is the index according to which data is physically stored on disk. Therefore, only one clustered index can be created on a given database table. Non-clustered indexes don’t define physical ordering of data, but logical ordering. Typically, a tree is created whose leaf point to disk records. B-Tree or B+ tree are used for this purpose.

23.What are Primary Keys and Foreign Keys?

Primary keys are the unique identifiers for each row. They must contain unique values and cannot be null. Due to their importance in relational databases, Primary keys are the most fundamental aspect of all keys and constraints. A table can have only one primary key. Foreign keys are a method of ensuring data integrity and manifestation of the relationship between tables.

24.What is SQL ?

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

25. What are the different type of SQL or different commands in SQL?

    Frequently asked SQL Interview Questions
  1. DDL – Data Definition Language.DDL is used to define the structure that holds the data.
  2. DML – Data Manipulation Language DML is used for manipulation of the data itself. Typical operations are Insert, Delete,Update and retrieving the data from the table
  3. DCL – DataControlLanguage DCL is used to control the visibility of data like granting database access and set privileges to create table etc.
  4. TCL – TransactionControl Language It contains

26. What are the Advantages of SQL?

  1. SQL is not a proprietary language used by specific database vendors. Almost every major DBMS supports SQL, so learning this one language will enable programmer to interact with any database like ORACLE, SQL ,MYSQL etc.
  2. SQL is easy to learn. The statements are all made up of descriptive English words, and there aren’t that many of them.
  3. SQL is actually a very powerful language and by using its language elements you can perform very complex and sophisticated database operations.

27. what is a field in a database ?

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

Employee Name , Employee ID etc

28.What is a Record in a database ?

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

29. What is a Table in a database ?

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

30.What is a database transaction?

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

31.What are properties of a transaction?

    Properties of the transaction can be summarized as ACID Properties.
  1. Atomicity: A transaction consists of many steps. When all the steps in a transaction gets completed, it will get reflected in DB or if any step fails, all the transactions are rolled back.
  2. Consistency: The database will move from one consistent state to another, if the transaction succeeds and remain in the original state, if the transaction fails.
  3. Isolation: Every transaction should operate as if it is the only transaction in the system
  4. Durability: Once a transaction has completed successfully, the updated rows/records must be available for all other transactions on a permanent basis

32.What is a Database Lock ?

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

33. What are the type of locks ?

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

34. What are the different type of normalization?

Frequently asked SQL Interview Questions

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

  1. First Normal Form (1NF) A relation is said to be in first normal form if and only if all underlying domains contain atomic values only. After 1NF, we can still have redundant data
  2. Second Normal Form (2NF) A relation is said to be in 2NF if and only if it is in 1NF and every non key attribute is fully dependent on the primary key. After 2NF, we can still have redundant data
  3. Third Normal Form (3NF) A relation is said to be in 3NF, if and only if it is in 2NF and every non key attribute is nontransitively dependent on the primary key

35.What is a primary key?

Frequently asked SQL Interview Questions

A primary key is a column whose values uniquely identify every row in a table. Primary key values can never be reused. If a row is deleted from the table, its primary key may not be assigned to any new rows in the future. To define a field as primary key, following conditions had to be met :

  1. No two rows can have the same primary key value.
  2. Every row must have a primary key value
  3. Primary key field cannot be null
  4. Values in primary key columns can never be modified or updated

36.What is a Composite Key ?

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

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

37.What is a Composite Primary Key ?

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

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

38.What is a Foreign Key ?

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

39. What is a Unique Key ?

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

40.Define SQL Insert Statement ?

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

  1. To insert a single complete row
  2. To insert a single partial row

41. Define SQL Update Statement ?

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

42. Define SQL Delete Statement ?

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

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

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

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

44. Define Join and explain different type of joins?

In order to avoid data duplication, data is stored in related tables . Join keyword is used to fetch data from related table. Join return rows when there is at least one match in both tables . Type of joins are

Right Join Return all rows from the right table, even if there are no matches in the left table .
Outer Join

Left Join Return all rows from the left table, even if there are no matches in the right table .

Full Join Return rows when there is a match in one of the tables.

45.What is Self-Join?

Self-join is query used to join a table to itself. Aliases should be used for the same table comparison.

46. What is Cross Join?

Cross Join will return all records where each row from the first table is combined with each row from the second table. SQL Interview Questions and answers on Database Views

47. What is a view?

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

48. What is a materialized view?

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

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

Advantages:

  1. Views doesn’t store data in a physical location.
  2. View can be use to hide some of the columns from the table
  3. Views can provide Access Restriction, since data insertion, update and deletion is not possible on the view.

Disadvantages:

  1. When a table is dropped, associated view become irrelevant.
  2. Since view are created when a query requesting data from view is triggered, its bit slow
  3. When views are created for large tables, it occupy more memory. SQL Interview Questions and answers on Stored Procedures and Triggers

50. What is a stored procedure?

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

51.What are the advantages a stored procedure?

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

52.What is a trigger?

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

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

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

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

A clustered index reorders the way records in the table are physically stored. There can be only one clustered index per table. It make data retrieval faster. A non clustered index does not alter the way it was stored but creates a complete separate object within the table. As a result insert and update command will be faster.

55. What is Union, minus and Interact commands?

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

56.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 doesn’t allow NULLs, but unique key allows one NULL only.

57. What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base Sql Server datatypes 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 datatype called Flight_num_type of varchar(8) and use it across all your tables.

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

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

59. What is bit datatype and what’s the information that can be stored inside a bit column?

Bit datatype is used to store boolean information like 1 or 0 (true or false). Until SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

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

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

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

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

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

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

65.What’s the maximum size of a row?

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

66. Explain Active/Active and Active/Passive cluster configurations

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

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

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

69.What is 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 de-allocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.

70. Explain the storage models of OLAP

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

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

72. 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”

73. 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 createe 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.

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

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

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

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

77. 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 live lock 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 live lock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

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

79. Explain CREATE DATABASE syntax

Many of us are used to creating databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE 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.

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

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

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

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

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

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

84. 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 Server 7.0+ are Full database backup, differential database backup, transaction log backup, file group backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.

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

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

  • Snapshot replication
  • Transactional replication (with immediate updating subscribers, with queued updating subscribers)
  • Merge replication

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

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

Cursors allow row-by-row processing of the result sets.

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

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

Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria:

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

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

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

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

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

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

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

89. What is a join and explain different types of joins

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs,OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.



This post first appeared on Best Data Science Online Training In India, please read the originial post: here

Share the post

SQL Interview Questions

×

Subscribe to Best Data Science Online Training In India

Get updates delivered right to your inbox!

Thank you for your subscription

×