Cloud Network

Networking | Support | Tricks | Troubleshoot | Tips

Buymecoffe

Buy Me A Coffee
Showing posts with label Interview Questions and Answers. Show all posts
Showing posts with label Interview Questions and Answers. Show all posts

Thursday, December 26, 2019

SQL Server Interview Questions and Answers

December 26, 2019
SQL Server Interview Questions and Answers


Q :- What are the difference between clustered and a non-clustered index?
Ans :- 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 non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

Q :What are the different index configurations a table can have?
Ans :- A table can have one of the following index configurations:
No indexes
A clustered index
A clustered index and many nonclustered indexes
A nonclustered index
Many nonclustered indexes

Q :- What are different types of Collation Sensitivity?
Ans :- Case sensitivity - A and a, B and b, etc.
Accent sensitivity
Kana Sensitivity - When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.
Width sensitivity - A single-byte character (half-width) and the same character represented as a double-byte character (full-width) are treated differently than it is width sensitive.

Q :- What is OLTP (Online Transaction Processing)?
Ans :- In OLTP - online transaction processing systems relational database design use the discipline of data modeling 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.

Q :- What is difference between DELETE and TRUNCATE commands?
Ans :- 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.

TRUNCATE: TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
TRUNCATE 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 removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE cannot be rolled back.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table

DELETE: ne at a time and records an entry in the transaction log for each deleted row.
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.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE can be rolled back.
DELETE is DML Command.
DELETE does not reset identity of the table.

Note: DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION if the current session is not closed. If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if session is closed, it can not be rolled back but DELETE can be rolled back.

Q :- What's the difference between a primary key and a unique key?
Ans :- Both primary key and unique key enforces 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.

Q :- When is the use of UPDATE_STATISTICS command?
Ans :- This command is basically used when a large processing of data has occurred. If a large amount 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.

Q :- What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Ans :- They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

Q :- What are the properties and different Types of Sub-Queries?
Properties of Sub-Query
Ans :- A sub-query must be enclosed in the parenthesis.
A sub-query must be put in the right hand of the comparison operator, and
A sub-query cannot contain an ORDER-BY clause.
A query can contain more than one sub-query.



Types of Sub-Query
Single-row sub-query, where the sub-query returns only one row.
Multiple-row sub-query, where the sub-query returns multiple rows,. and
Multiple column sub-query, where the sub-query returns multiple columns

Q :- What are the authentication modes in SQL Server? How can it be changed?
Ans :- Windows mode and Mixed Mode - SQL and 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.

Q :- What is SQL Profiler?
Ans :- 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 performances 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.

Q :- Which command using Query Analyzer will give you the version of SQL server and operating system?
Ans :- SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition').

Q :- What is SQL Server Agent?
Ans :- 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.

Q :- Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible?
Ans :- 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.

Q :- What is Log Shipping?
Ans :- 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.

Q :- Name 3 ways to get an accurate count of the number of records in a table?
Ans :- SELECT * FROM table1
SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

Q :- What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of having it OFF?
Ans :- 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.

Q :- What is the difference between a Local and a Global temporary table?
Ans :- 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.

Q :- What is the STUFF function and how does it differ from the REPLACE function?
Ans :- STUFF function is used 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 occurrences.

Using the 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.

Q :- What is PRIMARY KEY?
Ans :- A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

Q :- What is UNIQUE KEY constraint?
Ans :- A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

Q :- What is FOREIGN KEY?
Ans :- A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

Q :- What is CHECK Constraint?
Ans :- A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.


Q :- What is NOT NULL Constraint?
Ans :- A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.

Q :- How to get @@ERROR and @@ROWCOUNT at the same time?
Ans :- If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. And if @@Recordcount is checked before the error-checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable.
SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

Q :- What is a Scheduled Jobs or What is a Scheduled Tasks?
Ans :- 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 database, Update Stats of Tables.
Job steps give user control over flow of execution. If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution.

Q :- What are the advantages of using Stored Procedures?
Ans :- Stored procedure can reduced network traffic and latency, boosting application performance.
Stored procedure execution plans can be reused, staying cached in SQL Server's memory, reducing server overhead.
Stored procedures help promote code reuse.
Stored procedures can encapsulate logic.
You can change stored procedure code without affecting clients.
Stored procedures provide better security to your data.

Q :- What is a table called, if it has neither Cluster nor Non-cluster Index? What is it used for?
Ans :- Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A heap is a table that does not have a clustered index and, therefore, the pages are not linked by pointers. The IAM pages are the only structures that link the pages in a table together.
Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table and then do bulk of inserts and to restore those indexes after that.

Q :- Can SQL Servers linked to other servers like Oracle?
Ans :- SQL Server can be linked to any server provided it has OLE-DB provider from Microsoft to allow a link. E.g. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group.

Q :- What is BCP? When does it used?
Ans :- 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. BULK INSERT command helps to import a data file into a database table or view in a user-specified format.

Q :- How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
Ans :- 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.

Q :- What is an execution plan? When would you use it? How would you view the execution plan?
Ans :- An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad- hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.

Q :- Which TCP/IP port does SQL Server run on? How can it be changed?
Ans :- SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties.

Q :- What are the two authentication modes in SQL Server?
Ans :- There are two authentication modes –
Windows Mode
Mixed Mode
Modes can be changed by selecting the tools menu of SQL Server configuration properties and choose security page.

Q : What Is SQL Profiler?
Ans :- SQL Profiler is a tool which allows system administrator to monitor events in the SQL server.  This is mainly used to capture and save data about each event of a file or a table for analysis.

Q :- What is CHECK constraint?
Ans :- A CHECK constraint can be applied to a column in a table to limit the values that can be placed in a column. Check constraint is to enforce integrity.

Q :- Can SQL servers linked to other servers?
Ans :- SQL server can be connected to any database which has OLE-DB provider to give a link. Example: Oracle has OLE-DB provider which has link to connect with the SQL server group.

 Q :-  What is sub query and its properties?
Ans :- A sub-query is a query which can be nested inside a main query like Select, Update, Insert or Delete statements. This can be used when expression is allowed. Properties of sub query can be defined as
-A sub query should not have order by clause
-A sub query should be placed in the right hand side of the comparison operator of the main query
-A sub query should be enclosed in parenthesis because it needs to be executed first before the main query
-More than one sub query can be included.

Q :- What are the types of sub query?
Ans :- There are three types of sub query –
-Single row sub query which returns only one row
-Multiple row sub query which returns multiple rows
-Multiple column sub query which returns multiple columns to the main query. With that sub -query result, Main query will be executed.

Q :- What is SQL server agent?
Ans :- The SQL Server agent plays  a vital role in day to day tasks of SQL server administrator(DBA). Server agent’s purpose is to implement the tasks easily with the scheduler engine which allows our jobs to run at scheduled date and time.

Q :- What are scheduled tasks in SQL Server?
Ans :- Scheduled tasks or jobs are used to automate processes that can be run on a scheduled time at a regular interval. This scheduling of tasks helps to reduce human intervention during night time and feed can be done at a particular time. User can also order the tasks in which it has to be generated.

Q :- What is COALESCE in SQL Server?
Ans :- COALESCE is used to return first non-null expression within the arguments. This function is used to return a non-null from more than one column in the arguments.
 
Q :- How exceptions can be handled in SQL Server Programming?
Ans :- Exceptions are handled using TRY—-CATCH constructs and it is handles by writing scripts inside the TRY block and error handling in the CATCH block.

Q :-   What is the purpose of FLOOR function?
Ans :- FLOOR function is used to round up a non-integer value to the previous least integer

Q :-   Can we check locks in database? If so, how can we do this lock check?
Ans :- Yes, we can check locks in the database. It can be achieved by using in-built stored procedure called sp_lock.

Q :-   What is the use of SIGN function?
Ans :- SIGN function is used to determine whether the number specified is Positive, Negative and Zero. This will return +1,-1 or 0.

Q :-    What is a Trigger?
Ans :- Triggers are used to execute a batch of SQL code when insert or update or delete commands are executed against a table. Triggers are automatically triggered or executed when the data is modified. It can be executed automatically on insert, delete and update operations.




Q :- What are the types of Triggers?
Ans :- There are four types of triggers and they are:
Insert
Delete
Update
Instead of

Q :-    What is an IDENTITY column in insert statements?
Ans :- IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate key.

Q :- What is Bulkcopy in SQL?
Ans :- Bulkcopy is a tool used to copy large amount of data from Tables. This tool is used to load large amount of data in SQL Server.

Q :- What will be query used to get the list of triggers in a database?
Ans :- Query to get the list of triggers in database-

Q :- What is the difference between UNION and UNION ALL?
Ans :- UNION statement is mainly used to combine the tables including the duplicate rows and UNION ALL combine but does not look for duplicate rows. With this, UNION ALL will be very faster than UNION statements.

Q :-   How Global temporary tables are represented and its scope?
Ans :- Global temporary tables are represented with ## before the table name. Scope will be the outside the session whereas local temporary tables are inside the session. Session ID can be found using @@SPID.

Q :- What are the differences between Stored Procedure and the dynamic SQL?
Ans :- Stored Procedure is a set of statements which is stored in a compiled form. Dynamic SQL is a set of statements that dynamically constructed at runtime and it will not be stored in a Database and it simply execute during run time.

Q :- What is Collation?
Ans :- Collation is defined to specify the sort order in a table. There are three types of sort order –
Case sensitive
Case Insensitive
Binary

Q :- What is UPDATE_STATISTICS command?
Ans :- UPDATE_STATISTICS command is used to update the indexes on the tables when there is a large amount of deletions or modifications or bulk copy occurred in indexes.

Q :-   What is the use of SET NOCOUNT ON/OFF statement?
Ans :- By default, NOCOUNT is set to OFF and it returns number of records got affected whenever the command is getting executed. If the user doesn’t want to display the number of records affected, it can be explicitly set to ON- (SET NOCOUNT ON).

Q :- Which SQL server table is used to hold the stored procedure scripts?
Ans :- Sys.SQL_Modules is a SQL Server table used to store the script of stored procedure. Name of the stored procedure is saved in the table called Sys.Procedure.

Q :- What are Magic Tables in SQL Server?
Ans :- Insert and Delete tables are created when the trigger is fired for any DML command. Those tables are called Magic Tables in SQL Server. These magic tables are used inside the triggers for data transaction.

Q :- What is the difference between SUBSTR and INSTR in the SQL Server?
Ans :- The SUBSTR function is used to return specific portion of string in a given string. But, INSTR function gives character position in a given specified string.

Q :-  What is the use of =,==,=== operators?
Ans = is used to assign one value or variable to another variable. == is used for comparing two strings or numbers. === is used to compare only string with the string and number with numbers.

Q :-    What is ISNULL() operator?
Ans ISNULL function is used to check whether value given is NULL or not NULL in sql server. This function also provides to replace a value with the NULL.

Q :-     What is the use of FOR Clause?
Ans FOR clause is mainly used for XML and browser options. This clause is mainly used to display the query results in XML format or in browser.

Q :-  What will be the maximum number of index per table?
Ans 100 Index can be used as maximum number per table. 1 Clustered Index and 999 Non-clustered indexes per table can be used in SQL Server.

Q :- What is the difference between COMMIT and ROLLBACK?
Ans Every statement between BEGIN and COMMIT becomes persistent to database when the COMMIT is executed. Every statement between BEGIN and ROOLBACK are reverted to the state when the ROLLBACK was executed.

Q :-   What is the difference between varchar and nvarchar types?
Ans Varchar and nvarchar are same but the only difference is that nvarhcar can be used to store Unicode characters for multiple languages and it also takes more space when compared with varchar.

Q :-   What is the use of @@SPID?
Ans A @@SPID returns the session ID of the current user process.

Q :- How to delete duplicate rows in SQL Server?
Ans Duplicate rows can be deleted using CTE and ROW NUMER feature of SQL Server.

Q :-    Where are SQL Server user names and passwords stored in SQL Server?
Ans User Names and Passwords are stored in sys.server_principals and sys.sql_logins. But passwords are not stored in normal text.

Q :- What is the difference between GETDATE and SYSDATETIME?
Ans Both are same but GETDATE can give time till milliseconds and SYSDATETIME can give precision till nanoseconds. SYSDATE TIME is more accurate than GETDATE.

Q :-   How data can be copied from one table to another table?
Ans INSERT INTO SELECT
This command is used to insert data into a table which is already created.
SELECT INTO
This command is used to create a new table and its structure and data can be copied from existing table.

Q :-   What is TABLESAMPLE?
Ans TABLESAMPLE is used to extract sample of rows randomly that are all necessary for the application. The sample rows taken are based on the percentage of rows.

Q :-   Which command is used for user defined error messages?
Ans RAISEERROR is the command used to generate and initiates error processing for a given session. Those user defined messages are stored in sys.messages table.

Q :- What do mean by XML Datatype?
Ans XML data type is used to store XML documents in the SQL Server database. Columns and variables are created and store XML instances in the database.


Q :- What is CDC?
Ans CDC is abbreviated as Change Data Capture which is used to capture the data that has been changed recently. This feature is present in SQL Server 2008.

Q :- What is SQL injection?
Ans SQL injection is an attack by malicious users in which malicious code can be inserted into strings that can be passed to an instance of SQL server for parsing and execution. All statements have to checked for vulnerabilities as it executes all syntactically valid queries that it receives.Even parameters can be manipulated by the skilled and experienced attackers.

Q :-   What are the methods used to protect against SQL injection attack?
Ans Following are the methods used to protect against SQL injection attack:
Use Parameters for Stored Procedures
Filtering input parameters
Use Parameter collection with Dynamic SQL
In like clause, user escape characters

Q :- What is Filtered Index?               
Ans Filtered Index is used to filter some portion of rows in a table to improve query performance, index maintenance and reduces index storage costs. When the index is created with WHERE clause, then it is called Filtered Index
That's it

----------------------------------------------------------------------------------------------------------------------
Providing on the Web, online library and learning platform for IT Professional Developers with a unique blend of original content, peer-to-peer advice from the largest community of IT.

For The Latest Technology & Topics...

Redhat Linux | Linux Howtos | Ubuntu | Linux News | Centos | Linux Mint | Fedora | Linux Commands | Interview Question & Answers | Lintu Tricks | Linux Commands | Debian | Cinnamon | Apache | MySQL | Databases | Oracle-db | Java | SQL | pgAdmin | DevOps | Scripting | Python | Jenkins | Amazon AWS | Programming | Videos for Developers | Security & Hacking | VMware | Desktop | Laptops | Servers | Networking | Cloud | Installation | Operating System | MS Office | Switches | Routers | Firewall | Open Source | Outlook,Thunderbird, Gmail Emails | Monitoring Tools | JavaScript | YouTube | Android | Smartphone | Facebook | WhatsApp | Snapchat | Instagram | WordPress | Virtualbox | Browsers | Software | Hardware | Internet | Maintenance & Optimization | Antivirus | News | Google Play Store Apps | Prices | SEO | PC Games | Mobile Games | iPhone | Microsoft Windows 7 | Windows 10 | Windows Server 2012/2016/2019 | Windows Tips & Tricks | Tutorials | Training | Troubleshooting | Guides | Tips and Tricks | Reviews | Technology | IT Support | IT News | Advice for Technology | Features | Cloud | Cloud Computing | Privacy & Security| Banks

Follow Cloud Network on Twitter, Facebook and Subscribe to our YouTube channel.