Information Technology
SQL Server Interview Questions & Answers
Relational databases with SQL Server.
Aggregate Functions & GROUP BY
All 7 questionsAggregate functions calculate a single summary value from a set of rows, such as counting how many rows exist, adding up a column, or finding the average, minimum, or maximum value…
GROUP BY splits your rows into separate groups based on the values in one or more columns, and then any aggregate function in your query calculates its result separately for each o…
You use the HAVING clause instead of WHERE to filter after grouping and aggregation have already happened, since WHERE filters individual rows before grouping occurs, while HAVING…
- How do you correctly combine WHERE and HAVING in the same query to filter both individual rows and grouped results? Intermediate
You place WHERE before GROUP BY to filter out individual rows early, based on conditions that do not depend on aggregation, and then place HAVING after GROUP BY to filter the resul…
ROLLUP generates subtotal rows for each level of a hierarchy along with a final grand total, while CUBE generates subtotals for every possible combination of the grouped columns, b…
Always On Availability Groups
All 7 questionsAn Always On Availability Group is a high availability feature that keeps a copy of one or more databases synchronized across multiple SQL Server instances, so if the main server f…
The primary replica is the active database that handles all the read and write operations from your applications, while secondary replicas hold a continuously updated copy of that…
- What is the difference between automatic failover and manual failover in an Always On Availability Group? Intermediate
Automatic failover happens without any human intervention when a properly configured synchronous secondary replica detects that the primary has failed, immediately promoting itself…
An availability group listener provides a single, stable network name and address that applications connect to, regardless of which replica is currently acting as the primary, mean…
Synchronous commit mode waits for a secondary replica to confirm it has received and written the transaction before the primary considers the transaction complete, guaranteeing zer…
Backup & Recovery
All 7 questionsA full backup captures the entire database at a specific point in time, a differential backup captures only the changes made since the last full backup, and a transaction log backu…
You use the RESTORE DATABASE statement, specifying the database name and the location of the backup file, and SQL Server will recreate the database exactly as it existed at the mom…
- What are the three recovery models available in SQL Server, and how do they affect your backup strategy? Intermediate
The simple recovery model automatically clears the transaction log after each checkpoint and does not support log backups, the full recovery model keeps a complete log of every tra…
You restore the most recent full backup with the NORECOVERY option, then restore any differential backup if one exists, and finally restore the transaction log backups in order, us…
You would schedule full backups on a regular cycle such as weekly, differential backups daily to reduce restore time, and frequent transaction log backups, perhaps every five to fi…
Change Data Capture (CDC)
All 7 questionsChange Data Capture, often called CDC, automatically records insert, update, and delete activity on a table into a separate set of change tables, letting other systems or processes…
- How do you enable Change Data Capture on a specific table, and what does that process actually create? Intermediate
You first enable CDC at the database level using sp_cdc_enable_db, and then enable it for a specific table using sp_cdc_enable_table, which creates a corresponding change table tha…
- How do you query the change data captured for a table to find out exactly what changed within a specific time range? Intermediate
You use the cdc.fn_cdc_get_all_changes or cdc.fn_cdc_get_net_changes table valued functions, passing in the starting and ending log sequence numbers that correspond to your desired…
You would schedule a job that periodically queries the CDC change functions for each tracked table since the last successful run, apply those specific inserted, updated, and delete…
CDC adds some overhead to every insert, update, and delete since it must also write to the change table, and the change tables themselves consume additional storage that grows cont…
Columnstore Indexes
All 7 questionsA regular index organizes data by row, while a columnstore index organizes and compresses data by column instead, which dramatically speeds up queries that scan and aggregate large…
- What is the difference between a clustered columnstore index and a nonclustered columnstore index? Beginner
A clustered columnstore index replaces the entire table's underlying storage with columnstore format and is typically used for large fact tables in a data warehouse, while a nonclu…
Columnstore compression groups similar values from the same column together, which allows SQL Server to use highly efficient compression algorithms since repeated or similar values…
- What kinds of workloads benefit the most from columnstore indexes, and which workloads should avoid them? Intermediate
Columnstore indexes excel at analytical workloads that scan large amounts of data and aggregate results, such as data warehouse reporting, but they are generally a poor fit for tra…
New rows inserted into a columnstore indexed table are first placed into a delta store, a small rowstore structure, before eventually being compressed into full columnstore rowgrou…
Common Table Expressions (CTEs)
All 7 questionsA common table expression, defined using the WITH keyword, creates a temporary named result set that you can reference within a single query, making complex queries easier to read…
You separate multiple CTE definitions with a comma after the WITH keyword, and each subsequent CTE can even reference the ones defined before it, letting you build up a series of c…
- What is a recursive common table expression, and what kind of problems is it commonly used to solve? Intermediate
A recursive CTE references itself within its own definition, repeatedly building on its previous results, which makes it especially useful for working with hierarchical data, such…
SQL Server has a default maximum recursion limit of one hundred, which will stop the query and raise an error if that limit is exceeded, but you can also explicitly set a lower lim…
You define a CTE that uses ROW_NUMBER combined with a PARTITION BY clause to assign a sequential number to each duplicate group based on the columns that define a duplicate, and th…
Constraints (Primary Key, Foreign Key, Check & Unique)
All 7 questionsA primary key constraint uniquely identifies each row in a table, ensuring no two rows can have the same value in that column, and it also automatically prevents that column from c…
A foreign key constraint links a column in one table to the primary key of another table, ensuring that any value entered in that column must already exist in the referenced table,…
- What is a check constraint, and how do you use one to enforce a specific business rule at the database level? Intermediate
A check constraint defines a condition that every value in a column, or combination of columns, must satisfy before a row can be inserted or updated, letting you enforce business r…
- How is a unique constraint different from a primary key constraint, and when would you use one instead of the other? Intermediate
A unique constraint, like a primary key, ensures every value in a column is distinct, but unlike a primary key it does allow a single NULL value and a table can have multiple uniqu…
Cascading actions automatically apply a related change to child rows when the parent row is modified or deleted, such as automatically deleting all of a customer's orders when that…
Cursors
All 7 questionsA cursor lets you process a query's results one row at a time, similar to how you might loop through a list in a programming language, but most developers avoid them because SQL Se…
- What are the basic steps required to declare, open, use, and properly clean up a cursor? Intermediate
You declare the cursor with a defining query, open it to begin execution, fetch rows one at a time in a loop while checking the fetch status to know when to stop, and finally close…
A static cursor takes a snapshot of the data when it is opened and does not reflect later changes, a dynamic cursor reflects changes made to the underlying data while the cursor is…
You identify the specific logic being applied to each row inside the cursor's loop, and translate that same logic directly into a single UPDATE statement with an appropriate WHERE…
Cursors can be reasonable when you need to call an external process, like a stored procedure that sends an email, once for each row individually, when performing complex administra…
Data Types & Schema Design
All 7 questionsINT is used for whole numbers like an id or a count, VARCHAR stores variable length text like names or descriptions, DECIMAL is used for precise numbers like currency where roundin…
- What is the difference between VARCHAR and NVARCHAR, and when should you choose one over the other? Beginner
VARCHAR stores regular text using one byte per character and is sufficient for languages using the standard English alphabet, while NVARCHAR stores Unicode text using two bytes per…
You consider the realistic range of values a column will ever need to hold, choosing a smaller data type like TINYINT or SMALLINT when the range is genuinely limited to save storag…
- What are the differences between DATETIME, DATETIME2, and DATE, and when would you choose each one? Intermediate
DATE stores only a calendar date without any time component, DATETIME stores both a date and time but with a fixed precision and a limited date range going back to the year 1753, w…
You create a separate junction table, sometimes called a bridge or associative table, that contains foreign keys referencing both related tables, letting a single student be linked…
Deadlocks
All 7 questionsA deadlock happens when two or more transactions each hold a lock that the other transaction needs, creating a cycle where neither can move forward, so SQL Server must step in and…
SQL Server generally chooses the transaction that is cheapest to roll back based on the amount of work already done, unless a session has been given a higher deadlock priority, in…
The victim transaction receives error number 1205, and the application should catch this specific error and automatically retry the entire transaction after a short delay, since th…
You set up an Extended Events session capturing the xml_deadlock_report event, which automatically records full details about every deadlock that occurs, including the exact querie…
You examine the captured XML deadlock report, looking at the process list to see each transaction's query text and the resource list to see exactly which locks each transaction was…
Dynamic Data Masking
All 7 questionsDynamic data masking automatically hides sensitive information, like a full credit card number or an email address, from users who query a table but do not have special permission…
SQL Server provides several built-in masking functions including default, which fully hides a value based on its data type, email, which partially masks an email address, random, w…
You grant the UNMASK permission to a specific user or role, either at the database level to allow them to see all masked columns, or in more recent versions, at a more granular col…
- Does dynamic data masking prevent a determined user from working around it to see the real underlying values? Intermediate
Dynamic data masking is designed to prevent casual exposure of sensitive data in typical query results, but it is not a strong security boundary on its own, since a user with suffi…
You would first identify all columns containing sensitive information such as national identification numbers, emails, or phone numbers, apply the most appropriate masking function…
Dynamic SQL
All 7 questionsDynamic SQL means building a SQL statement as a text string at runtime and then executing it, which is useful when parts of your query, such as the table name or the columns being…
SQL injection is a security vulnerability where an attacker inserts malicious SQL code into an input field, which then gets concatenated directly into a dynamic SQL string and exec…
sp_executesql lets you define a parameterized dynamic SQL statement and pass in parameter values separately, similar to how a regular stored procedure works, which both protects ag…
Since parameters in sp_executesql can only substitute for values and not for object names like tables or columns, you must carefully validate and sanitize any user provided table o…
You build the base query as a string and conditionally append additional WHERE clause segments only for the filter parameters that were actually provided, using parameterized value…
Error Handling with TRY CATCH
All 7 questionsA TRY CATCH block lets you run a piece of SQL code inside the TRY section, and if any error occurs during its execution, control immediately jumps to the CATCH section instead of s…
Inside a CATCH block, you can use functions like ERROR_MESSAGE to get the actual error text, ERROR_NUMBER for the specific error code, ERROR_LINE for the line number where the erro…
You begin a transaction inside the TRY block, and if an error occurs and control moves to the CATCH block, you check whether a transaction is still open using XACT_STATE and roll i…
- What is the difference between using THROW and RAISERROR to raise a custom error in SQL Server? Intermediate
THROW is the newer, simpler way to raise an error, automatically preserving the original error information when used without parameters inside a CATCH block, while RAISERROR is the…
You create a stored procedure that accepts the standard error information as parameters, or calls the error functions directly since they remain accessible within the scope of the…
Full Text Search
All 7 questions- What is full text search in SQL Server, and how is it different from a regular LIKE search? Beginner
Full text search is a specialized indexing feature designed for efficiently searching large amounts of text, letting you find whole words or phrases quickly even in very large tabl…
You first create a full text catalog to organize your full text indexes, then create a full text index on the specific table and columns you want to search, which requires the tabl…
- What is the difference between the CONTAINS and FREETEXT predicates when performing a full text search? Intermediate
CONTAINS gives you precise control, letting you search for exact words, phrases, or use logical operators and proximity searches, while FREETEXT performs a more flexible, natural l…
- How do you perform a proximity search using full text search, finding rows where two words appear near each other? Intermediate
You use the CONTAINS predicate with the NEAR keyword, specifying the two words you want to find close together, optionally including a maximum distance between them, which is usefu…
You specify a language for your full text index using the LANGUAGE option, which tells SQL Server which word breaker and stemmer to use for that specific language, ensuring words a…
Hash Indexes & Hash Join Operations
All 7 questionsA hash join works by building a temporary hash table in memory from the smaller of the two input sets, based on the join column, and then scanning the larger input, checking each r…
A hash index stores a computed hash value for each row's indexed column, allowing extremely fast equality lookups, and is specifically the type of index used with memory optimized…
- How does the BUCKET_COUNT setting affect the performance of a hash index on a memory optimized table? Intermediate
The bucket count determines how many hash buckets are available to distribute rows into, and choosing a bucket count too small compared to your actual row count causes too many row…
The optimizer tends to choose a hash join when joining two relatively large tables that lack a useful index on the join column, or when at least one input is not already sorted, si…
When the hash table does not fit in the memory that was granted, SQL Server spills excess data to disk in a process called a hash spill, which is significantly slower than an entir…
Indexes
All 7 questionsAn index creates a separate, organized structure that lets SQL Server quickly locate specific rows in a table without scanning every single row, similar to how the index at the bac…
A clustered index determines the actual physical order in which data is stored on disk, meaning a table can only have one clustered index, while a nonclustered index creates a sepa…
A covering index includes all the columns a specific query needs, either as key columns or as included columns, meaning SQL Server can satisfy the entire query directly from the in…
- How do you identify unused or duplicate indexes that might be safely removed to improve write performance? Intermediate
You can query dynamic management views like sys.dm_db_index_usage_stats to see how often each index is actually being used for reads versus how much overhead it adds to writes, and…
As data is inserted, updated, and deleted, an index's logical order can become increasingly out of sync with its physical storage order, called fragmentation, which can slow down q…
In-Memory OLTP (Memory-Optimized Tables)
All 7 questionsIn-Memory OLTP lets you create memory optimized tables that are held entirely in memory rather than on disk, using a different internal engine specifically designed for extremely f…
By default, memory optimized tables are still durable, meaning their data is also persisted to disk and will be available again after a restart, though you can optionally configure…
In-Memory OLTP uses an optimistic concurrency model based on comparing row versions, entirely avoiding traditional locks and latches that disk based tables rely on to manage concur…
- What are natively compiled stored procedures, and how do they work together with memory optimized tables? Intermediate
A natively compiled stored procedure is compiled directly into machine code when it is created rather than being interpreted at execution time like a regular stored procedure, offe…
You would look for tables experiencing significant contention from many concurrent transactions, such as heavy locking or blocking shown in wait statistics, combined with a workloa…
Isolation & Locking
All 7 questionsA lock is a mechanism SQL Server uses to control concurrent access to data, temporarily preventing other transactions from making conflicting changes to the same data at the same t…
The isolation level controls how much one transaction can be affected by changes made by other concurrently running transactions, with Read Uncommitted allowing the most interferen…
A deadlock happens when two or more transactions are each waiting for a lock held by the other, creating a cycle where neither can proceed, and SQL Server automatically detects thi…
A pessimistic approach assumes conflicts are likely and uses locks to prevent them from happening in the first place, while an optimistic approach assumes conflicts are rare and in…
You would query dynamic management views like sys.dm_exec_requests and sys.dm_tran_locks to identify the specific session holding the blocking locks, examine what that session is c…
Joins
All 7 questionsAn INNER JOIN combines rows from two tables based on a matching condition, returning only the rows where a match is found in both tables, meaning any row without a corresponding ma…
A LEFT JOIN returns all rows from the left table along with any matching rows from the right table, filling in NULL for columns from the right table when no match exists, while a R…
- How do you find rows that exist in one table but have no matching row in another table using a join? Intermediate
You use a LEFT JOIN and then add a WHERE clause checking that the joined column from the right table is NULL, which identifies exactly the rows from the left table that did not fin…
A FULL OUTER JOIN returns all rows from both tables, matching them where possible and filling in NULL values on either side when no match exists, which is useful when you need to s…
A CROSS JOIN combines every row from the first table with every row from the second table, producing a result set whose size is the product of both table's row counts, which is gen…
JSON Support in SQL Server
All 7 questionsSQL Server stores JSON as regular text in an NVARCHAR column, but provides special built-in functions that let you parse and query values from within that JSON text directly in you…
JSON_VALUE extracts a single scalar value, like a string or number, from a JSON document, while JSON_QUERY extracts an entire object or array from within the JSON, letting you pull…
You use the OPENJSON function, which parses a JSON array or object and returns its elements as a set of rows and columns, letting you treat data that was originally stored as JSON…
You add the FOR JSON clause to the end of your SELECT statement, choosing either AUTO to let SQL Server automatically structure the output based on your table and column names, or…
You add a check constraint using the ISJSON function, which returns whether a given string is valid JSON, ensuring that any value inserted or updated in that column must be properl…
Linked Servers
All 7 questionsA linked server lets your SQL Server instance connect to and query data from another database server, whether it is another SQL Server instance or a different type of database enti…
You reference the remote table using a four part naming convention consisting of the linked server name, the remote database name, the schema, and the table name, letting you query…
- What are the security considerations when configuring authentication for a linked server connection? Intermediate
You need to decide how the local server authenticates to the remote server, either by passing through the current user's own credentials, using a fixed set of credentials for all c…
- What performance issues commonly arise when querying data through a linked server, and how can you address them? Intermediate
Queries against a linked server can perform poorly if SQL Server has to pull large amounts of data across the network before it can apply filters or joins locally, so it often help…
- How would you troubleshoot a linked server query that is running much slower than expected? Advanced
You would examine the execution plan to see how much of the query is being processed remotely versus locally, check whether appropriate indexes exist on the remote table being quer…
Merge Statement (Upsert)
All 7 questionsThe MERGE statement lets you compare a source set of data against a target table and, in a single statement, insert new rows that do not yet exist, update existing rows that have c…
WHEN MATCHED handles rows that exist in both the target and source, typically used for updates, WHEN NOT MATCHED BY TARGET handles rows that exist in the source but not the target,…
The MERGE statement has historically had a few documented bugs related to trigger behavior and concurrency under certain isolation levels, and Microsoft has recommended being cauti…
You add an OUTPUT clause to your MERGE statement, referencing the special $action column along with the inserted and deleted pseudo tables, which lets you capture exactly what happ…
You would use MERGE to compare incoming dimension data against the current table, closing out the previous version of a changed record by setting an end date and marking it inactiv…
Normalization
All 7 questionsDatabase normalization is the process of organizing tables and columns to reduce data duplication and improve data integrity, typically by breaking down a large table into smaller,…
The first normal form requires that every column in a table contains only a single, indivisible value, meaning you should not store multiple values, like several phone numbers, cra…
- What is the second normal form, and how does it build on the requirements of the first normal form? Intermediate
The second normal form requires a table to already be in first normal form, and additionally requires that every non key column depends on the entire primary key, not just part of…
- What is the third normal form, and what kind of dependency does it specifically eliminate? Intermediate
The third normal form requires a table to already satisfy second normal form, and additionally requires that non key columns do not depend on other non key columns, eliminating wha…
You might intentionally denormalize by duplicating some data to significantly speed up frequently run, performance critical read queries, particularly in reporting or data warehous…
Partitioning
All 7 questions- What is table partitioning in SQL Server, and what problem does it help solve for very large tables? Beginner
Table partitioning splits a very large table into smaller, more manageable physical pieces called partitions, typically based on a range of values like a date column, while the tab…
A partition function defines the actual boundary values used to split data into ranges, such as splitting by year, while a partition scheme maps each of those defined ranges to a s…
Partition elimination allows SQL Server's query optimizer to skip scanning partitions that could not possibly contain data relevant to a query's filter condition, such as skipping…
- How does a sliding window pattern work for automatically archiving old data using partitioning? Intermediate
A sliding window pattern involves regularly adding a new empty partition for upcoming data and switching out the oldest partition, moving its data to an archive table almost instan…
Both the source and target tables must have identical column definitions, matching indexes, and matching constraints, and the data being switched must fully satisfy the partition b…
Pivoting & Unpivoting Data
All 7 questionsPivoting transforms data from a row based format into a column based format, taking distinct values from one column and turning them into separate column headers, which is commonly…
- What does it mean to unpivot data, and how is it essentially the opposite operation of pivoting? Beginner
Unpivoting transforms data from a column based format back into a row based format, taking several separate columns and converting them into rows with a category label and a corres…
The PIVOT operator requires an aggregate function applied to the value you want to summarize, the FOR keyword followed by the column whose distinct values will become new column he…
Since the standard PIVOT operator requires you to list the exact column values explicitly, you combine it with dynamic SQL, first querying to find the current distinct values that…
Since a single PIVOT operator only supports one aggregate function at a time, you would either run two separate pivoted queries for each aggregate and join their results together,…
Query Optimization & Plans
All 7 questions- What is an execution plan in SQL Server, and how does it help you understand query performance? Beginner
An execution plan shows exactly how SQL Server intends to carry out a query, including which indexes it plans to use, how it will join tables together, and in what order operations…
A table scan means SQL Server reads through every single row in a table to find the ones it needs, which becomes slow on large tables, while an index seek means SQL Server uses an…
- How do outdated or missing statistics affect the query optimizer's ability to choose an efficient execution plan? Intermediate
SQL Server relies on statistics about the distribution of data within your tables to estimate how many rows a query will return and choose the most efficient plan accordingly, and…
- What is parameter sniffing, and how can it sometimes lead to unexpectedly poor query performance? Intermediate
Parameter sniffing happens when SQL Server caches an execution plan based on the specific parameter values used the first time a query or stored procedure runs, and if a very diffe…
You can add specific query hints, such as forcing a particular join type, a specific index, or a maximum degree of parallelism, directly in your query using the OPTION clause, thou…
Query Store
All 7 questionsQuery Store is a built-in feature that automatically captures a history of queries, their execution plans, and detailed runtime statistics like duration and resource usage over tim…
You can use the built-in reports available directly in SQL Server Management Studio under the Query Store folder for a database, such as Top Resource Consuming Queries, which visua…
- How do you use Query Store to identify a query whose performance has regressed after a recent code deployment? Intermediate
You use the Query Store's Regressed Queries report, which compares a query's recent performance against an earlier baseline period, highlighting queries that have become noticeably…
- How do you force SQL Server to use a specific, previously known good execution plan for a query using Query Store? Intermediate
You identify the desired plan id from Query Store's history of captured plans for that query, and use the sp_query_store_force_plan stored procedure to instruct SQL Server to alway…
You would adjust settings such as the maximum size allocated for Query Store data, the data flush interval controlling how often captured information is written to disk, the statis…
Replication
All 7 questionsReplication is a set of technologies that automatically copies and synchronizes data from one database, called the publisher, to one or more other databases, called subscribers, le…
Snapshot replication periodically copies an entire fresh snapshot of the published data, transactional replication continuously sends individual data changes as they happen for nea…
- What roles do the publisher, distributor, and subscriber play in a transactional replication setup? Intermediate
The publisher is the source database where the original data changes happen, the distributor is a special role, sometimes a separate server, that manages and forwards the captured…
You can use Replication Monitor, a built-in graphical tool in SQL Server Management Studio, which shows the current status of each publication and subscription, including how much…
You would check the status of the relevant replication agents, such as the log reader agent and distribution agent, in Replication Monitor or through their job history, review any…
SQL Server Agent & Job Scheduling
All 7 questionsSQL Server Agent is a background service that runs and manages scheduled jobs, such as regular database backups, index maintenance, data synchronization tasks, and custom scripts,…
- How do you create a basic SQL Server Agent job that runs a T-SQL script on a defined schedule? Beginner
You create a new job, add one or more job steps defining the actual T-SQL command or script to run, and attach a schedule specifying how often and when the job should execute, such…
You configure Database Mail with a valid mail profile, create an operator representing the person or team who should be notified, and then set up a notification on the job itself s…
You set the retry attempts and retry interval properties on a specific job step, telling SQL Server Agent to automatically attempt that step again a defined number of times, waitin…
You configure each job step's on success and on failure actions individually, choosing whether to move to the next step, quit the job reporting success, or quit the job reporting f…
SQL Server Architecture & Editions
All 7 questionsThe database engine handles storing, processing, and securing data, the SQL Server Agent automates scheduled tasks, SQL Server Analysis Services supports business intelligence and…
- What are the main differences between SQL Server Express, Standard, and Enterprise editions? Beginner
Express edition is free but has significant limitations on database size and available features, making it suitable for small applications or learning, Standard edition supports mo…
SQL Server uses a portion of the server's memory as a buffer pool, caching frequently accessed data pages in memory to avoid slower disk reads whenever possible, meaning that havin…
- What is tempdb, and why is its configuration particularly important for overall SQL Server performance? Intermediate
Tempdb is a special system database used by SQL Server for temporary objects like temporary tables, sorting operations, and row versioning, and since it is shared across the entire…
You would carefully size available memory to support a sufficiently large buffer pool for your expected data volume, choose fast storage such as solid state drives especially for t…
SQL Server Profiler & Extended Events
All 7 questionsSQL Server Profiler is a graphical tool that captures a detailed trace of events happening on a SQL Server instance, such as every query executed, how long each one took, and any e…
Extended Events are a lightweight, highly configurable event tracing system built directly into the SQL Server engine, using significantly less overhead than the older Profiler too…
- How do you create an Extended Events session to capture specific long running queries on a production server? Intermediate
You define an event session specifying which event to capture, such as sql_statement_completed, add a predicate filtering for only the specific conditions you care about, like a mi…
- How do you analyze the data captured by an Extended Events session once it has been running for a period of time? Intermediate
You can open the event file target directly in SQL Server Management Studio, which provides a graphical interface for viewing and filtering the captured events, or query the file p…
You would capture the xml_deadlock_report event, which automatically fires whenever a deadlock occurs, providing full details about the transactions and resources involved, and con…
SQL Server Security & Permissions
All 7 questionsA login is created at the server level and controls whether someone can connect to the SQL Server instance at all, while a database user exists within a specific database and is ma…
Windows Authentication uses the user's existing Windows domain credentials to connect to SQL Server, relying on the security already managed by the organization's Windows environme…
- How do database roles help simplify managing permissions for multiple users with similar access needs? Intermediate
A database role lets you group together a specific set of permissions once, and then simply add or remove individual users from that role to grant or revoke that entire set of perm…
- What is the principle of least privilege, and how should it guide how you grant permissions in SQL Server? Intermediate
The principle of least privilege means giving a user or application only the specific permissions they actually need to perform their job, and nothing more, reducing the potential…
You create a security policy using an inline table valued function that defines the logic for which rows a given user is allowed to access, then apply that policy to the relevant t…
Stored Procedures & Functions
All 7 questionsA stored procedure is a saved, reusable collection of SQL statements stored directly in the database, offering benefits like improved performance through plan reuse, better securit…
- What is the difference between a scalar function and a table valued function in SQL Server? Beginner
A scalar function returns a single value, such as a calculated number or a formatted string, and can be used anywhere a single value is expected, while a table valued function retu…
- What are the main differences between a stored procedure and a function in terms of what each one can and cannot do? Intermediate
A stored procedure can perform data modifications like INSERT, UPDATE, and DELETE, can have output parameters, and cannot be used directly inside a SELECT statement, while a functi…
You declare a parameter with the OUTPUT keyword in both the procedure definition and when calling it, and any value assigned to that parameter inside the procedure becomes availabl…
When a stored procedure runs for the first time, SQL Server compiles an execution plan and caches it for reuse on subsequent calls, avoiding the overhead of recompiling the same lo…
Subqueries
All 7 questionsA subquery is a query nested inside another query, often used within a WHERE clause to filter results based on the outcome of that inner query, within a SELECT list to calculate a…
A non correlated subquery runs independently and only once, producing a fixed result that the outer query then uses, while a correlated subquery references a column from the outer…
- What is the difference between using EXISTS and IN when checking for the presence of related data with a subquery? Intermediate
EXISTS checks only whether the subquery returns any rows at all, stopping as soon as it finds a match, which can be more efficient for large data sets, while IN compares a specific…
You place a correlated subquery directly inside the SELECT list, referencing the outer query's current row, which calculates and returns a related value, such as a customer's total…
You identify the relationship being checked by the correlated subquery, and express that same logic using a JOIN combined with either GROUP BY for aggregation needs or DISTINCT for…
Temporary Tables & Table Variables
All 7 questionsA local temporary table, created with a name starting with a single pound sign, is automatically dropped when the session that created it ends, and is only visible to that specific…
A table variable is declared using the DECLARE statement with a table data type, similar to declaring any other variable, and behaves somewhat like a temporary table but with a mor…
A local temporary table, prefixed with a single pound sign, is only visible to the session that created it, while a global temporary table, prefixed with two pound signs, is visibl…
SQL Server maintains statistics for temporary tables, similar to regular tables, allowing the optimizer to make reasonably accurate estimates about the amount of data they contain,…
You would choose a table variable for very small, simple intermediate result sets used briefly within a single batch, a temporary table when you expect a larger amount of data, nee…
Transactions & ACID
All 7 questions- What is a transaction in SQL Server, and why is grouping multiple statements into one important? Beginner
A transaction groups one or more SQL statements together so they are treated as a single unit of work, meaning either all of the statements succeed together and their changes are s…
ACID stands for Atomicity, meaning a transaction fully succeeds or fully fails with nothing in between, Consistency, meaning a transaction always leaves the database in a valid sta…
You mark a specific point within your transaction using SAVE TRANSACTION with a given name, and if you later need to undo only the changes made after that point, you can roll back…
An explicit transaction is one you deliberately start with BEGIN TRANSACTION and end with COMMIT or ROLLBACK, giving you full control over exactly what statements are grouped toget…
You would typically use the Microsoft Distributed Transaction Coordinator, which manages a two phase commit protocol across the involved servers, first asking each server to prepar…
Transparent Data Encryption
All 7 questionsTransparent Data Encryption, often called TDE, encrypts an entire database's data and log files at rest on disk, protecting against the scenario where someone gains physical access…
Transparent Data Encryption protects data at rest, meaning the physical files on disk, guarding against theft of the actual database or backup files, while Dynamic Data Masking pro…
- What is the hierarchy of encryption keys and certificates involved in setting up Transparent Data Encryption? Intermediate
TDE relies on a hierarchy starting with a service master key at the server level, which protects a database master key, which in turn protects a server certificate, and finally tha…
If the certificate used to protect a TDE encrypted database is lost without a proper backup, you will be permanently unable to restore that database's backups or attach its data fi…
TDE introduces a small amount of CPU overhead since data must be encrypted before being written to disk and decrypted when read back, though modern SQL Server versions have signifi…
Triggers
All 7 questions- What is a trigger in SQL Server, and what kinds of events can cause one to run automatically? Beginner
A trigger is a special kind of stored procedure that automatically runs in response to a specific event, such as an INSERT, UPDATE, or DELETE happening on a table, or certain data…
An AFTER trigger runs once the triggering action, like an insert or update, has already completed, letting you perform additional actions based on the change that just happened, wh…
- How do you access the old and new values of a row that was just updated from inside a trigger? Intermediate
Inside a trigger, SQL Server automatically provides two special pseudo tables, called inserted and deleted, where the deleted table contains the row's values before the change and…
A single statement, such as an UPDATE with a broad WHERE clause or none at all, can affect many rows simultaneously, and a trigger fires only once for that entire statement regardl…
Triggers execute synchronously as part of the same transaction as the original statement, meaning any additional work performed inside a trigger directly adds to the time that tran…
T-SQL Fundamentals & Syntax
All 7 questionsT-SQL, short for Transact-SQL, is Microsoft's extension of standard SQL used specifically in SQL Server, adding extra features beyond the standard SQL language, such as procedural…
You declare a variable using the DECLARE keyword followed by its name, prefixed with an at sign, and its data type, then assign it a value using either SET or SELECT, after which y…
- How do IF and WHILE control flow statements work in T-SQL, and what kinds of tasks are they typically used for? Intermediate
IF lets you conditionally execute a block of code only when a specified condition is true, while WHILE repeatedly executes a block of code as long as its condition remains true, an…
- What is the difference between a batch and a transaction in T-SQL, and how does the GO keyword relate to batches? Intermediate
A batch is a group of one or more T-SQL statements sent to SQL Server together for parsing and execution as a single unit, separated using the GO keyword, which is actually a clien…
A CASE expression evaluates one or more conditions in order and returns a corresponding value for the first matching condition, or a default value if none match, letting you implem…
User Defined Functions
All 7 questionsA user defined function lets you package a piece of reusable logic, such as a calculation or a formatting routine, into a single named object that you can call from many different…
An inline table valued function consists of a single RETURN statement containing a query, and SQL Server can often optimize it very efficiently, similar to a view, while a multi st…
A scalar function called within a query is typically executed once for every single row being processed, and since older versions of SQL Server treated scalar functions as a kind o…
Scalar UDF inlining allows the optimizer to automatically transform certain qualifying scalar functions into an equivalent inline expression as part of building the execution plan,…
You would create inline table valued functions where possible for best performance, carefully name and document each function's purpose and parameters, centralize business logic li…
Views
All 7 questionsA view is a saved, named query that you can treat like a virtual table, letting you simplify complex queries by hiding their underlying complexity behind a simple name, restrict wh…
You can modify data through a view as long as it references only a single underlying table and does not include certain features like GROUP BY, DISTINCT, or aggregate functions, si…
- What is a schema bound view, and what specific benefit does the WITH SCHEMABINDING option provide? Intermediate
A schema bound view is created using the WITH SCHEMABINDING option, which prevents the underlying tables referenced by the view from being altered or dropped in a way that would br…
- What is an indexed view, and how can it improve the performance of complex, frequently run queries? Intermediate
An indexed view, also called a materialized view, physically stores the results of a view's query on disk with its own unique clustered index, rather than recalculating the query e…
You might create a base set of views that join and clean up the raw underlying tables for analysts who need reasonably detailed access, and then build additional views on top of th…
Window Functions
All 7 questionsA window function performs a calculation across a set of related rows, similar to an aggregate function, but unlike GROUP BY, it does not collapse those rows into a single summariz…
ROW_NUMBER assigns a unique, sequential number to each row within a defined partition, based on a specified order, which is commonly used for tasks like identifying and removing du…
- What is the difference between RANK, DENSE_RANK, and ROW_NUMBER when there are tied values in the ordering column? Intermediate
ROW_NUMBER always assigns a unique, sequential number even to tied rows, RANK assigns the same rank to tied rows but then skips subsequent rank numbers to account for the tie, whil…
LAG retrieves a value from a specified number of rows before the current row within the defined ordering, and LEAD retrieves a value from a specified number of rows after the curre…
The frame specification defines exactly which related rows are included in the window function's calculation relative to the current row, with ROWS defining the frame based on a ph…
XML Data Type & Querying
All 7 questionsThe XML data type stores XML documents in a way that SQL Server understands their structure, letting you validate them against a schema, query specific elements and attributes effi…
You call the value method on an XML column, providing an XPath expression identifying the specific element or attribute you want to extract along with the SQL data type you want th…
The nodes method shreds an XML document into a rowset based on a specified XPath, effectively creating one row for each matching element, which you can then combine with CROSS APPL…
- How do you modify a specific part of an XML document stored in a column without replacing the entire document? Intermediate
You use the modify method on an XML column combined with XML DML statements like insert, replace value of, or delete, specifying an XPath to target the exact node you want to chang…
- How does an XML index improve query performance against large or frequently queried XML columns? Advanced
An XML index creates an internal, queryable structure over the paths, values, and elements within an XML column, allowing SQL Server to avoid parsing the entire XML document from s…