SQL Server Interview Questions and Answers
In this article, I am going to discuss the most frequently asked basic SQL Server Interview Questions and Answers. As part of this article, we are going to discuss the following SQL Server Interview Questions with answers.
- What is RDBMS?
- Explain DML, DDL, DCL and TCL statements with examples?
- What is the difference between Drop, Delete and Truncate statements in SQL Server?
- What is Cascading referential integrity constraint?
- Explain the difference between where clause and having clause in SQL Server
- What are the differences between primary key and unique key in SQL Server?
- How can we copy the data from one table to another?
- How to create a new table from an existing table or in how many ways we can create a new table from an existing table?
- What is normalization?
- What are the different normalization forms?
- What is the Cursor?
- What is the use of DBCC commands?
- What is a Linked Server?
- What is Collation?
- What are different types of Collation Sensitivity?
- How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
- What is a NOLOCK?
- What is the use of UPDATE_STATISTICS command?
- What is sub-query? Explain the properties of sub-query.
- What is the SQL Profiler?
- What are the authentication modes in SQL Server? How can it be changed?
- What is SQL server agent?
- What is log shipping?
- What is sp_configure commands and set commands?
- What are the different types of replication?
- What does it mean to have quoted_identifier on?
- What are the implications of having it off?
- What is the STUFF function and how does it differ from the REPLACE function?
- How to rebuild Master Database?
- What are the basic functions for master, msdb, model, tempdb databases?
- What is De-normalization?
- What is a Scheduled Jobs or What is a Scheduled Tasks?
- What is BCP? When does it used?
- How do you load large data to the SQL server database?
- Can we rewrite subqueries into simple select statements or with joins?
- Can SQL Servers linked to other servers like Oracle?
- How to copy the tables, schema and views from one SQL server to another?
- What is DataWarehousing?
- What is OLTP (OnLine Transaction Processing)?
What is RDBMS?
Relational Database Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers.
This allows for a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.
Explain DML, DDL, DCL and TCL statements with examples?
DML stands for Data Manipulation Language. DML is used to retrieve, insert, update and delete data in a database that means DML statements affect records in a table. These are basic operations we perform on data such as selecting a few records from a table, inserting new records, deleting unnecessary records, and updating/modifying existing records. DML statements include the following:
SELECT – select records from a table
INSERT – insert new records
UPDATE – update/Modify existing records
DELETE – delete existing records
DDL stands for Data Definition Language. DDL statements are used to alter/modify a database or table structure and schema. These statements handle the design and storage of database objects.
CREATE – create a new Table, database, schema
ALTER – alter the existing table, column description
DROP – delete existing objects from a database
DCL stands for data control language. Generally, we will use these commands to secure database objects by creating roles, permissions using GRANT, REVOKE operations. In SQL Server, the following operations will come under DCL operations
GRANT – allows users to read/write on certain database objects
REVOKE – keeps users from the read/write permission on database objects
TCL stands for Transactional Control Language. TCL is used to manage transactions within a database. Examples: COMMIT, ROLLBACK, Begin Transaction statements
BEGIN Transaction – opens a transaction
COMMIT Transaction – commits a transaction
ROLLBACK Transaction – ROLLBACK a transaction in case of any error
What is the difference between Drop, Delete and Truncate statements in SQL Server?
This is one of the frequently asked SQL Server Interview Questions. The Drop, Delete and Truncate – All operations can be rolled back.
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.
All the statements (Delete, Truncate and Drop) are logged operations but the amount of information that is logged varies. Delete statement logs an entry in the transaction log for each deleted row, whereas Truncate Table logs only the Page deallocations. Hence, truncate is a little faster than Delete.
- The DELETE command is used to remove some or all rows from a table.
- A WHERE clause can be used with a DELETE command to remove some specific rows from a table.
- If the WHERE condition is not specified, then all rows are removed.
- The DELETE operation will cause all DELETE triggers on the table to fire.
- It does not reset the identity of the column value.
- It removes rows on the row-by-row basis and hence for each deleted row it records an entry in the transaction logs, thus this is slower than truncate.
- This is a DML command so it is just used to manipulate or modify the table data and it does not change any property of a table.
- TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain.
- It does not require a WHERE clause, so we cannot filter rows while Truncating.
- IDENTITY columns are re-seeded on this operation if no seed was defined then the default value 1 is used.
- No Triggers are fired on this operation because it does not operate on individual rows.
- TRUNCATE removes the data by deallocating the data pages used to store the table’s data instead of rows and records, and only the page deallocations are recorded in the transaction log thus it is faster than delete.
- We cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
- TRUNCATE is DDL Command
- The DROP command removes a table from the database.
- All the related Data, Indexes, Triggers, Constraints, and Permission specifications for the Table are dropped by this operation.
- Some objects like Views, Stored Procedures that reference the dropped table are not dropped and must be explicitly dropped.
- Cannot drop a table that is referenced by any Foreign Key constraint.
- No Triggers are fired on this operation because it does not operate on individual rows.
Note: If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if the session is closed, it cannot be rolled back but DELETE can be rolled back.
What is Cascading referential integrity constraint?
Cascading referential integrity constraints are foreign key constraints that tell SQL Server to perform certain actions when a user attempts to delete or update a primary key to which an existing foreign keys point.
SET NULL: If a delete or update statement affects rows in a foreign key table, those values will be set to NULL when the primary key record is deleted or updated. The foreign key columns affected must allow NULL values.
CASCADE: If a delete statement affects one or more rows in a foreign key table, those rows will be deleted when the primary key record is deleted. If an update statement affects rows in the foreign key table, those rows will be updated with the value from the primary key record after it has been updated.
SET DEFAULT: If a delete or update statement affects rows in a foreign key table, then all rows containing those foreign keys are set to the default value. All foreign key columns in the related table must have default constraints defined on them.
NO ACTION: This is the default action. This specifies that if an update or deletes statement affects rows in foreign key tables, then the action will be denied and rolled back. An error message will be raised.
What is the difference between where clause and having clause in SQL Server?
This is one of the most frequently asked SQL Server Interview Questions and in almost all interviews this question being asked.
- WHERE clause cannot be used with aggregate functions whereas the HAVING clause can be used with aggregate functions. This means WHERE clause is used for filtering individual rows on a table whereas the HAVING clause is used to filter groups.
- WHERE comes before GROUP BY. This means WHERE clause filters rows before aggregate calculations are performed. HAVING comes after GROUP BY. This means HAVING clause filters rows after aggregate calculations are performed. So, from a performance standpoint, HAVING is slower than WHERE and should be avoided when possible.
- WHERE and HAVING clause can be used together in a SELECT query. In this case WHERE clause is applied first to filter individual rows. The rows are then grouped and aggregate calculations are performed, and then the HAVING clause filters the groups.
- WHERE clause can be used with – Select, Insert, and Update statements whereas the HAVING clause can only be used with the Select statement.
What are the differences between primary key and unique key in SQL Server?
This is of the most asked SQL Server Interview Questions in Interviews. Let discuss this question in detail.
- A table can have only one primary key. On the other hand, a table can have more than one unique key.
- The primary key column does not accept any null values whereas a unique key column accepts one null value.
- Both Primary key and unique key enforce the uniqueness of the column on which they are defined. But By default, the primary key creates a unique clustered index on the column whereas a unique key creates a unique non clustered index.
How can we copy the data from one table to another?
When we copy the data from one table to another table then the two tables should contain the same structure.
When we copy the data from one table to another table we use insert and select query. Tables always independent objects that mean a table does not depend on other tables
How to create a new table from an existing table or in how many ways we can create a new table from an existing table?
If required we can create a new table from an existing table as below.
Syntax1: (with all column from an existing table)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT * INTO NEWEMPLOYEE FROM EMPLOYEE
When we execute the above query it will create a new table with all records from an existing table.
Syntax2: (with specific columns from an existing table)
SELECT <REQUIREDCOLUMN> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT EID, SALARY INTO SPECEMP FROM EMPLOYEE
When we execute the above query it will create a new table with the specific column data from an existing table.
Syntax3: (creating a new table without data)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME> WHERE 1 = 0
Example: SELECT * INTO DUMMYEMP FROM EMPLOYEE WHERE 1 = 0
SELECT <REQUIRED COLUMNS> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
SELECT EID, SALARY INTO TAB1 FROM EMPLOYEE WHERE 1 = 0
When we execute the above query it will create a new table without records from an existing table.
What is normalization?
Database normalization is a data design and organization processes applied to data structures based on rules that help build relational databases. In relational database design the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.
What are the different normalization forms?
This is one of the frequently asked SQL Server Interview Questions.
1NF: Eliminate Repeating Groups: Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data: If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key: If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key
BCNF: Boyce-Codd Normal Form: If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships: No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships: There may be practical constraints on information that justify separating logically related many-to-many relationships.
ONF: Optimal Normal Form: A model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF: Domain-Key Normal Form: A model free from all modification anomalies.
Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first full-fill all the criteria of a 2NF and 1NF database. Please click here to learn Database Normalization in detail step by step with some real time examples.
What is the Cursor?
A cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.
In order to work with a cursor we need to perform some steps in the following order:
- Declare cursor
- Open cursor
- Fetch row from the cursor Process fetched row Close cursor
- Deallocate cursor
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. For example,
- DBCC CHECKDB – Ensures that tables in the DB and the indexes are correctly linked.
- DBCC CHECKALLOC – To check that all pages in a DB are correctly allocated.
- DBCC CHECKFILEGROUP – Checks all tables file group for any damage.
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. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Stored Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.
What is Collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types and character width.
What are different types of Collation Sensitivity?
- Case sensitivity: A and a, B and b, etc.
- Accent sensitivity: a and á, o and ó, etc.
- Kana Sensitivity: When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.
- Width sensitivity: When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive.
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
The one-to-one relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.
What 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) locks. 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 the delay(blocking).
When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a large number of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
What is sub-query? Explain the properties of sub-query.
This is one of the frequently asked SQL Server Interview Questions. Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword.
A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a result set. Meaning a subquery SELECT statement can stand alone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically, a subquery can be used anywhere an expression can be used.
Properties of Sub-Query
- A subquery must be enclosed in the parenthesis.
- The subquery must be put in the right hand of the comparison operator, and
- subquery cannot contain an ORDER-BY clause.
- A query can contain more than one sub-queries.
What are the types of sub-queries?
- Single-row subquery, where the subquery returns only one row.
- Multiple-row subquery, where the subquery returns multiple rows,.and
- Multiple column subquery, where the subquery returns multiple columns.
What is the SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performance by executing too slowly.
Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large, especially when the monitoring process takes place over a long period of time.
Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties –> Port number.both on client and the server.
What are the authentication modes in SQL Server? How can it be changed?
Windows mode and mixed mode (SQL & Windows). To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page.
Where are SQL server users names and passwords are stored in sql server?
They get stored in master db in the sysxlogins table.
Which command using Query Analyzer will give you the version of SQL server and operating system?
SELECT SERVERPROPERTY(‘productversion’), SERVERPROPERTY (‘productlevel’), SERVERPROPERTY (‘edition’)
What is SQL server agent?
This is one of the frequently asked SQL Server Interview Questions. SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts.
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 transnational 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 can be used this as the Disaster Recovery plan. The key feature of log shipping is that is will automatically backup transaction logs throughout the day and automatically restore them on the standby server at a defined interval.
What command do we use to rename a db?
sp_renamedb ‘oldname’ , ‘newname’
If someone is using db it will not accept sp_renmaedb. In that case first, bring db to the single user using sp_dboptions. Use sp_renamedb to rename the database. Use sp_dboptions to bring the database to multi user mode.
What is sp_configure commands and set commands?
Use sp_configure to display or change server-level settings. To change database-level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.
What are the different types of replication? Explain.
The SQL Server 2000-supported replication types are as follows:
Snapshot replication distributes data exactly as it appears at a specific moment in time and does not monitor for updates to the data. Snapshot replication is best used as a method for replicating data that changes infrequently or where the most up-to-date values (low latency) are not a requirement. When synchronization occurs, the entire snapshot is generated and sent to Subscribers.
Transactional replication, an initial snapshot of data is applied at Subscribers, and then when data modifications are made at the Publisher, the individual transactions are captured and propagated to Subscribers.
Merge replication is the process of distributing data from Publisher to Subscribers, allowing the Publisher and Subscribers to make updates while connected or disconnected, and then merging the updates between sites when they are connected.
What are the OS services that the SQL Server installation adds?
MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)
What are three SQL keywords used to change or set someone’s permissions?
GRANT, DENY, and REVOKE.
What does it mean to have quoted_identifier on? What are the implications of having it off?
When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers.
What is the STUFF function and how does it differ from the REPLACE function?
STUFF function to overwrite existing characters. Using this syntax, STUFF(string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string.
REPLACE function to replace existing characters of all occurance. Using this syntax REPLACE(string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string.
Using query analyzer, name 3 ways to get an accurate count of the number of records in a table?
SELECT * FROM table1 SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2
How to rebuild Master Database?
Shutdown Microsoft SQL Server 2000, and then run Rebuildm.exe. This is located in the Program Files\Microsoft SQL Server\80\Tools\Binn directory.
In the Rebuild Master dialog box, click Browse. In the Browse for Folder dialog box, select the \Data folder on the SQL Server 2000 compact disc or in the shared network directory from which SQL Server 2000 was installed, and then click OK.
Click Settings. In the Collation Settings dialog box, verify or change settings used for the master database and all other databases.
Initially, the default collation settings are shown, but these may not match the collation selected during setup. You can select the same settings used during setup or select new collation settings. When done, click OK.
In the Rebuild Master dialog box, click Rebuild to start the process. The Rebuild Master utility reinstalls the master database. To continue, you may need to stop a server that is running.
What are the basic functions for master, msdb, model, tempdb databases?
This is one of the frequently asked SQL Server Interview Questions. 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.
What is De-normalization?
De-normalization is the process of attempting to optimise the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalised database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalisation is a technique to move from higher to lower normal forms of database modeling in order to speed up database access.
What is a Scheduled Jobs or What is a Scheduled Tasks?
This is one of the frequently asked SQL Server Interview Questions. Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule administrative tasks, such as cube processing, to run during times of slow business activity. User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. Back up the database, Update Stats of Tables. Job steps give the user control over the flow of execution.
If one job fails, the user can configure SQL Server Agent to continue to run the remaining tasks or to stop the execution.
What is BCP? When does it used?
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures same as source to destination.
How do you load large data to the SQL server database?
BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to Imports a data file into a database table or view in a user-specified format.
Can we rewrite subqueries into simple select statements or with joins?
Subqueries can often be re-written to use a standard outer join, resulting in faster performance. As we may know, an outer join uses the plus sign (+) operator to tell the database to return all non-matching rows with NULL values. Hence we combine the outer join with a NULL test in the WHERE clause to reproduce the result set without using a sub-query.
Can SQL Servers linked to other servers like Oracle?
SQL Server can be lined to any server provided it has OLE-DB provider from Microsoft to allow a link. E.g. Oracle has a OLE-DB provider for oracle that Microsoft provides to add it as a linked server to SQL Server group.
How to copy the tables, schema and views from one SQL server to another?
Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets user extract, transform, and consolidate data from disparate sources into single or multiple destinations.
What is DataWarehousing?
Subject-oriented, meaning that the data in the database is organised so that all the data elements relating to the same real-world event or object are linked together;
Time-variant, meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes over time;
Non-volatile, meaning that data in the database is never over-written or deleted, once committed, the data is static, read-only, but retained for future reporting;
Integrated, meaning that the database contains data from most or all of an organisation’s operational applications, and that this data is made consistent.
What is OLTP (OnLine Transaction Processing)?
In OLTP – online transaction processing systems relational database design use the discipline of data modelling and generally follow the Codd rules of data normalization in order to ensure absolute data integrity. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules.
In the next article, I am going to discuss the most frequently asked SQL Server Temporary Tables Interview Questions with answers. Here, in this article, I try to explain most frequently asked basic SQL Server Interview Questions and Answers. I hope you enjoy this SQL Server Interview Questions and Answers article. I would like to have your feedback. Please post your feedback, question, or comments about this SQL Server Interview Questions and Answers article.