SQL Server & T-SQL


What is SQL Server?

SQL Server = Microsoft's enterprise relational database management system (RDBMS)

T-SQL = Transact-SQL, Microsoft's extension of SQL standard

Key Features:

  • ACID compliant - Reliable transactions

  • High performance - Optimized query execution

  • Scalability - Handles small to enterprise workloads

  • Security - Row-level security, encryption, auditing

  • Integration - Works seamlessly with .NET ecosystem

  • Rich tooling - SQL Server Management Studio (SSMS), Azure Data Studio

SQL Server Editions

Express - Free, limited to 10GB database size

-- Perfect for: Development, small applications, learning

Developer - Free, full features (non-production only)

-- Perfect for: Development and testing

Standard - Commercial, for small-medium businesses

Enterprise - Commercial, all features


SQL Language Categories

DDL (Data Definition Language)

Define and modify database structure

DML (Data Manipulation Language)

Manipulate data in tables

DCL (Data Control Language)

Control access permissions

TCL (Transaction Control Language)

Manage transactions


Data Types in SQL Server

Numeric Types

String Types

Date and Time Types

Binary Types

Other Types


DDL - Data Definition Language

CREATE TABLE

ALTER TABLE

DROP TABLE

TRUNCATE TABLE


DML - Data Manipulation Language

SELECT - Query Data

Basic SELECT

WHERE Clause - Filter Rows

ORDER BY - Sort Results

TOP / OFFSET-FETCH - Limit Results

DISTINCT - Unique Values

INSERT - Add Data

UPDATE - Modify Data

DELETE - Remove Data


Joins - Combining Tables

INNER JOIN

LEFT JOIN (LEFT OUTER JOIN)

RIGHT JOIN (RIGHT OUTER JOIN)

FULL OUTER JOIN

CROSS JOIN

Join Comparison Table


Subqueries

Scalar Subquery (Returns single value)

Multi-value Subquery (Returns multiple values)

Correlated Subquery (References outer query)

Derived Table (Subquery in FROM)


Common Table Expressions (CTEs)

Basic CTE

Recursive CTE


Window Functions

ROW_NUMBER - Assign unique row numbers

RANK and DENSE_RANK - Ranking with ties

Aggregate Window Functions

LAG and LEAD - Access previous/next rows

FIRST_VALUE and LAST_VALUE


Aggregate Functions

Basic Aggregates

GROUP BY

HAVING - Filter Groups

String Aggregation (SQL Server 2017+)


Stored Procedures

Basic Stored Procedure

Procedure with Multiple Parameters

Procedure with OUTPUT Parameters

Procedure with Error Handling

Procedure with Dynamic SQL


Functions

Scalar Functions (Return single value)

Table-Valued Functions (Return table)


Triggers

AFTER Triggers (Fire after operation)

INSTEAD OF Triggers (Override operation)

Trigger Management


Transactions and Locking

Basic Transactions

Transaction with Error Handling

Savepoints

Isolation Levels

Lock Types


Indexes (Brief Overview)

Index Types


Built-in Functions

String Functions

Date Functions

Conversion Functions

Math Functions

NULL Handling

JSON Functions (SQL Server 2016+)


Common Table Patterns

Pagination

Deduplication

Running Totals

Pivot and Unpivot

Merge (Upsert)


Best Practices

1. Always Use WHERE in UPDATE/DELETE

2. Use Parameterized Queries (Prevent SQL Injection)

3. Use Appropriate Data Types

4. Use NVARCHAR for Unicode

5. Add Proper Constraints

6. Use Transactions for Multiple Operations

7. Use EXISTS Instead of COUNT(*) > 0

8. Use SET NOCOUNT ON in Procedures

9. Use Schema Names

10. Comment Complex Queries


Common Pitfalls

1. SELECT *

2. Not Using WHERE in DELETE/UPDATE

3. NOLOCK Misuse

4. Implicit Conversion

5. Functions in WHERE (Non-Sargable)

6. Not Handling NULLs

7. Cursor Overuse


Quick Reference Tables

JOIN Types Comparison

Join Type
Description
Returns

INNER JOIN

Matching rows only

Rows that exist in both tables

LEFT JOIN

All from left + matching

All left rows + matching right (NULL if no match)

RIGHT JOIN

All from right + matching

All right rows + matching left (NULL if no match)

FULL JOIN

All from both

All rows from both (NULL where no match)

CROSS JOIN

Cartesian product

Every combination of rows

Aggregate Functions

Function
Purpose
Example

COUNT(*)

Count all rows

COUNT(*) = 100

COUNT(col)

Count non-NULL

COUNT(Phone)

SUM(col)

Sum values

SUM(Price)

AVG(col)

Average

AVG(Price)

MIN(col)

Minimum

MIN(Price)

MAX(col)

Maximum

MAX(Price)

STRING_AGG

Concatenate

STRING_AGG(Name, ', ')

Window Functions

Function
Purpose
Example

ROW_NUMBER()

Unique row number

ROW_NUMBER() OVER (ORDER BY Price)

RANK()

Rank with gaps

RANK() OVER (ORDER BY Price DESC)

DENSE_RANK()

Rank no gaps

DENSE_RANK() OVER (ORDER BY Price DESC)

NTILE(n)

Divide into n groups

NTILE(4) OVER (ORDER BY Price)

LAG()

Previous row

LAG(Price, 1) OVER (ORDER BY Date)

LEAD()

Next row

LEAD(Price, 1) OVER (ORDER BY Date)

SUM() OVER

Running total

SUM(Amount) OVER (ORDER BY Date)

Isolation Levels

Level
Dirty Read
Non-Repeatable Read
Phantom Read
Performance

READ UNCOMMITTED

✅ Yes

✅ Yes

✅ Yes

⚡ Fastest

READ COMMITTED (Default)

❌ No

✅ Yes

✅ Yes

⚡⚡ Fast

REPEATABLE READ

❌ No

❌ No

✅ Yes

⚡ Slower

SERIALIZABLE

❌ No

❌ No

❌ No

🐌 Slowest

SNAPSHOT

❌ No

❌ No

❌ No

⚡⚡ Fast (versions)

Constraint Types

Constraint
Purpose
Example

PRIMARY KEY

Unique identifier

CustomerId INT PRIMARY KEY

FOREIGN KEY

Reference another table

FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)

UNIQUE

Unique values

Email NVARCHAR(100) UNIQUE

CHECK

Validate values

CHECK (Price >= 0)

DEFAULT

Default value

DEFAULT GETDATE()

NOT NULL

Require value

FirstName NVARCHAR(50) NOT NULL


T-SQL Query Execution Order


Decision Tree: What Query Should I Write?


Guide Complete! This comprehensive SQL Server & T-SQL guide covers fundamentals, DDL, DML, joins, subqueries, CTEs, window functions, stored procedures, functions, triggers, transactions, and best practices. Master these concepts and you'll be well-prepared for any backend interview! 🎯

Last updated