Advertisement

Information Technology

SQL Server Interview Questions & Answers

Relational databases with SQL Server.

43topics 301questions last updated
Advertisement

Aggregate Functions & GROUP BY

All 7 questions
  1. Aggregate 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. An 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…

  2. 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…

  3. Automatic failover happens without any human intervention when a properly configured synchronous secondary replica detects that the primary has failed, immediately promoting itself…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Change 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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,…

  3. 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…

  4. 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…

  5. 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…

  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. INT 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…

  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Dynamic 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Dynamic 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…

Hash Indexes & Hash Join Operations

All 7 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…

  1. An 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. In-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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…

  1. An 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. SQL 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. The 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…

  2. 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,…

  3. 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…

  4. 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…

  5. 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 questions
  1. Database 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,…

  2. 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…

  3. 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…

  4. 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…

  5. 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
  1. 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Pivoting 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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
  1. 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Query 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Replication 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…

  2. Snapshot replication periodically copies an entire fresh snapshot of the published data, transactional replication continuously sends individual data changes as they happen for nea…

  3. 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…

  4. 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…

  5. 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 questions
  1. SQL 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,…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. The database engine handles storing, processing, and securing data, the SQL Server Agent automates scheduled tasks, SQL Server Analysis Services supports business intelligence and…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. SQL 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…

  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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,…

  5. 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
  1. 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. Transparent 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…

  1. 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. T-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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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,…

  5. 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…

  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. A 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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 questions
  1. The 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…

  2. 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…

  3. 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…

  4. 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…

  5. 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…