Showing posts with label Sql Server. Show all posts
Showing posts with label Sql Server. Show all posts

Wednesday, July 1, 2026

SQL Query & Stored Procedure Optimization: A Complete Guide for Developers

 


Whether you're a beginner or an experienced SQL Server developer, writing optimized SQL queries and stored procedures is essential for building high-performance applications. Poorly written queries can lead to slow response times, high CPU usage, excessive memory consumption, and unnecessary disk I/O.

In this article, we'll explore practical techniques to optimize SQL queries and stored procedures, helping you improve database performance and prepare for SQL Server interviews.


Why SQL Query Optimization Matters

As applications grow, databases often become the biggest performance bottleneck. Optimized SQL queries provide several benefits:

  • Faster query execution

  • Reduced CPU and memory usage

  • Lower disk I/O

  • Better scalability

  • Improved user experience

  • Reduced server costs

Let's look at some proven optimization techniques.


1. Create Proper Indexes

Indexes help SQL Server locate data quickly without scanning the entire table.

Before (Table Scan)

SELECT *
FROM Employees
WHERE Department = 'IT';

If the Department column is not indexed, SQL Server performs a table scan.

Create an Index

CREATE INDEX IX_Employees_Department
ON Employees(Department);

After creating the index, SQL Server can perform an Index Seek, which is significantly faster.


2. Avoid Using SELECT *

Although SELECT * is convenient, it retrieves every column from the table—even when you don't need them.

Avoid

SELECT *
FROM Employees;

Use

SELECT EmployeeId, Name, Salary
FROM Employees;

Benefits

  • Reduces network traffic

  • Improves query performance

  • Lowers memory usage


3. Filter Data with WHERE Clause

Always retrieve only the rows you actually need.

Avoid

SELECT *
FROM Orders;

Use

SELECT OrderId, CustomerId
FROM Orders
WHERE OrderDate >= '2026-01-01';

Filtering reduces unnecessary data processing.


4. Don't Use Functions in WHERE Clauses

Applying functions on indexed columns prevents SQL Server from using indexes efficiently.

Avoid

SELECT *
FROM Employees
WHERE YEAR(HireDate) = 2025;

Use

SELECT *
FROM Employees
WHERE HireDate >= '2025-01-01'
AND HireDate < '2026-01-01';

This allows SQL Server to utilize indexes effectively.


5. Prefer EXISTS Over IN

For large datasets, EXISTS often performs better than IN.

Instead of

SELECT *
FROM Customers
WHERE CustomerId IN
(
    SELECT CustomerId
    FROM Orders
);

Use

SELECT *
FROM Customers C
WHERE EXISTS
(
    SELECT 1
    FROM Orders O
    WHERE O.CustomerId = C.CustomerId
);

6. Use JOINs Instead of Nested Subqueries

JOINs are generally more efficient and easier to read.

SELECT E.Name
FROM Employees E
INNER JOIN Departments D
ON E.DepartmentId = D.DepartmentId
WHERE D.DepartmentName = 'IT';

7. Choose Appropriate Data Types

Selecting the correct data type reduces storage requirements and improves performance.

Avoid

Salary VARCHAR(100)

Use

Salary DECIMAL(18,2)

Always use the smallest suitable data type.


8. Avoid Cursors

Cursors process rows one at a time, making them slow for large datasets.

Avoid

DECLARE EmployeeCursor CURSOR
FOR
SELECT EmployeeId
FROM Employees;

Use Set-Based Operations

UPDATE Employees
SET Salary = Salary + 1000
WHERE Department = 'IT';

Set-based operations are much faster and more scalable.


9. Retrieve Only Required Rows

Instead of loading an entire table:

SELECT *
FROM Employees;

Retrieve only what you need.

SELECT TOP 10 *
FROM Employees;

10. Implement Pagination

For applications displaying large datasets, pagination improves performance.

SELECT *
FROM Employees
ORDER BY EmployeeId
OFFSET 0 ROWS
FETCH NEXT 20 ROWS ONLY;

This is commonly used in web applications with paging.


11. Avoid Leading Wildcards

Avoid

WHERE Name LIKE '%John';

Use

WHERE Name LIKE 'John%';

Leading wildcards prevent SQL Server from efficiently using indexes.


12. Avoid DISTINCT When Unnecessary

DISTINCT requires SQL Server to eliminate duplicate rows, which adds extra processing.

Only use it when duplicates actually exist.


13. Prefer UNION ALL Over UNION

UNION removes duplicate rows, requiring additional sorting.

SELECT Name FROM A
UNION ALL
SELECT Name FROM B;

Use UNION ALL whenever duplicate removal isn't required.


14. Use Parameterized Stored Procedures

Avoid dynamic SQL whenever possible.

CREATE PROCEDURE GetEmployee
    @EmployeeId INT
AS
BEGIN
    SELECT *
    FROM Employees
    WHERE EmployeeId = @EmployeeId;
END

Benefits include:

  • Better security

  • Reusable execution plans

  • Improved performance


15. Minimize Dynamic SQL

Dynamic SQL increases complexity and can affect execution plan reuse.

Prefer static SQL unless dynamic behavior is absolutely necessary.


16. Keep Transactions Short

Long-running transactions hold locks longer, increasing blocking.

Good Example

BEGIN TRANSACTION;

UPDATE Employees
SET Salary = Salary + 1000;

COMMIT;

Complete transactions as quickly as possible.


17. Use SET NOCOUNT ON

Add this to the beginning of stored procedures.

SET NOCOUNT ON;

It prevents unnecessary row count messages from being returned to the client, reducing network traffic.


18. Avoid Nested Loops in T-SQL

Instead of processing records row by row, use joins.

SELECT *
FROM Employees E
JOIN Departments D
ON E.DepartmentId = D.DepartmentId;

Set-based operations are almost always more efficient.


19. Analyze the Execution Plan

SQL Server's Execution Plan helps identify performance bottlenecks.

Look for:

  • Table Scan

  • Index Scan

  • Index Seek

  • Key Lookup

  • Missing Index suggestions

  • Expensive operators

Understanding execution plans is one of the most valuable SQL optimization skills.


20. Keep Statistics Updated

Statistics help SQL Server choose the best execution plan.

EXEC sp_updatestats;

Or update a specific table.

UPDATE STATISTICS Employees;

21. Rebuild or Reorganize Indexes

Over time, indexes become fragmented.

Rebuild

ALTER INDEX ALL
ON Employees
REBUILD;

Reorganize

ALTER INDEX ALL
ON Employees
REORGANIZE;

Regular index maintenance improves query performance.


22. Best Practices for Stored Procedures

When writing stored procedures:

  • Use parameters

  • Return only required columns

  • Avoid unnecessary business logic

  • Keep procedures focused

  • Use proper indexing

  • Use SET NOCOUNT ON

  • Write readable and maintainable SQL

Example:

CREATE PROCEDURE GetEmployees
    @Department VARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT EmployeeId,
           Name,
           Salary
    FROM Employees
    WHERE Department = @Department;
END

Common SQL Performance Interview Questions

Q: What is the difference between a Clustered Index and a Non-Clustered Index?

A Clustered Index determines the physical order of data in a table, while a Non-Clustered Index stores key values separately with pointers to the actual data.


Q: What is an Execution Plan?

An Execution Plan shows how SQL Server executes a query and helps identify performance bottlenecks.


Q: What is the difference between an Index Seek and a Table Scan?

An Index Seek uses an index to locate data efficiently, whereas a Table Scan reads every row in the table.


*Q: Why should you avoid SELECT ?

Because it retrieves unnecessary columns, increasing I/O, memory usage, and network traffic.


Q: Why use SET NOCOUNT ON?

It suppresses row count messages, reducing unnecessary network communication.


Q: How do you identify slow queries?

Use:

  • Execution Plans

  • SET STATISTICS IO ON

  • SET STATISTICS TIME ON

  • Query Store

  • SQL Server Dynamic Management Views (DMVs)


Final Thoughts

SQL optimization is not just about making queries faster—it's about designing efficient, scalable, and maintainable database solutions. By following these best practices, you can significantly improve application performance, reduce resource consumption, and build reliable enterprise applications.

Whether you're preparing for SQL Server interviews or working on production systems, mastering these optimization techniques will make you a more effective database developer.


If you found this article helpful, share it with your fellow developers and follow the blog for more tutorials on SQL Server, Azure DevOps, .NET, C#, Angular, and Full Stack Development.

Thursday, June 25, 2026

Top 100 C# Interview Questions and Answers for 2026

 

Introduction

C# (C-Sharp) is one of the most popular programming languages used for building desktop applications, web applications, APIs, cloud solutions, mobile apps, and enterprise software. If you're preparing for a C# developer interview, these frequently asked questions will help you strengthen your fundamentals and advanced concepts.


Basic C# Interview Questions

1. What is C#?

C# is an object-oriented programming language developed by Microsoft for building applications on the .NET platform.

2. What are the key features of C#?

  • Object-Oriented

  • Type-Safe

  • Automatic Garbage Collection

  • Rich Library Support

  • Language Interoperability

  • Scalability

3. What is .NET?

.NET is a software development framework created by Microsoft for building and running applications.

4. What is CLR?

CLR (Common Language Runtime) is the execution engine of .NET that manages memory, exceptions, and security.

5. What is CTS?

CTS (Common Type System) defines how data types are declared and used in .NET.

6. What is CLS?

CLS (Common Language Specification) defines rules that .NET languages must follow to ensure interoperability.

7. What is managed code?

Code executed under CLR supervision.

8. What is unmanaged code?

Code executed directly by the operating system without CLR.

9. What is JIT Compiler?

Just-In-Time Compiler converts Intermediate Language (IL) into machine code at runtime.

10. What is MSIL?

Microsoft Intermediate Language generated after compiling C# code.


OOP Concepts

11. What is Object-Oriented Programming?

A programming paradigm based on objects and classes.

12. What are the four pillars of OOP?

  • Encapsulation

  • Inheritance

  • Polymorphism

  • Abstraction

13. What is a Class?

A blueprint for creating objects.

14. What is an Object?

An instance of a class.

15. What is Encapsulation?

Binding data and methods together while restricting direct access.

16. What is Inheritance?

The ability to derive a class from another class.

17. What is Polymorphism?

The ability of a method to perform different tasks based on context.

18. What is Abstraction?

Hiding implementation details and exposing only essential functionality.

19. What is Method Overloading?

Multiple methods with the same name but different parameters.

20. What is Method Overriding?

Providing a new implementation of a base class method.


Data Types

21. What are Value Types?

Stored directly in memory.

Examples:

  • int

  • double

  • bool

  • char

22. What are Reference Types?

Store references to memory locations.

Examples:

  • class

  • string

  • object

  • array

23. Difference between Value Type and Reference Type?

Value types store actual data, reference types store memory addresses.

24. What is Boxing?

Converting a value type into an object type.

25. What is Unboxing?

Converting an object type back into a value type.

26. What is Nullable Type?

Allows value types to store null values.

Example:

int? age = null;

27. What is var?

Allows implicit type declaration.

28. What is dynamic?

Type checking occurs at runtime.

29. Difference between var and dynamic?

var is checked at compile time, dynamic at runtime.

30. What is object data type?

Base type for all .NET types.


Exception Handling

31. What is Exception Handling?

Mechanism to handle runtime errors.

32. What are try, catch, and finally blocks?

Used to detect and handle exceptions.

33. What is throw keyword?

Used to raise an exception manually.

34. What is custom exception?

User-defined exception class.

35. Difference between throw and throw ex?

throw preserves stack trace; throw ex resets it.


Access Modifiers

36. What are access modifiers?

Keywords controlling visibility.

37. What is public?

Accessible from anywhere.

38. What is private?

Accessible only within the class.

39. What is protected?

Accessible within derived classes.

40. What is internal?

Accessible within the same assembly.


Constructors and Destructors

41. What is a Constructor?

Special method called when an object is created.

42. Types of Constructors?

  • Default

  • Parameterized

  • Static

  • Copy

43. What is Static Constructor?

Executes only once per class.

44. Can constructors be overloaded?

Yes.

45. What is Destructor?

Used for cleanup before object destruction.


Collections

46. What is Array?

Fixed-size collection of elements.

47. What is ArrayList?

Dynamic collection storing any type.

48. What is List?

Generic dynamic collection.

49. Difference between Array and List?

List can grow dynamically.

50. What is Dictionary?

Stores key-value pairs.

51. What is Hashtable?

Non-generic key-value collection.

52. Difference between Dictionary and Hashtable?

Dictionary is generic and type-safe.

53. What is Queue?

FIFO collection.

54. What is Stack?

LIFO collection.

55. What is HashSet?

Stores unique values only.


String Handling

56. Is string a value type or reference type?

Reference type.

57. What is StringBuilder?

Used for efficient string manipulation.

58. Difference between String and StringBuilder?

String is immutable; StringBuilder is mutable.

59. What is string interpolation?

Embedding expressions inside strings.

Example:

$"Hello {name}"

60. What is verbatim string?

String prefixed with @.


Delegates and Events

61. What is Delegate?

Type-safe function pointer.

62. What are Events?

Mechanism for notification.

63. Difference between Delegate and Event?

Events provide controlled delegate access.

64. What is Action Delegate?

Represents methods returning void.

65. What is Func Delegate?

Represents methods returning a value.


LINQ

66. What is LINQ?

Language Integrated Query for querying collections.

67. Benefits of LINQ?

  • Readability

  • Less Code

  • Strong Typing

68. What is Lambda Expression?

Anonymous function syntax.

Example:

x => x > 10

69. What is Deferred Execution?

Query executes only when results are requested.

70. Difference between IEnumerable and IQueryable?

IEnumerable works in memory; IQueryable executes against data source.


Advanced C#

71. What is Interface?

Contract containing method declarations.

72. Can an interface contain implementation?

Yes, using default interface methods in newer versions.

73. What is Abstract Class?

Class that cannot be instantiated directly.

74. Difference between Interface and Abstract Class?

Interfaces define contracts; abstract classes can provide implementation.

75. Can a class inherit multiple classes?

No.

76. Can a class implement multiple interfaces?

Yes.

77. What is Sealed Class?

Class that cannot be inherited.

78. What is Partial Class?

Class definition split across multiple files.

79. What is Extension Method?

Adds methods to existing types.

80. What is Reflection?

Ability to inspect metadata at runtime.


Memory Management

81. What is Garbage Collection?

Automatic memory cleanup process.

82. What are Generations in GC?

  • Generation 0

  • Generation 1

  • Generation 2

83. What is IDisposable?

Interface for releasing unmanaged resources.

84. What is using statement?

Ensures resource disposal.

85. What is Finalize method?

Called by GC before object removal.


Multithreading

86. What is Thread?

Smallest execution unit.

87. What is Multithreading?

Running multiple threads simultaneously.

88. What is Task?

Higher-level abstraction for asynchronous work.

89. What is async and await?

Keywords for asynchronous programming.

90. Difference between Thread and Task?

Tasks are lightweight and managed by the thread pool.


ASP.NET and .NET Core

91. What is ASP.NET?

Framework for web applications.

92. What is ASP.NET Core?

Cross-platform web framework.

93. What is Middleware?

Component that processes HTTP requests.

94. What is Dependency Injection?

Technique for providing dependencies externally.

95. What is REST API?

Architectural style for web services.


Modern C# Features

96. What are Records?

Reference types designed for immutable data.

97. What is Pattern Matching?

Feature for checking object structure and type.

98. What is Nullable Reference Type?

Helps prevent null reference exceptions.

99. What is Global Using?

Allows project-wide namespace imports.

100. What are Top-Level Statements?

Enable writing simple programs without a Program class.


Conclusion

These Top 100 C# Interview Questions cover fundamentals, OOP concepts, collections, LINQ, delegates, multithreading, memory management, ASP.NET Core, and modern C# features. Mastering these questions will significantly improve your confidence in technical interviews for Junior, Mid-Level, and Senior C# Developer positions.

Tuesday, September 23, 2025

DELETE vs TRUNCATE vs DROP in SQL Server

 1. DELETE

  • Used to remove rows one at a time from a table.

  • Can be filtered with WHERE clause.

  • Each deleted row is logged in transaction log (slower).

  • Identity column value does not reset unless explicitly used with DBCC CHECKIDENT.

  • Can be rolled back if inside a transaction.

✅ Example:

DELETE FROM Employees WHERE DeptId = 2;

2. TRUNCATE

  • Removes all rows from a table (no WHERE).

  • Logs only page deallocations (faster than DELETE).

  • Resets identity column to seed value.

  • Cannot be used if:

    • Table is referenced by a foreign key.

    • Indexed views exist on the table.

  • Can be rolled back if inside a transaction.

✅ Example:

TRUNCATE TABLE Employees;

3. DROP

  • Deletes the entire table structure and data.

  • Table definition, constraints, indexes, triggers — all removed.

  • Cannot be rolled back (once committed).

  • After DROP, table is gone from database; must be recreated to use again.

✅ Example:

DROP TABLE Employees;

4. Key Differences Table

FeatureDELETETRUNCATEDROP
RemovesSpecific rows (WHERE) or allAll rowsEntire table (structure + data)
WHERE Clause✅ Allowed❌ Not allowed❌ Not applicable
LoggingRow-by-row (slow)Minimal logging (fast)Logs table removal
Identity Reset❌ No✅ Yes❌ Not applicable
Rollback Possible✅ Yes✅ Yes❌ No (unless inside transaction)
Foreign Key Restriction✅ Allowed❌ Not allowed if referenced✅ Allowed (but drops constraints)
Table Structure Exists?✅ Yes (after delete)✅ Yes (empty table)❌ No (removed completely)
SpeedSlower (row-by-row)Faster (deallocate pages)Fastest (drops object)

5. When to Use?

  • DELETE → When you need to remove specific rows or want triggers to fire.

  • TRUNCATE → When you want to remove all rows quickly and reset identity.

  • DROP → When you want to completely remove table and free space.


6. Interview Tip

If interviewer asks:
👉 “Can we rollback TRUNCATE?”
✅ Answer: Yes, TRUNCATE can be rolled back if executed inside a transaction.

BEGIN TRAN; TRUNCATE TABLE Employees; ROLLBACK; -- restores data

👉 “Why TRUNCATE is faster than DELETE?”
✅ Answer: Because TRUNCATE logs only extent (page) deallocation, while DELETE logs each row removal.

Don't Copy

Protected by Copyscape Online Plagiarism Checker