Modernized SQL Server Interview Cheat-Sheet
(Rewritten for clarity, updated for SQL Server 2022/Oracle 23c, and trimmed to the essentials students actually need to remember)
1 | SQL Server vs. Oracle — Quick Comparison
| Criterion | SQL Server 2022 | Oracle Database 23c |
|---|---|---|
| Primary OS support | Windows & Linux (RHEL, Ubuntu, SUSE) – also runs in Docker & Azure SQL | Windows, Linux (many distros), Solaris, AIX, HP-UX |
| Default dialect | T-SQL | PL/SQL + ANSI SQL |
| Licensing model | Core-based or subscription (incl. Azure SQL Managed Instance) | Core-based + optional BYOL in Oracle Cloud / AWS |
| Typical use cases | OLTP/OLAP, hybrid on-prem ↔ cloud, tight MS stack integration | Very large multi-platform deployments, advanced clustering (RAC), engineered systems (Exadata) |
| Learning curve | Gentler; SSMS & Azure Data Studio are beginner-friendly | Steeper; powerful but complex toolset (SQL*Plus, SQLcl, SQL Developer) |
2 | Hiding a SQL Server Instance
-
SQL Server Configuration Manager → SQL Server Network Configuration.
-
Right-click Protocols for <InstanceName> → Properties → Flags.
-
Set HideInstance = Yes → OK.
-
Restart the SQL service.
-
Connect explicitly with
ServerName,Portor the pipe name because the Browser service will no longer advertise it.
Tip (2025): Blocking the Browser service in the firewall is an easier first step if you only need to reduce—not hide—network visibility.
3 | Page & Extent Refresher
-
Page = 8 KB (unchanged since SQL Server 7.0).
-
Extent = 8 contiguous pages = 64 KB.
-
Main page types (SQL Server 2022):
-
Data, Index, TEXT/IMAGE, PFS, GAM, SGAM, IAM, Differential-Map (DMF), Bulk-Changed Map (BCM), Boot.
-
4 | Adding CPUs (Hot-Add)
-
Prerequisites: Windows Server 2016 + and Enterprise/Datacenter SKU or supported Linux kernel; VM/host must expose hot-plug CPUs.
-
Steps (no downtime):
-
Add vCPUs in hypervisor / plug hardware.
-
In SSMS run:
ALTER SERVER CONFIGURATION SET PROCESS AFFINITY AUTO; RECONFIGURE; -
Verify with
SELECT scheduler_id, status FROM sys.dm_os_schedulers;.
-
5 | Checking Port Connectivity
Modern alternative to Telnet (deprecated):
Test-NetConnection -ComputerName PAXT3DEVSQL24 -Port 1433
Returns TcpTestSucceeded : True/False plus latency.
6 | Creating a Database
CREATE DATABASE WideWorldImporters;
GO
(Use the Query Editor in SSMS/Azure Data Studio or sqlcmd CLI.)
7 | Hardening SQL Server (2025 essentials)
-
Windows authentication preferred; disable SQL logins you don’t need.
-
MF-A on privileged AD accounts.
-
Encrypt at rest & in transit: TDE or Azure Key Vault + TLS 1.2/1.3.
-
Principle of least privilege: RBAC, database roles, row-level security.
-
Rename or disable the
salogin; enforce strong password policy. -
Patch regularly (Cumulative Updates every ~60 days).
-
Network isolation: private subnets, Firewall, no public IP unless behind VPN.
8 | Startup & Emergency Modes
| Mode | Typical Command |
|---|---|
| Single-User | net stop MSSQLSERVERnet start MSSQLSERVER /m"sqlcmd" |
| Dedicated Admin Connection (DAC) | sqlcmd -A -S localhost |
| Emergency (db-level) | ALTER DATABASE MyDB SET EMERGENCY, SINGLE_USER;DBCC CHECKDB ('MyDB', REPAIR_ALLOW_DATA_LOSS); |
9 | Replication Overview (current names)
| Type | Use Case | Latency |
|---|---|---|
| Snapshot | Read-mostly tables, small DBs | Minutes / hours |
| Transactional | Real-time reporting, DR | Seconds |
| Peer-to-Peer (evolved from Merge) | Multi-write, geo-distributed OLTP | Seconds |
| Merge | Mobile / occasionally connected | Variable |
Push vs. Pull: push = Distributor runs the agent; pull = agent runs at the Subscriber.
10 | Replication Components
-
Publisher → defines Publications (articles).
-
Distributor → stores & forwards data (can be remote).
-
Subscriber → consumes.
-
Log Reader Agent → scans the publisher’s log and queues commands.
Health tools: Replication Monitor, sp_replmonitorsubscriptionpendingcmds, Extended Events.
11 | Downgrade? (SQL 2022 → 2019/2017)**
Direct attach/restore not supported. Use:
-
Export Data-Tier Application (bacpac),
-
SSIS / BCP / PolyBase, or
-
Transactional Replication with lower-version subscriber.
12 | Index Primer
| Clustered | Non-Clustered | |
|---|---|---|
| Physical order | Yes (one per table) | No |
| Includes all columns? | Always | Only key + optional INCLUDE columns |
| Ideal for | Range queries, PKs | Lookups on non-key columns |
13 | Recovering a Suspect Database
ALTER DATABASE MyDB SET EMERGENCY, SINGLE_USER;
DBCC CHECKDB (MyDB, REPAIR_ALLOW_DATA_LOSS);
ALTER DATABASE MyDB SET MULTI_USER;
Always try to restore from backup first; REPAIR_ALLOW_DATA_LOSS does exactly what it says.
14 | Deadlocks—Avoidance Tips
-
Keep transactions short; commit quickly.
-
Touch objects in the same order in every proc.
-
Use row-level locks where possible (appropriate indexes).
-
Capture graphs with Extended Events:
system_healthsession already logs them.
15 | CHAR vs. VARCHAR
| CHAR(n) | VARCHAR(n) | |
|---|---|---|
| Storage | Fixed n bytes (+padding) | 1–n bytes + 2-byte length |
| Performance | Slightly faster for truly fixed-width like ISO codes | More space-efficient for variable text |
16 | Why Use Views?
-
Hide complexity (
SELECT * FROM vwSalesSummary). -
Abstract schema changes.
-
Enforce row/column security (WITH CHECK OPTION, RLS).
17 | Tuning Stored Procedures (2025 checklist)
-
Sargable predicates (
WHERE Col = @pnotWHERE CONVERT(varchar,Col)=@p). -
Proper indexes including filtered & columnstore where appropriate.
-
Avoid RBAR: use set-based inserts/updates.
-
Parameter sniffing fixes: OPTIMIZE_FOR, RECOMPILE, or plan guides.
-
Review query plan (
sys.dm_exec_query_plan).
18 | Normalization — 10-Second Definition
Splitting data into logical tables (1NF → 5NF) to eliminate redundancy, ensure update consistency, and improve each table’s focus.
19 | Profiler is Legacy — Use Extended Events
SQL Profiler/Server Trace is still available but deprecated. Use Extended Events (XE) sessions in SSMS; lighter, more granular, scriptable.
20 | JOIN & SET Operators Quick-Look
-
INNER JOIN → rows where keys match in both tables.
-
LEFT JOIN → all rows from left + matching right; NULLs when no match.
-
UNION → distinct rows from two
SELECTs. -
UNION ALL → same but keeps duplicates (faster, no sort).
21 | Transactions in Stored Procs
CREATE PROC TransferMoney
@From int, @To int, @Amt money
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRAN;
UPDATE Accounts SET Balance -= @Amt WHERE Id = @From;
UPDATE Accounts SET Balance += @Amt WHERE Id = @To;
COMMIT;
END TRY
BEGIN CATCH
ROLLBACK;
THROW;
END CATCH;
END
GO
Final Tips for Students
-
Hands-on > theory: spin up a free SQL Server Docker container and practice every command above.
-
Keep the “Internals” diagram (Pages → Extents → Files) in your notes; most interview stumpers trace back to it.
-
Learn one modern troubleshooting tool (Extended Events) really well—it replaces Profiler, Top Query reports, and more.
Good luck on your DBA interviews!
Q. What is the objective of the COALESCE function in SQL Server?
Answer: COALESCE returns the first non-NULL value from a list of expressions. It’s useful for handling NULL values by providing a default.
Example:
SELECT COALESCE(NULL, NULL, 'third_value', 'fourth_value');
This would return 'third_value'.
SQL Server Advanced Query Concepts – Cheat-Sheet
1 | Error Handling in Stored Procedures
Use the TRY...CATCH block to gracefully catch and manage errors.
BEGIN TRY
-- Risky code (e.g., division, DML)
INSERT INTO Orders (CustomerID) VALUES (@CustomerID);
END TRY
BEGIN CATCH
PRINT 'Error Number: ' + CAST(ERROR_NUMBER() AS VARCHAR);
PRINT 'Message: ' + ERROR_MESSAGE();
ROLLBACK TRANSACTION;
END CATCH;
✅ You can also use
THROW(modern replacement forRAISERROR) to re-raise the error.
2 | Temporary Tables vs Table Variables
| Feature | Temporary Table | Table Variable |
|---|---|---|
| Syntax | CREATE TABLE #Temp or ##GlobalTemp |
DECLARE @TableVar TABLE (...) |
| Scope | Local (#) = session; Global (##) = across sessions |
Current batch/procedure only |
| Indexing | Can define clustered and non-clustered indexes | Limited: can declare a PK or clustered index only |
| Statistics | ✅ Yes (used by query optimizer) | ❌ No — may result in less optimal plans |
Use in INSERT EXEC |
✅ Allowed | ❌ Not supported |
3 | Common Table Expression (CTE)
A CTE is a temporary, named result set defined within the scope of a single query. It improves readability, modularity, and supports recursion.
Syntax Example:
-- Simple (non-recursive) CTE
WITH TopCustomers AS (
SELECT CustomerID, COUNT(*) AS OrderCount
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) > 5
)
SELECT * FROM TopCustomers;
Recursive Example:
-- Hierarchical query with recursion
WITH OrgChart (EmployeeID, ManagerID, Level) AS (
SELECT EmployeeID, ManagerID, 0
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.ManagerID, Level + 1
FROM Employees e
JOIN OrgChart o ON e.ManagerID = o.EmployeeID
)
SELECT * FROM OrgChart;
🧠 Tip: Always end recursive CTEs with
OPTION (MAXRECURSION n)to prevent infinite loops.
WITH CTE_Name AS (
SELECT column1, column2 FROM some_table
)
SELECT * FROM CTE_Name;
✅ SQL Server – Advanced Concepts Q&A
Q: How is a full-text search different from a regular search in SQL Server?
A:
A full-text search enables powerful linguistic searches such as finding word variations, phrases, or words near each other. It supports CONTAINS, FREETEXT, and inflectional forms (e.g., “run” also matches “running”).
In contrast, regular searches (like WHERE Name LIKE '%run%') only match literal string patterns, which limits flexibility and performance on large text fields.
Q: What is the difference between a Trigger and a Stored Procedure in SQL Server?
A:
-
Trigger: Executes automatically in response to a
INSERT,UPDATE, orDELETEon a table or view. Used for enforcing rules or logging changes. -
Stored Procedure: A manually invoked set of SQL commands stored under a name. It can accept input/output parameters, use control flow, and be reused by applications or other procedures.
Q: How can you retrieve an image stored in SQL Server?
A:
If the image is stored in a column of type VARBINARY(MAX) or IMAGE (deprecated), use a SELECT query like:
SELECT ImageData FROM Products WHERE ProductID = 101;
The result returns binary data, which must be handled in your application layer (e.g., C#, Python) to decode and display the image properly.
Q: What is the difference between a Function and a Stored Procedure in SQL Server?
A:
| Feature | Function | Stored Procedure |
|---|---|---|
| Returns | Must return a value (scalar or table) | May return nothing, one, or multiple output values |
| Use in SELECT | ✅ Yes | ❌ Not allowed |
| Can modify data? | ❌ No (read-only) | ✅ Yes (can use INSERT/UPDATE/DELETE) |
| Transactions | Cannot start/commit/rollback | ✅ Full transaction support |
| Dynamic SQL | ❌ Not supported | ✅ Supported |
Trending SQL DBA Tutorials
Microsoft Power BI Certification Training Course
Trainer: Microsoft Partner
Subject matter experts curate a Power BI certification course hands-on experience in real-time projects to help you clear the official Microsoft Power BI Data Analyst Exam: PL-300.
AWS Solutions Architect Certification Training Course
Trainer: Microsoft Partner
AWS Training will help you train for the AWS Certified Solutions Architect – Associate exam SAA-C03. With Edureka’s live instructor-led sessions, you can effectively architect, monitor, and deploy secure and robust AWS applications.
DevOps Certification Training Course
Trainer: Microsoft Partner
This course certifies you as a practitioner in Continuous Development, Configuration Management, Continuous Integration, and Continuous Monitoring. You’ll learn to apply these practices for optimal results in software development.