0% found this document useful (0 votes)
13 views71 pages

Essential Interview Questions for .NET & SQL

The document contains a comprehensive list of interview questions and answers related to software development, focusing on topics such as N-tier architecture, state management techniques, SQL joins, and various programming concepts in C#. It covers both theoretical explanations and practical examples, making it a useful resource for candidates preparing for technical interviews in software engineering roles.

Uploaded by

merupulapraveen5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views71 pages

Essential Interview Questions for .NET & SQL

The document contains a comprehensive list of interview questions and answers related to software development, focusing on topics such as N-tier architecture, state management techniques, SQL joins, and various programming concepts in C#. It covers both theoretical explanations and practical examples, making it a useful resource for candidates preparing for technical interviews in software engineering roles.

Uploaded by

merupulapraveen5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interview Questions & Answers

[Link] is N-tier Architecture and why we used ?

2. What is State management Techniques ?

3. What is Joins & it's types ?

4. What is View State ?

5. What is Hidden Filed ?

6. What is Index in SQL ?

7. How to Optimize Sql Performance ?

8. What is Access Modifiers ?

9. What is Data types in Sql ?

10. What is View In Sql ?

11. If Page Load is taking to much of time what action you take ?

12. What is code Reusability ?

13. What is Common Table Expression (CTE) in Sql ?

---------HDFC----------

[Link] in brief your project

[Link] is session?

[Link] is nested if else can write if inside if?

[Link] is for and foreach loop?

[Link] is do while and while loop?write syntax?

[Link] class and normal class?

[Link] pattern? and Types ?

[Link] repositery design pattern?

[Link] is cont and readonly keyword?

[Link] is boxing and unboxing?

[Link] is abstract class and interface ? Interface have 2 method it is mandatory to implement?

[Link] overriding write code?

[Link] many primary key constraint create on same table?

[Link] key? Candidate key?

[Link] to find last generated identity column value? What are ways?

[Link] catch block in c#? Can we write try without catch? If Yes then how?

Sahil
Interview Questions & Answers

HDFC ERGO interview Question

30. What is SQL & types of SQL ?

31. How to Connect SQL with .Net web Application where it's assign [Link] file with give
Connection String ?

[Link] many finally block writes?

[Link] Session variable and application variable?

34. What is SQL Clauses ?

35. What is IN & OUT Parameter in SQL ?

36. Difference Between Stored Procedures & Functions ?

37. What is Task Scheduler ?

38. How to Used Task Scheduler in Stored Procedures ?

39. What is DML Opration ?

40. What is Validators in [Link] & Types ?

41. Use of Regular Expression Validator in [Link] ?

42. What is CLR ?

43. What is ref & OUT keyword ?

44. What is Boxing & Unboxing ?

[Link] to find nth highest salary and write SQL query ?

[Link] is store procedure and write query ?

[Link] query of backup table ?

[Link] is state management techniques in [Link] ?

[Link] a column have already unique key constraint can we apply foreign key to same column ?

[Link] call Store procedure using select statement ?

[Link] class

[Link] between store procedure and functions ?

[Link] to transfer data one page to another page in [Link] ?

[Link] is the use of var keyword ?

[Link] is forloop and foreach loop ?

[Link] Do while and while ?

[Link] is having clause ?


Sahil
Interview Questions & Answers

[Link] a duplicate #Back-up table.

59. if you have 10 data in the data table you have to delete 9 data, what will be.. the count?

[Link] we create a table using a stored procedure?

[Link] between [Link] & Asp. Det Core?

[Link] is the [Link] File?

[Link] is middleware?

[Link] the use of Run(), Use() map() methods?

[Link] is Routing in the .net core?

[Link] to do Session management? difference between Viewbag & viewdata

[Link] is the use of app_start file?

68. what is the use of [Link]?

[Link] to execute sp.

[Link] count (*) from employee

71. Select count (8) from employee

72. select count (0) from

[Link] a table 5 record in another table 0 record , cross join.

74. trigger

75. primary, unique key

--------------SQL--------

76. types of joins

77. diff between function and stored proceure

78. statemaster (table) statename (colum)

Statecode (colum)

[Link] the statename duplicate values count. (Write query)

80. diff between primary key, unique key

81. what is view bag?

82. connected architecture and non connected architecture

[Link] count (*) from employee

84. Select count (8) from employee

[Link] count (0) from employee which is correct? What is output?

Sahil
Interview Questions & Answers

[Link] example

[Link] Oops concept with example

[Link] with code example

[Link] to class called?

[Link] are Aggregate functions and name any 5 of them and explain.

91. Explain Unique Key vs Primary Key .Can Primary key store null value?Can Unique Key can store
null value , if yes can unique can store multiple values?

92. What are triggers ? And Explain its use

93. What is copy table ? And how many types of temporary are there in Sql.

94. Difference between const and readonly key word in C#

[Link] Error Handling in c#

[Link] is connected and Disconnected

97. Explain [Link] page life cycle.

98. How you will consume Web API

99. If there are multiple catch blocks are there , which one will be executed first and last.

100. what is the function and store procedure

In details? Explain in brief. Where to use why to use?

101. are you writing queries in sql?v

102. types of functions? Aggregate function?

103. can you please explain in the count,max,and min.

104. what is the use of drop keywords?

105. difference between drop and truncate

106. where to use function? and which kind of function do you create?

107. how to execute the store procedure?

--C#--

108. how to implement encapsulation?

109. what is out and ref?

110. if I have one store procedure and I need to display it on the front end side? which kind of steps I
followed?

Sahil
Interview Questions & Answers

111. what is static?

112. what is access modifires? And there types?

113. what is [Link] controls?

114. what is continuous and discontinues?

[Link] count(*) from employee and select count (0) from employee what will be output of both
query?

[Link] value returns UDF function?Sql

[Link] of join?what is cross join? support I have table A and table B table A jas 4 rows and table B
is 0 rows write cross join ? What is output?

[Link] 4 largest employeeid without using CTE and ranking function?

[Link] query employee table have name column in that multiple names are different we want
delete duplicate name write query?

[Link] is trigger? Write syntax? Types of trigger?? Where exactly used in project?

[Link] use partition by clause?

1. What is N-tier Architecture and why we used?


N-tier Architecture

N-tier architecture (also called multi-tier architecture) is a software design pattern that
separates an application into multiple logical layers (or tiers), each serving a specific purpose.
The most common implementation is the 3-tier architecture, but there can be more layers
depending on complexity.

Key Layers in N-tier Architecture

1. Presentation Layer (UI)


o This is the front-end layer where users interact with the application.
o Examples: Web pages, mobile apps, or desktop GUIs.
2. Business Logic Layer (BLL)
o Contains core business logic, rules, and processing.
o Acts as a bridge between the UI and Data Access Layer.
3. Data Access Layer (DAL)
o Handles database interactions like CRUD operations.
o Ensures data consistency and abstraction from the database logic.
4. Database Layer
o Stores data in a structured format (e.g., SQL Server, MySQL, MongoDB).

Sahil
Interview Questions & Answers

Why Use N-tier Architecture?

✅ Separation of Concerns

• Each layer handles its specific responsibility, improving code organization and
maintainability.

✅ Scalability

• Allows individual layers to scale independently for improved performance.

✅ Reusability

• Business logic and data access code can be reused across multiple applications or services.

✅ Flexibility

• Easier to replace or upgrade specific layers without affecting the entire application.

✅ Security

• Critical logic and database access can be isolated from the UI, reducing security risks.

✅ Testability

• Isolated layers make unit testing more effective and manageable.

Example in .NET Core Using Entity Framework

In your .NET Core project with EF Core, your structure may look like this:

/PresentationLayer ([Link] Core MVC/Blazor)


/BusinessLogicLayer (Service classes, validation, etc.)
/DataAccessLayer (EF Core DbContext, repositories)
/Database (SQL Server, PostgreSQL, etc.)

2. What is State management Techniques?


State Management Techniques

State management refers to the process of preserving and managing the state (data) of an
application across multiple requests, pages, or user interactions. This is crucial in web
applications because HTTP is stateless by default, meaning each request is independent and
doesn’t retain information about previous requests.

Sahil
Interview Questions & Answers

Types of State Management Techniques

State management techniques are generally categorized into two types:

1. Client-Side State Management

Data is stored directly on the client's browser. Common techniques include:

✅ Cookies

• Small text files stored in the browser.


• Useful for storing small amounts of data for extended periods.
• Example: Authentication tokens, user preferences.

✅ Local Storage

• Stores data with no expiration date.


• Data persists even after the browser is closed.
• Example: Saving theme settings or user profile details.

✅ Session Storage

• Similar to localStorage, but data is cleared when the browser tab is closed.
• Useful for temporary data like form entries.

✅ IndexedDB / Web SQL

• Advanced database system in the browser for handling larger data sets.
• Example: Storing offline application data.

✅ Hidden Fields

• Hidden <input> fields in HTML forms that retain data across requests.
• Useful for storing small amounts of data in form submissions.

2. Server-Side State Management

Data is stored on the server, offering better security and centralized control.

✅ Session State

• Data is stored on the server, and a session ID is sent to the client (usually via cookies).
• Suitable for storing user-specific data securely.

✅ Application State

• Data shared across all users in the application (e.g., app-wide settings).
Sahil
Interview Questions & Answers

✅ Cache

• Frequently accessed data is stored temporarily for faster retrieval.


• Common tools: MemoryCache, Redis, etc.

✅ Database

• Storing state in a database is useful for long-term persistence.


• Example: Saving shopping cart details for logged-in users.

Example in .NET Core

Session State in [Link] Core

// Configure Session in [Link]


public void ConfigureServices(IServiceCollection services)
{
[Link]();
}

public void Configure(IApplicationBuilder app)


{
[Link]();
}

// Controller Example
public class HomeController : Controller
{
public IActionResult Index()
{
[Link]("Username", "JohnDoe");
return View();
}

public IActionResult GetUser()


{
var username = [Link]("Username");
return Content($"Hello, {username}!");
}
}

[Link] is Joins & it's types?


Joins in SQL

A JOIN in SQL is used to combine rows from two or more tables based on a related column
between them. Joins are essential when working with relational databases to retrieve
meaningful data from multiple tables.

Sahil
Interview Questions & Answers

Types of Joins in SQL

SQL supports several types of joins, each serving different data retrieval needs:

1. INNER JOIN (or simply JOIN)

• Returns only the rows that have matching values in both tables.
• Commonly used when you need data that exists in both tables.

Syntax:

SELECT A.Column1, B.Column2


FROM TableA A
INNER JOIN TableB B
ON [Link] = [Link];

Example Output:

| EmployeeID | EmployeeName | DepartmentName |


|-------------|---------------|-----------------|
| 1 | John Doe | HR |
| 2 | Jane Smith | IT |

2. LEFT JOIN (LEFT OUTER JOIN)

• Returns all rows from the left table, plus matching rows from the right table.
• If no match is found, NULL values are returned for columns from the right table.

Syntax:

SELECT A.Column1, B.Column2


FROM TableA A
LEFT JOIN TableB B
ON [Link] = [Link];

Example Output:

| EmployeeID | EmployeeName | DepartmentName |


|-------------|---------------|-----------------|
| 1 | John Doe | HR |
| 2 | Jane Smith | IT |
| 3 | Alex Johnson | NULL |

3. RIGHT JOIN (RIGHT OUTER JOIN)

• Returns all rows from the right table, plus matching rows from the left table.
• If no match is found, NULL values are returned for columns from the left table.

Syntax:

SELECT A.Column1, B.Column2


Sahil
Interview Questions & Answers
FROM TableA A
RIGHT JOIN TableB B
ON [Link] = [Link];

Example Output:

| EmployeeID | EmployeeName | DepartmentName |


|-------------|---------------|-----------------|
| 1 | John Doe | HR |
| 2 | Jane Smith | IT |
| NULL | NULL | Finance |

4. FULL JOIN (FULL OUTER JOIN)

• Combines the results of both LEFT JOIN and RIGHT JOIN.


• Returns all rows when there’s a match in either table. Non-matching rows are filled with
NULL.

Syntax:

SELECT A.Column1, B.Column2


FROM TableA A
FULL JOIN TableB B
ON [Link] = [Link];

Example Output:

| EmployeeID | EmployeeName | DepartmentName |


|-------------|---------------|-----------------|
| 1 | John Doe | HR |
| 2 | Jane Smith | IT |
| 3 | Alex Johnson | NULL |
| NULL | NULL | Finance |

5. CROSS JOIN

• Returns the Cartesian product of both tables — every row from the first table is combined
with every row from the second table.

Syntax

SELECT A.Column1, B.Column2


FROM TableA A
CROSS JOIN TableB B;

Example Output (with 3 rows in each table):

| EmployeeID | DepartmentName |
|-------------|-----------------|
| 1 | HR |
| 1 | IT |
| 1 | Finance |

Sahil
Interview Questions & Answers
| 2 | HR |
| 2 | IT |
| 2 | Finance |

6. SELF JOIN

• A join where a table is joined with itself.


• Often used to represent hierarchical data (e.g., employee-manager relationships).

Syntax:

SELECT [Link] AS Employee, [Link] AS Manager


FROM Employees A
INNER JOIN Employees B
ON [Link] = [Link];

Key Differences Summary


Join Type Description Rows Returned

INNER JOIN Only matching rows Matches only

LEFT JOIN All rows from the left table + matches Left table + Matches

RIGHT JOIN All rows from the right table + matches Right table + Matches

FULL JOIN All rows from both tables All data (matches + unmatched)

CROSS JOIN Cartesian product of both tables Total rows = Rows(A) × Rows(B)

SELF JOIN Table joined with itself Varies based on condition

Which Join to Use?

• Use INNER JOIN for precise data matching.


• Use LEFT JOIN if the left table's data is mandatory.
• Use RIGHT JOIN if the right table's data is mandatory.
• Use FULL JOIN for comprehensive data inclusion.

[Link] is View State?


ViewState is a client-side state management technique used in [Link] Web Forms to
preserve the state of controls between post backs (server round-trips).

Since HTTP is stateless, ViewState helps maintain the values of UI controls (like textboxes,
dropdowns, etc.) so that data isn’t lost when the page reloads after a postback.
Sahil
Interview Questions & Answers

How Does ViewState Work?

• ViewState stores data in a hidden <input> field with the name __VIEWSTATE.
• This hidden field is automatically included in the HTML markup of the page.
• Data stored in ViewState is Base64-encoded, making it harder to read but not encrypted by
default.

Example of ViewState in [Link] Web Forms

ASPX Page:

<asp:TextBox ID="txtName" runat="server" />


<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblResult" runat="server" />

Code-Behind (C#):

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
ViewState["PageVisitCount"] = 0;
}
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
int count = (int)ViewState["PageVisitCount"] + 1;
ViewState["PageVisitCount"] = count;

[Link] = $"Hello, {[Link]}! You've submitted {count}


times.";
}

Flow:

• On the first page load (!IsPostBack), ViewState["PageVisitCount"] is initialized to


0.
• Each time the button is clicked, the count increments and persists because of ViewState.

Advantages of ViewState

✅ Simple Implementation: No extra configuration is required; ViewState is enabled by


default.
✅ Automatic Control Management: Maintains the state of controls without additional
code.

Sahil
Interview Questions & Answers

✅ No Server Resources Needed: Data is stored on the client-side, reducing server memory
usage.

Disadvantages of ViewState

❌ Increased Page Size: Since data is stored in the page itself, large ViewState data can
slow down performance.
❌ Security Risk: ViewState is Base64-encoded but not encrypted by default. Sensitive
data should be avoided.
❌ Limited to Same Page: ViewState cannot transfer data between multiple pages.

Best Practices for ViewState

✅ Minimize ViewState usage for lightweight pages.


✅ Disable ViewState on controls that don’t require state persistence:

aspx

<asp:TextBox ID="txtTempData" runat="server" EnableViewState="false" />

✅ Encrypt ViewState data for enhanced security by modifying the [Link]:

xml

<pages enableViewStateMac="true" viewStateEncryptionMode="Always" />

When to Use ViewState

• Ideal for preserving small control values (like textboxes, dropdown selections) between
postbacks.
• For large data sets or multi-page navigation, consider alternatives like Session State,
Cookies, or Cache.

[Link] is Hidden Filed?


What is a Hidden Field in [Link]?

A Hidden Field is an HTML input control used to store data that is not visible to the user
but can be sent back to the server during form submission. Hidden fields are commonly used
for maintaining state or passing data between pages without displaying it in the UI.

Sahil
Interview Questions & Answers

Syntax for Hidden Field

In [Link] Web Forms:

aspx

<asp:HiddenField ID="hdnUserID" runat="server" Value="12345" />

In HTML:

html

<input type="hidden" id="hdnUserID" name="hdnUserID" value="12345" />

How Hidden Fields Work

1. Hidden fields are included in the HTML form as <input type="hidden">.


2. The user cannot see the field on the page, but its value is sent to the server during form
submission.
3. It is ideal for storing small amounts of data that must persist across postbacks.

Example in [Link] Web Forms

ASPX Page:

aspx

<asp:HiddenField ID="hdnUserID" runat="server" Value="1001" />


<asp:Button ID="btnSubmit" runat="server" Text="Get User Info"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server" />

Code-Behind (C#):

protected void btnSubmit_Click(object sender, EventArgs e)


{
string userID = [Link]; // Retrieve hidden field value
[Link] = $"User ID from Hidden Field: {userID}";
}

Output:

User ID from Hidden Field: 1001

Advantages of Hidden Fields

✅ Simple to Implement: Easy to add and retrieve data.


✅ No Server Resources Required: Data is stored in the page itself.
✅ Useful for Non-Sensitive Data: Ideal for persisting simple values like IDs, flags, etc.
Sahil
Interview Questions & Answers

Disadvantages of Hidden Fields

❌ Security Risk: Since hidden fields are stored in the page's HTML, they can be modified
by users. Avoid using them for sensitive data (e.g., passwords).
❌ Data Exposure: Hidden field data is visible in the browser's "View Source."
❌ Limited Data Capacity: Suitable only for small data. For large data sets, prefer Session
State or Cache.

Best Practices for Using Hidden Fields

✅ Encrypt or hash sensitive data before placing it in hidden fields.


✅ Use hidden fields only for non-sensitive data like IDs, flags, or temporary values.
✅ Consider alternatives like Session State, Cookies, or ViewState for improved security
and performance.

Hidden Fields in [Link] Core

In [Link] Core, you can create hidden fields directly in Razor views like this:

<input type="hidden" id="hdnToken" name="hdnToken"


value="@[Link]" />

[Link] is Index in SQL?


What is an Index in SQL?

An Index in SQL is a database object that improves the performance of data retrieval
operations (e.g., SELECT queries) by providing faster access to table rows. It's similar to an
index in a book — helping you quickly locate information.

An index is created on one or more columns of a table, allowing the database engine to find
data more efficiently without scanning the entire table.

How Does an Index Work?

• SQL indexes use B-trees or hash structures internally to optimize data lookup.
• When a query runs, the database engine checks if an index exists for the searched
column(s).

Sahil
Interview Questions & Answers

• If an index is present, SQL will use it to locate the desired data faster. Otherwise, it performs
a full table scan, which is slower.

Types of Indexes in SQL

1. Clustered Index
2. Non-Clustered Index
3. Unique Index
4. Filtered Index
5. Composite Index
6. Full-Text Index
7. Spatial Index

1. Clustered Index

• A Clustered Index determines the physical order of data in the table.


• Each table can have only one clustered index because data can be physically sorted in only
one order.
• By default, the Primary Key creates a clustered index.

Syntax:

CREATE CLUSTERED INDEX IX_Employee_ID


ON Employees(EmployeeID);

✅ Fast retrieval for range-based queries.


❌ Slower insert/update operations since data is physically rearranged.

2. Non-Clustered Index

• A Non-Clustered Index stores pointers to the actual data instead of rearranging it.
• A table can have multiple non-clustered indexes.

Syntax:

CREATE NONCLUSTERED INDEX IX_Employee_Name


ON Employees(EmployeeName);

✅ Improves search performance without affecting physical data order.


❌ Consumes additional storage.

Sahil
Interview Questions & Answers

3. Unique Index

• Ensures that no duplicate values are inserted in the indexed column.


• Often created automatically when you define a Unique Constraint.

Syntax:

CREATE UNIQUE INDEX IX_Email


ON Employees(Email);

✅ Ensures data uniqueness.


❌ Inserts may fail if duplicate values are attempted.

4. Filtered Index

• Used to index a subset of rows in a table.


• Ideal for tables with large data sets and selective conditions.

Syntax:

CREATE NONCLUSTERED INDEX IX_ActiveUsers


ON Users(Status)
WHERE Status = 'Active';

✅ Improves query performance for frequently accessed data subsets.

5. Composite Index

• An index created on multiple columns to improve search performance on combined


conditions.

Syntax:

CREATE NONCLUSTERED INDEX IX_Employee_Dept


ON Employees(DepartmentID, EmployeeName);

✅ Speeds up queries that filter or sort by multiple columns.

6. Full-Text Index

• Designed for text-heavy searches, especially in large text columns.

Syntax:

Sahil
Interview Questions & Answers
CREATE FULLTEXT INDEX ON Articles(Content)
KEY INDEX PK_ArticleID;

✅ Ideal for fast text-based search across large data sets.

7. Spatial Index

• Used to improve performance on geospatial data queries.

Syntax:

CREATE SPATIAL INDEX IX_Geography


ON Locations(GeographyData);

✅ Speeds up geographic searches like location proximity queries.

When to Use Indexes

✅ When querying large data sets frequently.


✅ For columns used in WHERE, ORDER BY, GROUP BY, or JOIN conditions.
✅ For improving search performance on non-trivial queries.

When NOT to Use Indexes

❌ On small tables (full table scans may be faster).


❌ On columns with frequent updates, as indexes slow down INSERT, UPDATE, and DELETE.
❌ On columns with low cardinality (few distinct values like "Yes/No").

Example with Performance Impact

Without Index:

SELECT * FROM Employees WHERE LastName = 'Smith';

• In a large table, this may trigger a full table scan.

With Index:

CREATE INDEX IX_LastName ON Employees(LastName);

SELECT * FROM Employees WHERE LastName = 'Smith';

Sahil
Interview Questions & Answers

• This will efficiently locate the records using the index, significantly improving query speed.

Best Practices for Using Indexes

✅ Index frequently used search conditions.


✅ Avoid over-indexing; it can degrade performance for insert/update operations.
✅ Regularly analyse and rebuild fragmented indexes to maintain efficiency.

[Link] to Optimize Sql Performance?


SQL Performance Optimization Techniques

Optimizing SQL performance is essential for improving query speed, reducing server load,
and ensuring scalability. Below are proven techniques to enhance SQL performance:

1. Indexing

Indexes are critical for speeding up data retrieval by reducing the need for full table scans.

✅ Use Clustered Indexes for frequently searched or sorted columns.


✅ Use Non-Clustered Indexes for columns involved in WHERE, JOIN, ORDER BY, or GROUP
BY.
✅ Create Composite Indexes for multiple-column filtering.
✅ Avoid excessive indexing to prevent overhead on INSERT, UPDATE, and DELETE
operations.

Example:

CREATE INDEX IX_Employee_LastName


ON Employees (LastName);

2. Use Proper SELECT Statements

Avoid selecting unnecessary columns — fetching only the data you need improves
performance.

❌ Inefficient Query:

SELECT * FROM Employees;

✅ Optimized Query:

SELECT FirstName, LastName FROM Employees;


Sahil
Interview Questions & Answers

3. Avoid Using Functions in WHERE Clauses

Functions in WHERE conditions prevent the use of indexes, forcing a full table scan.

❌ Inefficient Query:

SELECT * FROM Orders WHERE YEAR(OrderDate) = 2024;

✅ Optimized Query:

SELECT * FROM Orders WHERE OrderDate >= '2024-01-01' AND OrderDate < '2025-
01-01';

4. Optimize Joins

• Use INNER JOIN instead of LEFT JOIN or RIGHT JOIN if matching records are all you
need.
• Index columns that are used in JOIN conditions.

Example:

SELECT [Link], [Link]


FROM Employees e
INNER JOIN Departments d ON [Link] = [Link];

5. Use EXISTS Instead of IN for Subqueries

EXISTS is generally faster than IN because it stops processing as soon as a match is found.

❌ Inefficient Query:

SELECT * FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM


Departments WHERE IsActive = 1);

✅ Optimized Query:

SELECT * FROM Employees e


WHERE EXISTS (
SELECT 1 FROM Departments d
WHERE [Link] = [Link] AND [Link] = 1
);

6. Use UNION ALL Instead of UNION

• UNION removes duplicates (requires sorting), while UNION ALL keeps all records without
sorting.

Sahil
Interview Questions & Answers

• Use UNION ALL when duplicate data is acceptable.

✅ Optimized Query:

SELECT FirstName FROM Employees


UNION ALL
SELECT FirstName FROM Customers;

7. Use Stored Procedures

• Stored procedures are compiled and cached, improving execution speed.


• They reduce network traffic by executing logic directly on the server.

Example Stored Procedure:

CREATE PROCEDURE GetEmployeeDetails


@EmployeeID INT
AS
BEGIN
SELECT * FROM Employees WHERE EmployeeID = @EmployeeID;
END;

8. Avoid Cursors (If Possible)

• Cursors loop row-by-row and are slower than set-based operations.


• Prefer set-based SQL queries.

❌ Inefficient Cursor Example:

DECLARE @Name NVARCHAR(50)


DECLARE CursorName CURSOR FOR SELECT Name FROM Employees;
OPEN CursorName;
FETCH NEXT FROM CursorName INTO @Name;

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Name
FETCH NEXT FROM CursorName INTO @Name;
END;

✅ Optimized Set-Based Query:

SELECT Name FROM Employees;

9. Optimize Temp Tables and Table Variables

• Temporary Tables (#TempTable) are ideal for complex data manipulation with indexing
capabilities.
Sahil
Interview Questions & Answers

• Table Variables (@TableVariable) are memory-efficient but lack indexing.

Example (Temporary Table with Index):

CREATE TABLE #TempEmployee (ID INT PRIMARY KEY, Name NVARCHAR(100));

INSERT INTO #TempEmployee VALUES (1, 'John Doe'), (2, 'Jane Smith');

10. Use Pagination for Large Data Sets

Fetching large data sets in chunks improves performance and reduces memory usage.

Example Using OFFSET and FETCH:

SELECT * FROM Employees


ORDER BY EmployeeID
OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY;

11. Use Database Statistics and Execution Plan

• Analyze the Execution Plan to identify bottlenecks and inefficient query paths.
• Update statistics regularly to help the SQL engine make better decisions.

Update Statistics Command:

UPDATE STATISTICS Employees;

12. Optimize Data Types

• Use appropriate data types to save storage and improve performance.


• Prefer INT over BIGINT if values are within range.
• Avoid using NVARCHAR(MAX) unless necessary.

13. Partition Large Tables

Partitioning divides large tables into smaller, manageable pieces for faster query
performance.

Example of Partitioning by Year:

CREATE PARTITION FUNCTION pfYearlyOrders (DATETIME)


AS RANGE LEFT FOR VALUES ('2022-12-31', '2023-12-31', '2024-12-31');

14. Avoid Deadlocks and Blocking

• Identify problematic queries using SQL Profiler or Extended Events.


Sahil
Interview Questions & Answers

• Use NOLOCK cautiously for read-only queries to avoid locking issues.

Example with NOLOCK:

SELECT * FROM Orders WITH (NOLOCK);

15. Regular Database Maintenance

✅ Rebuild Indexes to reduce fragmentation.


✅ Update Statistics to improve query optimizer accuracy.
✅ Backup and Cleanup unused data to improve performance.

Rebuild Index Example:

ALTER INDEX ALL ON Employees REBUILD;

Bonus: Tools for Performance Analysis

🔍 SQL Server Profiler — For analyzing query performance.


🔍 Execution Plan (CTRL + M in SSMS) — To visualize query steps.
🔍 Database Engine Tuning Advisor — For automatic index recommendations.

Summary Cheat Sheet


Optimization Tip Key Benefit

Use Indexes Faster data retrieval

Use EXISTS instead of IN Faster subquery performance

Use Pagination Improves performance on large datasets

Optimize Data Types Reduces storage and improves efficiency

Avoid **SELECT *** Reduces unnecessary data transfer

Use Stored Procedures Faster execution and reduced network load

8. What are Access Modifiers?

Access Modifiers are keywords in C# that define the scope and visibility of classes,
methods, and variables. They control which parts of your code can access specific members.

Sahil
Interview Questions & Answers

Types of Access Modifiers in C#


Modifier Description

public Accessible from anywhere.

private Accessible only within the same class.

protected Accessible within the same class or derived classes.

internal Accessible only within the same assembly (project).

protected internal Accessible within the same assembly or in derived classes.

private protected Accessible within the same class or derived classes in the same assembly.

Example:

public class Sample


{
public int PublicValue = 10; // Accessible everywhere
private int PrivateValue = 20; // Accessible only inside this class
protected int ProtectedValue = 30; // Accessible within this class &
derived classes
}

9. What are Data Types in SQL?

SQL data types define the type of data a column can store. Choosing the correct data type
improves performance, accuracy, and storage efficiency.

Common SQL Data Types


Category Data Type Description

Integer Types INT, BIGINT, SMALLINT, TINYINT Whole numbers

Decimal Types DECIMAL, NUMERIC, FLOAT, REAL Decimal values

String Types CHAR, VARCHAR, TEXT, NVARCHAR Text values

Date/Time Types DATE, DATETIME, TIME, TIMESTAMP Date and time values

Boolean Type BIT 0 (False) or 1 (True)

Binary Types BINARY, VARBINARY Binary data (e.g., images, files)

Example:

CREATE TABLE Employees (

Sahil
Interview Questions & Answers
ID INT PRIMARY KEY,
Name NVARCHAR(100),
Salary DECIMAL(10, 2),
HireDate DATE
);

10. What is a View in SQL?

A View is a virtual table that stores the result of a SELECT query. Views help simplify
complex queries, enhance security, and improve code reusability.

Syntax

CREATE VIEW EmployeeDetails AS


SELECT ID, Name, Salary
FROM Employees
WHERE Salary > 50000;
Key Benefits

✅ Simplifies complex queries.


✅ Enhances data security by exposing only specific columns.
✅ Provides a layer of abstraction from the underlying table structure.

11. If Page Load is Taking Too Much Time, What Actions Will You Take?

Steps to Improve Page Load Speed:

✅ Optimize Database Queries:

• Use proper indexing.


• Minimize SELECT * and fetch only necessary data.
• Use EXISTS instead of IN.

✅ Enable Caching:

• Implement Output Caching for static data.


• Use MemoryCache, Redis, or Distributed Caching in .NET Core.

✅ Minimize HTTP Requests:

• Combine CSS and JavaScript files.


• Use Content Delivery Networks (CDNs) for faster asset delivery.

✅ Compress Data:

• Enable Gzip compression in the .NET Core middleware.


• Optimize image sizes and use modern formats like WebP.
Sahil
Interview Questions & Answers

✅ Asynchronous Loading:

• Load heavy resources asynchronously using AJAX.

✅ Profile Performance:

• Use tools like SQL Server Profiler, MiniProfiler, or Postman to identify bottlenecks.

12. What is Code Reusability?

Code Reusability refers to writing code in such a way that it can be reused in multiple parts
of an application without duplication. Reusability improves efficiency, reduces redundancy,
and enhances maintainability.

Techniques for Code Reusability

✅ Functions/Methods: Encapsulate logic in reusable methods.


✅ Classes and Objects: Create modular classes for repeated logic.
✅ Inheritance: Use OOP principles to reuse base class logic.
✅ Interfaces & Abstraction: Promote flexible and extensible design.
✅ NuGet Packages or Libraries: Encapsulate reusable logic in libraries.

Example Using Methods:

public class Calculator


{
public int Add(int a, int b) => a + b;
public int Multiply(int a, int b) => a * b;
}

13. What is a Common Table Expression (CTE) in SQL?

A Common Table Expression (CTE) is a temporary result set that you can reference within
a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax

WITH EmployeeCTE AS (
SELECT ID, Name, Salary
FROM Employees
WHERE Salary > 50000
)
SELECT * FROM EmployeeCTE;

Sahil
Interview Questions & Answers

Benefits of Using CTE

✅ Improves query readability for complex joins and nested queries.


✅ Can be referenced multiple times within the same query.
✅ Provides better structure for recursive queries.

Example of a Recursive CTE (for hierarchy like employees reporting to managers):

WITH EmployeeHierarchy AS (
SELECT ID, Name, ManagerID
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT [Link], [Link], [Link]
FROM Employees e
INNER JOIN EmployeeHierarchy eh ON [Link] = [Link]
)
SELECT * FROM EmployeeHierarchy;

----------------------------------HDFC-----------------------------------------

14. Explain in Brief Your Project

When describing your project in an interview, focus on these key points:

✅ Project Name and Purpose: Briefly explain what the project does and its objective.
✅ Tech Stack: Mention the technologies used (e.g., .NET Core, Entity Framework Core,
SQL Server, etc.).
✅ Architecture: Describe if you used N-tier, MVC, or Microservices.
✅ Your Role: Highlight your specific contributions (e.g., API development, database
design, etc.).
✅ Challenges and Solutions: Share a problem you faced and how you resolved it.

Example Answer:
"I worked on an e-commerce platform using .NET Core and Entity Framework Core. The
application followed an N-tier architecture where I developed RESTful APIs for product
management, integrated Stripe for payments, and implemented caching using Redis to
improve performance. One challenge was optimizing database queries, which I solved by
adding proper indexes and using pagination techniques."

15. What is a Session?

A Session is a server-side state management technique used to store user-specific data


temporarily. Each session is unique to a particular user and is identified via a Session ID.

Example in [Link] Core:


Sahil
Interview Questions & Answers
// Store data in Session
[Link]("UserName", "JohnDoe");

// Retrieve data from Session


var userName = [Link]("UserName");

16. What is a Nested If-Else? Can We Write an if Inside Another if?

Yes, you can write an if statement inside another if statement. This is called a Nested If-
Else.

Example:

int marks = 85;

if (marks >= 50)


{
if (marks >= 75)
{
[Link]("Distinction");
}
else
{
[Link]("Pass");
}
}
else
{
[Link]("Fail");
}

17. What is the Difference Between for and foreach Loop?


Feature for Loop foreach Loop

Used when index-based iteration is Used for iterating directly over


Purpose
required. collections.

Can iterate in reverse order or skip Iterates only forward through the
Flexibility
elements. collection.

Faster when modifying data inside the Safer for read-only data but slightly
Performance
loop. slower.

Example (for Loop):

for (int i = 0; i < 5; i++)


{
[Link](i);
}

Sahil
Interview Questions & Answers

Example (foreach Loop):

string[] fruits = { "Apple", "Banana", "Cherry" };


foreach (var fruit in fruits)
{
[Link](fruit);
}

18. do-while vs while Loop with Syntax


Feature while Loop do-while Loop

Condition is checked before executing Condition is checked after executing


Condition Check
the loop body. the loop body.

Execution May never execute if the condition is


Executes at least once.
Guarantee false initially.

Syntax (while Loop):

int i = 0;
while (i < 5)
{
[Link](i);
i++;
}

Syntax (do-while Loop):

int i = 0;
do
{
[Link](i);
i++;
} while (i < 5);

19. Static Class vs Normal Class


Feature Static Class Normal Class

Instance Creation Cannot be instantiated. Requires object creation for use.

Contains Only contains static members. Can contain both static and instance members.

Inheritance Cannot be inherited. Supports inheritance.

Example Static Class:

public static class Utility


{
public static int Add(int a, int b) => a + b;

Sahil
Interview Questions & Answers
}

20. What is a Design Pattern? Types?

A Design Pattern is a proven solution to common software design problems.

Types of Design Patterns

✅ Creational Patterns (e.g., Singleton, Factory)


✅ Structural Patterns (e.g., Adapter, Decorator)
✅ Behavioral Patterns (e.g., Observer, Strategy)

21. What is the Repository Design Pattern?

The Repository Pattern separates business logic from data access logic by creating an
abstraction layer.

Example Repository Interface:

public interface IEmployeeRepository


{
Task<IEnumerable<Employee>> GetAllEmployees();
Task<Employee> GetEmployeeById(int id);
}

Example Repository Implementation:

public class EmployeeRepository : IEmployeeRepository


{
private readonly AppDbContext _context;

public EmployeeRepository(AppDbContext context)


{
_context = context;
}

public async Task<IEnumerable<Employee>> GetAllEmployees() =>


await _context.[Link]();

public async Task<Employee> GetEmployeeById(int id) =>


await _context.[Link](id);
}

22. What is const and readonly Keyword?


Feature const readonly

Must be assigned during Can be assigned during declaration or in the


Value Assignment
declaration. constructor.

Sahil
Interview Questions & Answers

Feature const readonly

Runtime vs Compile-
Evaluated at compile time. Evaluated at runtime.
time

Cannot be modified after


Modification Can only be modified in the constructor.
declaration.

Example:

public class Example


{
public const double Pi = 3.14; // Compile-time constant
public readonly int MaxUsers;

public Example(int maxUsers)


{
MaxUsers = maxUsers; // Assigned in constructor
}
}

23. What is Boxing and Unboxing?

• Boxing: Converting a value type to a reference type (object).


• Unboxing: Converting a reference type (object) back to a value type.

Example:

int number = 100; // Value type


object obj = number; // Boxing
int unboxedNumber = (int)obj; // Unboxing

24. What is an Abstract Class and Interface?


Feature Abstract Class Interface

Method Can have both abstract and Can only have abstract methods (C# 8+
Implementation non-abstract methods. allows default implementations).

Inheritance Supports single inheritance. Supports multiple inheritance.

Can have access modifiers like


Access Modifiers Methods are public by default.
public, protected.

Sahil
Interview Questions & Answers

Example Interface Implementation (with 2 methods):

interface IAnimal
{
void Eat();
void Sleep();
}

public class Dog : IAnimal


{
public void Eat() => [Link]("Dog is eating");
public void Sleep() => [Link]("Dog is sleeping");
}

25. Method Overriding Example

public class Parent


{
public virtual void Show() => [Link]("Parent Show");
}

public class Child : Parent


{
public override void Show() => [Link]("Child Show");
}

26. How Many Primary Keys Can a Table Have?

✅ A table can have only one Primary Key.


✅ However, the primary key can consist of multiple columns (Composite Key).

27. What is a Composite Key and Candidate Key?

• Composite Key: A primary key made up of two or more columns.


• Candidate Key: Any column (or combination) that can uniquely identify rows.

28. How to Find the Last Generated Identity Value?

Methods to Retrieve Last Identity Value: ✅ SCOPE_IDENTITY() — Returns the last


identity value generated in the current session and scope.
✅ @@IDENTITY — Returns the last identity value for the session (may include triggers).
✅ IDENT_CURRENT('TableName') — Returns the last identity value for a specific table.

Example:

INSERT INTO Employees (Name) VALUES ('John');


SELECT SCOPE_IDENTITY();

Sahil
Interview Questions & Answers

29. Try catch block in c#? Can we write try without catch? If Yes then
how?
Try-Catch Block in C#

The try-catch block is used to handle exceptions in C#.

✅ The try block contains the code that may throw an exception.
✅ The catch block handles the exception.
✅ The finally block (optional) contains code that always executes (even if an exception
occurs).

Syntax of Try-Catch Block

try
{
// Code that may throw an exception
int result = 10 / 0; // Division by zero exception
}
catch (DivideByZeroException ex)
{
[Link]("Cannot divide by zero!");
}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
finally
{
[Link]("Execution completed.");
}

✅ Output:

Cannot divide by zero!


Execution completed.

Can We Write try Without catch?

Yes, you can write a try block without a catch block by using the finally block.

✅ The finally block ensures that cleanup code (like closing connections or releasing
resources) always runs, regardless of whether an exception occurs.

Sahil
Interview Questions & Answers

Example: Try-Finally Without Catch


try
{
[Link]("Opening File...");
// Simulating file operation
throw new Exception("File error occurred.");
}
finally
{
[Link]("Closing File..."); // Executes no matter what
}

✅ Output:

Opening File...
Closing File...
Exception thrown: '[Link]' with message 'File error occurred.'

When to Use try-finally Without catch?

• When you need mandatory cleanup (e.g., closing database connections, releasing
resources).
• When you want the application to terminate naturally after performing important cleanup
tasks.

Best Practice Tip:

• Use try-catch-finally when you need error handling and cleanup.


• Use try-finally when cleanup is your primary focus.

HDFC ERGO interview Question

30. What is SQL & Types of SQL?

SQL (Structured Query Language) is used to manage and manipulate relational databases.

Types of SQL Commands

1. DQL (Data Query Language) → SELECT


2. DDL (Data Definition Language) → CREATE, ALTER, DROP
Sahil
Interview Questions & Answers

3. DML (Data Manipulation Language) → INSERT, UPDATE, DELETE


4. TCL (Transaction Control Language) → COMMIT, ROLLBACK, SAVEPOINT
5. DCL (Data Control Language) → GRANT, REVOKE

31. How to Connect SQL with .NET Web Application (Connection String in [Link])

1. In [Link] file:

xml

<configuration>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Server=localhost;Database=MyDB;User
Id=sa;Password=YourPassword;" providerName="[Link]"/>
</connectionStrings>
</configuration>

2. In C# Code:

csharp

using [Link];

string connectionString =
[Link]["DefaultConnection"].ConnectionStrin
g;
using (SqlConnection conn = new SqlConnection(connectionString))
{
[Link]();
// Database operations here
}

32. How Many finally Blocks Can Be Written in C#?

✅ In C#, only one finally block is allowed for each try block.

• Each try block can have:


o One or more catch blocks (for handling different exceptions).
o Only one finally block (for cleanup operations).

Example of Multiple catch Blocks with One finally Block


try
{
int[] numbers = { 1, 2, 3 };
[Link](numbers[5]); // IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{

Sahil
Interview Questions & Answers
[Link]("Array index is out of range.");
}
catch (Exception ex)
{
[Link]("General Exception: " + [Link]);
}
finally
{
[Link]("Finally block executed.");
}

✅ Output:

Array index is out of range.


Finally block executed.

✅ Key Rule:

• Multiple catch blocks → ✅ Allowed


• Multiple finally blocks → ❌ Not Allowed

33. Explain Session Variable and Application Variable in [Link]

Both Session and Application variables are used to store data, but they differ in scope,
lifetime, and purpose.

Feature Session Variable Application Variable

Scope Stores data for a single user session. Stores data shared by all users.

Exists until the session ends (browser closes or Exists until the application stops or
Lifetime
timeout occurs). restarts.

Stored in server memory (shared by


Storage Stored in server memory (per user).
all users).

Thread Thread-safe (data shared across


Not thread-safe (handled individually).
Safety requests).

Session Variable Example


// Storing data in Session
Session["UserName"] = "JohnDoe";

// Retrieving data from Session


string userName = Session["UserName"].ToString();
[Link](userName); // Output: JohnDoe

Sahil
Interview Questions & Answers

Application Variable Example


// Storing data in Application
Application["TotalVisitors"] = 100;

// Retrieving data from Application


int visitors = (int)Application["TotalVisitors"];
[Link]($"Total Visitors: {visitors}");

Key Differences in Usage:

✅ Use Session Variables for user-specific data (e.g., User ID, Cart Items).
✅ Use Application Variables for global data shared across users (e.g., Total Visitors,
Config Settings).

34. What is SQL Clauses?

SQL clauses are conditions used to filter, sort, or manipulate query results.

✅ WHERE – Filters records


✅ ORDER BY – Sorts results
✅ GROUP BY – Groups data
✅ HAVING – Filters grouped data
✅ TOP / LIMIT – Limits results

Example:

SELECT Name, Salary FROM Employees


WHERE Salary > 50000
ORDER BY Salary DESC;

35. What is IN & OUT Parameter in SQL?

• IN Parameter: Passes input values to the stored procedure.


• OUT Parameter: Returns a value from the stored procedure.

Example:

CREATE PROCEDURE GetEmployeeById


@Id INT,
@Name NVARCHAR(100) OUTPUT
AS
BEGIN
SELECT @Name = Name FROM Employees WHERE ID = @Id;
END;

Sahil
Interview Questions & Answers

36. Difference Between Stored Procedures & Functions


Feature Stored Procedure Function

Must return one value (scalar, table,


Return Type Can return 0 or more values.
etc.).

Usage Called using EXEC or CALL. Called from SQL queries directly.

Can use transaction controls like


Transactions Cannot handle transactions.
COMMIT.

Exception
Supports TRY...CATCH. Limited error handling.
Handling

37. What is Task Scheduler?

Task Scheduler is a Windows utility that allows you to schedule programs, scripts, or tasks
to run at predefined times or in response to specific events.

38. How to Use Task Scheduler with Stored Procedures

1. Create a .bat file with the SQL execution command:

sqlcmd -S localhost -d MyDB -U sa -P MyPassword -Q "EXEC


[Link]"

2. Create a Task in Windows Task Scheduler:

• Go to Task Scheduler → Create Basic Task


• Set Trigger (e.g., Daily, Weekly)
• In Action, select "Start a Program" and provide the .bat file path.

39. What is DML Operation?

DML (Data Manipulation Language) commands are used to modify database records.

✅ INSERT – Adds new records


✅ UPDATE – Modifies existing records
✅ DELETE – Removes records

Example:

INSERT INTO Employees (Name, Age) VALUES ('John Doe', 30);

Sahil
Interview Questions & Answers

40. What are Validators in [Link] & Types?

Validators are controls in [Link] that enforce input validation.

Types of Validators

✅ RequiredFieldValidator
✅ RangeValidator
✅ RegularExpressionValidator
✅ CompareValidator
✅ CustomValidator

Example:

html
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator ControlToValidate="txtAge" MinimumValue="18"
MaximumValue="60"
Type="Integer" ErrorMessage="Age must be between 18 and 60"
runat="server" />

41. Use of Regular Expression Validator in [Link]

The RegularExpressionValidator control ensures that user input matches a specified pattern
using regex.

Example: Email Validation


html

<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>


<asp:RegularExpressionValidator
ControlToValidate="txtEmail"
ValidationExpression="^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
ErrorMessage="Invalid Email Format"
runat="server" />

42. What is CLR?

The Common Language Runtime (CLR) is the core runtime environment in the .NET
Framework responsible for:

✅ Memory Management (Garbage Collection)


✅ Code Execution
✅ Exception Handling
✅ Security Management
✅ Just-In-Time (JIT) Compilation

Sahil
Interview Questions & Answers

43. What is ref & out Keyword?

Both are used to pass parameters by reference, but they differ in usage:

Feature ref out

The variable must be initialized before The variable doesn’t need to be initialized
Initialization
passing. before passing.

Data Flow Passes data into and out of a method. Passes data out of a method only.

Example of ref:

void Add(ref int number) { number += 10; }


int x = 5;
Add(ref x); // x becomes 15

Example of out:

void GetValues(out int a, out int b)


{
a = 10;
b = 20;
}
int x, y;
GetValues(out x, out y); // x = 10, y = 20

44. What is Boxing & Unboxing?

• Boxing: Converting value type → reference type (object).


• Unboxing: Converting reference type → value type.

Example:

int num = 100; // Value type


object obj = num; // Boxing
int unboxedNum = (int)obj; // Unboxing

45. How to Find the Nth Highest Salary in SQL?

Using OFFSET-FETCH (Recommended for SQL Server 2012+)

SELECT Salary

Sahil
Interview Questions & Answers
FROM Employees
ORDER BY Salary DESC
OFFSET 3 ROWS FETCH NEXT 1 ROW ONLY;

Using ROW_NUMBER()

WITH EmployeeRank AS (
SELECT Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Rank
FROM Employees
)
SELECT Salary FROM EmployeeRank WHERE Rank = 4;

46. What is a Stored Procedure & Example Query?

A Stored Procedure is a precompiled SQL code block that can be executed multiple times.

Syntax:

CREATE PROCEDURE GetEmployeeDetails


@EmpId INT
AS
BEGIN
SELECT * FROM Employees WHERE ID = @EmpId;
END;

Execution:

EXEC GetEmployeeDetails @EmpId = 101;

47. Write a Query to Backup a Table

To create a backup of a table:

Method 1: Using SELECT INTO

SELECT * INTO Employees_Backup FROM Employees;

Method 2: Using INSERT INTO

INSERT INTO Employees_Backup


SELECT * FROM Employees;

48. What is State Management Techniques in [Link]?

State management techniques maintain user data across post backs.


Sahil
Interview Questions & Answers

✅ Client-Side Techniques:

• View State
• Hidden Fields
• Cookies
• Query String

✅ Server-Side Techniques:

• Session State
• Application State
• Cache

49. If a Column Has a Unique Key Constraint, Can We Apply a Foreign Key to the Same
Column?

✅ Yes, a column with a Unique Key can also have a Foreign Key constraint.

Example:

CREATE TABLE Departments (


DeptID INT PRIMARY KEY,
DeptName NVARCHAR(100)
);

CREATE TABLE Employees (


EmpID INT PRIMARY KEY,
DeptID INT UNIQUE, -- Unique Key
FOREIGN KEY (DeptID) REFERENCES Departments(DeptID)
);

50. Can We Call a Stored Procedure Using a SELECT Statement?

✅ No, you cannot directly call a stored procedure inside a SELECT statement.

However, you can:

• Use EXEC or EXECUTE to call a stored procedure.


• Use OPENQUERY (in linked servers) for indirect execution.

Example Using EXEC:

EXEC GetEmployeeDetails @EmpId = 101;

51. What is a Static Class?

A static class in C# is a class that:


Sahil
Interview Questions & Answers

✅ Cannot be instantiated.
✅ Contains only static members (methods, fields, etc.).
✅ Is sealed by default (cannot be inherited).
✅ Provides utility functions or constant data.

Example:

public static class MathUtility


{
public static int Add(int a, int b) => a + b;
public static int Multiply(int a, int b) => a * b;
}

52. Difference Between Stored Procedure and Functions


Feature Stored Procedure Function

Must return one value


Return Value Can return 0 or more values.
(scalar/table).

Execution Executed using EXEC or CALL. Can be called from SQL queries.

Transaction
Supports transaction control. Cannot handle transactions.
Support

Can perform INSERT, UPDATE,


DML Operations Limited to read-only operations.
DELETE.

Exception Handling Supports TRY...CATCH block. Limited error handling.

53. How to Transfer Data from One Page to Another in [Link]?

✅ Query String

[Link]("[Link]?name=John");

✅ Session State

Session["UserName"] = "John";
[Link]("[Link]");

✅ Cookies

[Link]["UserName"].Value = "John";

✅ [Link]

[Link]("[Link]");

Sahil
Interview Questions & Answers

54. What is the Use of var Keyword?

The var keyword declares implicitly typed variables, meaning the data type is determined at
compile time.

Example:

var num = 10; // Inferred as int


var name = "John"; // Inferred as string

✅ Best for readability in LINQ queries and anonymous types.


❌ Avoid using var for unclear data types.

55. What is for and foreach Loop?


Feature for Loop foreach Loop

Usage Used for index-based iteration. Used for iterating collections directly.

Flexibility Can modify or skip iterations. Suitable for read-only collections.

Example (for Loop):

for(int i = 0; i < 5; i++)


{
[Link](i);
}

Example (foreach Loop):

string[] fruits = { "Apple", "Banana", "Cherry" };


foreach (var fruit in fruits)
{
[Link](fruit);
}

56. What is do-while and while Loop?


Feature while Loop do-while Loop

Condition is checked before executing Condition is checked after executing


Condition Check
the loop body. the loop body.

Execution May never execute if the condition is


Executes at least once.
Guarantee false.

Sahil
Interview Questions & Answers

Example (while Loop):

int i = 0;
while (i < 3)
{ [Link](i);
i++;
}

Example (do-while Loop):

int i = 0;
do
{ [Link](i);
i++;
} while (i < 3);

57. What is the HAVING Clause?

The HAVING clause filters grouped data after aggregation.

Example:

SELECT Department, AVG(Salary) AS AvgSalary


FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 50000;

58. Create a Duplicate #Back-up Table

Method 1: Using SELECT INTO (Recommended)

SELECT * INTO Employees_Backup FROM Employees;

Method 2: Using CREATE TABLE + INSERT

CREATE TABLE Employees_Backup AS


SELECT * FROM Employees;

59. If You Have 10 Data Rows and Delete 9, What Will Be the Count?

✅ COUNT*) returns the number of existing rows.


✅ COUNT(ColumnName) returns the non-null values in that column.

Example:

DELETE FROM Employees WHERE EmpID < 10;


SELECT COUNT(*) FROM Employees;

➡️ The result will be 1 since only 1 row remains.

Sahil
Interview Questions & Answers

60. Can We Create a Table Using a Stored Procedure?

✅ Yes, you can create a table inside a stored procedure.

Example:

CREATE PROCEDURE CreateEmployeeTable


AS
BEGIN
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name NVARCHAR(100),
Salary DECIMAL(10, 2)
);
END;

Execution:

EXEC CreateEmployeeTable;

61. Difference Between [Link] & [Link] Core


Feature [Link] [Link] Core

Platform Runs only on Windows. Cross-platform (Windows, Linux, macOS).

Improved performance and faster request


Performance Comparatively slower.
processing.

Hosting Hosted only on IIS. Can be hosted on IIS, Kestrel, Docker, etc.

Based on Web Forms and


Architecture Unified with MVC, Razor Pages, and Web API.
MVC.

Dependency
Limited support. Built-in dependency injection support.
Injection

Configuration Uses [Link]. Uses [Link].

62. What is the [Link] File?

The [Link] file is the entry point of an [Link] Core application where:

✅ Services are configured in the ConfigureServices() method.


✅ Middleware pipeline is defined in the Configure() method.

Sahil
Interview Questions & Answers

Example Structure:

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
[Link]();
}

public void Configure(IApplicationBuilder app)


{
[Link]();
[Link](endpoints => [Link]());
}
}

63. What is Middleware?

Middleware is a component in the request pipeline that processes requests and responses.

✅ Each middleware handles part of the request.


✅ Examples include authentication, logging, and error handling.

Example:

[Link](async (context, next) =>


{
[Link]("Middleware 1");
await next();
[Link]("Returning from Middleware 1");
});

64. Explain the Use of Run(), Use(), and Map() Methods


Method Description

Run() Terminates the middleware pipeline (no further middleware runs).

Use() Allows calling the next middleware in the pipeline.

Map() Branches the pipeline based on a URL path.

Example:

[Link](async (context, next) =>


{
[Link]("Use Middleware");
await next();
});

[Link](async context =>

Sahil
Interview Questions & Answers
{
await [Link]("Final Middleware - Stops Here");
});

65. What is Routing in .NET Core?

Routing maps incoming requests to corresponding endpoints (e.g., controllers or Razor


Pages).

✅ Defined in the [Link] file using [Link]().


✅ Endpoints are configured with [Link]().

Example:

[Link]();
[Link](endpoints =>
{
[Link](
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

66. How to Manage Sessions in [Link] Core?

Steps for Session Management:

1. Add Session Service:

public void ConfigureServices(IServiceCollection services)


{
[Link]();
}

2. Use Session Middleware:

public void Configure(IApplicationBuilder app)


{
[Link]();
}

3. Store & Retrieve Session Data:

// Storing Session Data


[Link]("UserName", "John");

// Retrieving Session Data


var userName = [Link]("UserName");

Sahil
Interview Questions & Answers

Difference Between ViewBag and ViewData


Feature ViewBag ViewData

Type Dynamic property. Dictionary object.

Data Available only during the current


Available only during the current request.
Lifetime request.

ViewData["Title"] = "Home
Syntax [Link] = "Home Page";
Page";

Best Use Recommended for small data transfer. Better for larger data transfer.

67. What is the Use of the App_Start Folder?

The App_Start folder (mainly in [Link] MVC) contains configuration files like:

✅ [Link] – Configures routing.


✅ [Link] – Manages filters (like authorization).
✅ [Link] – Handles script and CSS bundling.

68. What is the Use of [Link]?

The [Link] file stores configuration settings such as:

✅ Connection Strings
✅ Logging Settings
✅ App Settings (e.g., API keys, custom configs)

Example ([Link]):

{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDB;User
Id=sa;Password=YourPassword;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
}
}

Sahil
Interview Questions & Answers

69. How to Execute a Stored Procedure in SQL Server?

✅ Executing Without Parameters

EXEC GetAllEmployees;

✅ Executing With Parameters

EXEC GetEmployeeDetails @EmpId = 101;

✅ Using SqlCommand in C#:

using (SqlConnection conn = new SqlConnection("Your_Connection_String"))


{
SqlCommand cmd = new SqlCommand("GetEmployeeDetails", conn);
[Link] = [Link];
[Link]("@EmpId", 101);

[Link]();
SqlDataReader reader = [Link]();
while ([Link]())
{
[Link](reader["Name"]);
}
}

70. What Does SELECT COUNT(*) FROM Employees Do?

✅ Returns the total number of rows in the Employees table, including NULL values.

Example:

SELECT COUNT(*) FROM Employees;

71. What Does SELECT COUNT(8) FROM Employees Do?

✅ COUNT(8) behaves like COUNT(*) but returns the total number of rows.
✅ The 8 is treated as a constant value in each row, so it counts every row.

Example:

SELECT COUNT(8) FROM Employees;

🔍 Output: Same as COUNT(*).

Sahil
Interview Questions & Answers

72. What Does SELECT COUNT(0) FROM Employees Do?

✅ COUNT(0) behaves similarly to COUNT(8).


✅ The constant 0 is evaluated for each row, and the total count is returned.

Example:

SELECT COUNT(0) FROM Employees;

🔍 Output: Same as COUNT(*).

73. Cross Join with 5 Records in One Table & 0 Records in Another Table

A CROSS JOIN returns the Cartesian product of two tables.


✅ If one table has zero rows, the result will always be zero rows.

Example:

SELECT A.*, B.*


FROM TableA A
CROSS JOIN TableB B;

🔍 Result: 0 rows (if TableB is empty).

74. What is a Trigger?

A trigger is a special type of stored procedure that automatically executes in response to:

✅ INSERT
✅ UPDATE
✅ DELETE

Example:

CREATE TRIGGER trg_AfterInsert


ON Employees
AFTER INSERT
AS
BEGIN
PRINT 'New Employee Added';
END;

✅ Trigger Execution:

Sahil
Interview Questions & Answers
INSERT INTO Employees VALUES (101, 'John Doe', 'IT');

75. Difference Between Primary Key & Unique Key


Feature Primary Key Unique Key

Ensures unique values but allows one null


Uniqueness Ensures unique and non-null values.
value.

Index Creates a clustered index by default. Creates a non-clustered index by default.

Per Table Only one primary key allowed. Multiple unique keys allowed.

Key Can be a single column or composite


Can be a single column or composite key.
Combination key.

Example (Primary Key):

CREATE TABLE Employees (


EmpID INT PRIMARY KEY,
Name NVARCHAR(100));

Example (Unique Key):

CREATE TABLE Employees (


EmpID INT UNIQUE,
Email NVARCHAR(100) UNIQUE
);

76. Types of Joins in SQL

Joins are used to combine data from multiple tables based on related columns.

✅ INNER JOIN — Returns matching records from both tables.


✅ LEFT JOIN — Returns all records from the left table and matching records from the
right table.
✅ RIGHT JOIN — Returns all records from the right table and matching records from the
left table.
✅ FULL OUTER JOIN — Returns all records when there is a match in either table.
✅ CROSS JOIN — Returns the Cartesian product of both tables.

Example (INNER JOIN):

SELECT [Link], [Link], [Link]


FROM Employees E
INNER JOIN Departments D
ON [Link] = [Link];

Sahil
Interview Questions & Answers

77. Difference Between Function and Stored Procedure


Feature Function Stored Procedure

Must return one value


Return Value Can return 0 or more values.
(scalar/table).

Execution Called from SELECT, WHERE, etc. Called using EXEC or EXECUTE.

Transaction
❌ No transaction control. ✅ Supports transaction control.
Support

Error Handling Limited error handling. Full support for TRY...CATCH block.

Can perform INSERT, UPDATE,


DML Operations Limited to read-only operations.
DELETE.

78. statemaster (table) statename (colum) Statecode (colum) Write


query
SQL Queries for StateMaster Table

Table Structure:

StateName StateCode

Maharashtra MH

Gujarat GJ

Maharashtra MH

Karnataka KA

Tamil Nadu TN

1. Query to Find Duplicate StateName Count

SELECT StateName, COUNT(*) AS DuplicateCount


FROM StateMaster
GROUP BY StateName
HAVING COUNT(*) > 1;

Output:

Sahil
Interview Questions & Answers

StateName DuplicateCount

Maharashtra 2

2. Query to List Unique StateName

SELECT DISTINCT StateName


FROM StateMaster;

3. Query to Get Total Record Count

SELECT COUNT(*) AS TotalRecords


FROM StateMaster;

4. Query to Get State Names with Their Corresponding Codes

SELECT StateName, StateCode


FROM StateMaster;

5. Query to Get Only States Starting with Letter 'M'

SELECT StateName
FROM StateMaster
WHERE StateName LIKE 'M%';

6. Query to Display StateName and Their Counts (Including Non-Duplicates)

SELECT StateName, COUNT(*) AS TotalCount


FROM StateMaster
GROUP BY StateName;

79. Query to Find Duplicate State Names with Count

SELECT StateName, COUNT(*) AS DuplicateCount


FROM StateMaster
GROUP BY StateName
HAVING COUNT(*) > 1;

80. Difference Between Primary Key and Unique Key


Feature Primary Key Unique Key

Uniqueness Ensures unique and non-null values. Ensures unique values but allows one null value.

Index Creates a clustered index by default. Creates a non-clustered index by default.

Sahil
Interview Questions & Answers

Feature Primary Key Unique Key

Per Table Only one primary key allowed. Multiple unique keys allowed.

81. What is ViewBag?

ViewBag is a dynamic property in [Link] Core used to transfer data from the controller
to the view.

Example:

public IActionResult Index()


{
[Link] = "Hello World!";
return View();
}

In View (.cshtml):

<h1>@[Link]</h1>

82. Connected vs Non-Connected Architecture


Feature Connected Architecture Non-Connected Architecture

Uses SqlDataReader for real-time data Uses DataSet or DataTable for offline
Data Access
fetching. data access.

Slightly slower since it maintains a copy of


Performance Faster for large data operations.
the data.

Requires an active connection to fetch


Connection Can work with a disconnected connection.
data.

83. What Does SELECT COUNT(*) FROM Employees Do?

✅ Counts all rows, including rows with NULL values.

84. What Does SELECT COUNT(8) FROM Employees Do?

✅ Returns the total number of rows because 8 is treated as a constant for every row.

Sahil
Interview Questions & Answers

85. What Does SELECT COUNT(0) FROM Employees Do?

✅ Same as COUNT(*) and COUNT(8).


✅ Output: Counts all rows.

86. Interface Example

Interface Declaration:

public interface IShape


{
void Draw();
}

Implementation:

public class Circle : IShape


{
public void Draw() => [Link]("Drawing a Circle");
}

Usage:

IShape shape = new Circle();


[Link](); // Output: Drawing a Circle

87. OOPs Concepts with Example

✅ Encapsulation – Wrapping data and methods within a class.


✅ Abstraction – Hiding implementation details.
✅ Inheritance – Reusing code from a base class.
✅ Polymorphism – Same method behaving differently in different scenarios.

Example: Polymorphism

public class Animal


{
public virtual void Speak() => [Link]("Animal Sound");
}

public class Dog : Animal


{
public override void Speak() => [Link]("Dog Barks");
}

Sahil
Interview Questions & Answers

88. Abstraction with Code Example

Abstract Class:

public abstract class Vehicle


{
public abstract void StartEngine(); // Abstract Method
}

public class Car : Vehicle


{
public override void StartEngine()
{
[Link]("Car Engine Started");
}
}

89. How is a Class Called?

Creating and Using a Class:

public class Calculator


{
public int Add(int a, int b) => a + b;
}

// Calling the Class


Calculator calc = new Calculator();
int result = [Link](5, 10);
[Link](result); // Output: 15

90. What Are Aggregate Functions?

Aggregate functions perform calculations on a set of values and return a single value.

✅ COUN() — Counts rows.


✅ SUM() — Calculates the total sum.
✅ AVG() — Returns the average value.
✅ MAX() — Finds the maximum value.
✅ MIN() — Finds the minimum value.

Example:

SELECT
COUNT(*) AS TotalEmployees,
AVG(Salary) AS AvgSalary,
MAX(Salary) AS MaxSalary,
MIN(Salary) AS MinSalary
FROM Employees;

Sahil
Interview Questions & Answers

91. Unique Key vs Primary Key


Feature Primary Key Unique Key

Ensures unique and non-null Ensures unique values but allows one NULL
Uniqueness
values. value.

Null Values ❌ Cannot store NULL values. ✅ Can store one NULL value.

Creates a clustered index by


Index Creates a non-clustered index by default.
default.

Per Table Only one primary key is allowed. Multiple unique keys are allowed.

✅ Can Primary Key Store NULL Values? → ❌ NO


✅ Can Unique Key Store NULL Values? → ✅ YES (Only one NULL value)
✅ Can Unique Key Store Multiple NULL Values? → ❌ NO

92. What are Triggers?

A Trigger is a special type of stored procedure that automatically executes when certain
conditions are met.

✅ Used to enforce business rules, auditing, or automatic updates.


✅ Types of triggers:

• AFTER Trigger (Executes after INSERT, UPDATE, or DELETE).


• INSTEAD OF Trigger (Executes instead of the actual operation).

Example:

CREATE TRIGGER trg_AfterInsert


ON Employees
AFTER INSERT
AS
BEGIN
PRINT 'New Employee Added';
END;

93. What is a Copy Table?

A copy table is a duplicate of an existing table with or without data.

✅ Copy Table Structure Only

Sahil
Interview Questions & Answers
SELECT * INTO NewTable FROM OldTable WHERE 1 = 0;

✅ Copy Table Structure with Data

SELECT * INTO NewTable FROM OldTable;

Temporary Tables in SQL:

1. Local Temporary Table (#Temp) — Visible only to the session that created it.
2. Global Temporary Table (##Temp) — Visible to all sessions.

94. Difference Between const and readonly in C#


Feature const readonly

Must be assigned at Can be assigned in constructor or


Value Assignment
declaration. declaration.

Compile-Time /
Evaluated at compile-time. Evaluated at runtime.
Runtime

Scope Always static by default. Instance-specific (non-static by default).

Example:

public class Example


{
public const double PI = 3.14; // Constant value
public readonly int Age; // Readonly field

public Example(int age)


{
Age = age; // Allowed in constructor
}
}

95. Error Handling in C#

C# uses try...catch...finally for error handling.

✅ try — Code that may throw an exception.


✅ catch — Handles the exception.
✅ finally — Executes code regardless of success or failure.

Example:
Sahil
Interview Questions & Answers
try
{
int result = 10 / 0; // Exception occurs
}
catch (DivideByZeroException ex)
{
[Link]("Division by zero is not allowed.");
}
finally
{
[Link]("Execution completed.");
}

96. Connected vs Disconnected Architecture


Feature Connected Architecture Disconnected Architecture

Uses SqlDataReader for real-time Uses DataSet or DataTable for offline


Data Access
data fetching. data access.

Connection Can work without a continuous


Requires an active connection.
Type connection.

Slower but efficient for complex data


Performance Faster for large data operations.
manipulation.

97. [Link] Page Life Cycle

✅ Page_PreInit → Initialize master page and themes.


✅ Page_Init → Initializes controls and state.
✅ Page_Load → Loads data and page logic.
✅ Page_PreRender → Final changes before rendering.
✅ Page_Unload → Cleanup code.

98. How to Consume Web API in [Link] Core

Steps to Consume Web API:

1. Install HttpClient in your project.


2. Create an instance of HttpClient.
3. Use GetAsync(), PostAsync(), etc. to call API endpoints.

Example:

HttpClient client = new HttpClient();


HttpResponseMessage response = await
[Link]("[Link]
string result = await [Link]();

Sahil
Interview Questions & Answers
[Link](result);

99. Multiple Catch Blocks — Execution Order

✅ The first matching catch block will be executed.


✅ If no matching block is found, the catch(Exception ex) block is executed (if defined).

Example:

try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
[Link]("Divide by zero error.");
}
catch (Exception ex)
{
[Link]("General Exception.");
}

100. Functions vs Stored Procedures


Feature Function Stored Procedure

Return Value Must return one value (scalar/table). Can return 0 or more values.

Execution Called from SELECT, WHERE, etc. Called using EXEC or EXECUTE.

DML Operations Limited to read-only operations. Can perform INSERT, UPDATE, DELETE.

101. Writing SQL Queries

✅ Yes, you can write SQL queries directly within tools like:

• SQL Server Management Studio (SSMS)


• Visual Studio
• Entity Framework using LINQ

102. Types of Functions in SQL

✅ Scalar Functions — Returns a single value.


✅ Table-Valued Functions — Returns a table.
✅ Aggregate Functions — Perform calculations on data (e.g., SUM(), AVG()).

Sahil
Interview Questions & Answers

103. Explanation of COUNT(), MAX(), and MIN()

✅ COUNT() — Counts the number of rows.


✅ MAX() — Finds the maximum value in a column.
✅ MIN() — Finds the minimum value in a column.

Example:

SELECT
COUNT(*) AS TotalEmployees,
MAX(Salary) AS MaxSalary,
MIN(Salary) AS MinSalary
FROM Employees;

104. What is the DROP Keyword?

The DROP statement is used to delete a database object (table, procedure, etc.).

✅ Drop Table Example:

DROP TABLE Employees;

105. Difference Between DROP and TRUNCATE


Feature DROP TRUNCATE

Data Deletion Deletes the table structure and data. Deletes only data while keeping the structure.

Rollback ❌ Cannot be rolled back. ✅ Can be rolled back (if inside a transaction).

Performance Slower compared to TRUNCATE. Faster for bulk deletion.

106. Where to Use Functions & Types of Functions

✅ Use functions for reusable logic that returns values.


✅ Types include Scalar, Inline Table-Valued, and Multi-Statement Table-Valued.

Sahil
Interview Questions & Answers

107. How to Execute a Stored Procedure

✅ Execution Without Parameters:

EXEC GetAllEmployees;

✅ Execution With Parameters:

EXEC GetEmployeeDetails @EmpId = 101;

✅ Execution Using SqlCommand in C#:

SqlCommand cmd = new SqlCommand("GetEmployeeDetails", conn);


[Link] = [Link];
[Link]("@EmpId", 101);

108. How to Implement Encapsulation in C#?

Encapsulation is the process of hiding implementation details by restricting access to class


members and exposing only necessary functionalities via getters and setters.

✅ Encapsulation Example:

public class Employee


{
// Private fields (hidden data)
private string name;
private double salary;

// Public property to access private field


public string Name
{
get { return name; }
set
{
if (![Link](value))
name = value;
}
}

// Public method for data access


public void SetSalary(double amount)
{
if (amount > 0)
salary = amount;
}

public double GetSalary()


{
return salary;
}
}

Sahil
Interview Questions & Answers

Usage:

Employee emp = new Employee();


[Link] = "John Doe";
[Link](50000);

[Link]($"Name: {[Link]}, Salary: {[Link]()}");

109. What is out and ref in C#?

Both out and ref are used to pass arguments by reference, but they have key differences.

Feature ref out

The variable must be initialized The variable doesn't need to be initialized


Initialization
before passing. before passing.

Used to return multiple values from a


Purpose Used to modify the original value.
method.

Usage
Best for modifying data. Best for returning extra output values.
Scenario

Example Using ref:

void ModifyValue(ref int value)


{
value += 10;
}

int number = 5;
ModifyValue(ref number);
[Link](number); // Output: 15

Example Using out:

void GetValues(out int x, out int y)


{
x = 5; // Must be assigned before returning
y = 10;
}

GetValues(out int a, out int b);

Sahil
Interview Questions & Answers
[Link]($"a = {a}, b = {b}"); // Output: a = 5, b = 10

110. Steps to Display Stored Procedure Data in Frontend ([Link] MVC or Core)

1. Create the Stored Procedure in SQL

CREATE PROCEDURE GetEmployeeData


AS
BEGIN
SELECT EmpID, Name, Salary FROM Employees;
END;

2. Create a Data Access Layer (DAL)

public class EmployeeRepository


{
private readonly string _connectionString = "Your_Connection_String";

public DataTable GetEmployees()


{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
SqlCommand cmd = new SqlCommand("GetEmployeeData", conn)
{
CommandType = [Link]
};

SqlDataAdapter da = new SqlDataAdapter(cmd);


DataTable dt = new DataTable();
[Link](dt);
return dt;
}
}
}

3. Create the Controller

public class EmployeeController : Controller


{
EmployeeRepository repo = new EmployeeRepository();

public IActionResult Index()


{
var employees = [Link]();
return View(employees);
}
}

Sahil
Interview Questions & Answers

4. Create the View

<table>
<tr>
<th>EmpID</th>
<th>Name</th>
<th>Salary</th>
</tr>
@foreach (DataRow row in [Link])
{
<tr>
<td>@row["EmpID"]</td>
<td>@row["Name"]</td>
<td>@row["Salary"]</td>
</tr>
}
</table>

111. What is static in C#?

The static keyword is used for declaring class members that belong to the class itself
rather than an instance of the class.

✅ Static Members Example:

public class Calculator


{
public static int Add(int a, int b) => a + b;
}

// Calling without object creation


int result = [Link](5, 10);
[Link](result); // Output: 15

✅ Static Class Example:

public static class MathUtilities


{
public static double PI = 3.14;
public static int Square(int x) => x * x;
}

112. What are Access Modifiers and Their Types?

Access modifiers control the scope and visibility of class members.

✅ Types of Access Modifiers in C#:

• public — Accessible from anywhere.


Sahil
Interview Questions & Answers

• private — Accessible only within the declared class.


• protected — Accessible within the class and its derived classes.
• internal — Accessible within the same assembly.
• protected internal — Combination of protected and internal.
• private protected — Accessible within the same class or derived class in the same
assembly.

113. What are [Link] Controls?

[Link] controls are server-side controls used to create interactive web pages.

✅ Common [Link] Controls:

• TextBox — For text input.


• Button — For user actions like submit.
• DropDownList — For dropdown selections.
• GridView — Displays data in tabular form.
• Repeater — Lightweight data display control.

Example:

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>


<asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"
runat="server" />

114. What is Continuous and Discontinuous?

✅ Continuous Data — Data that can take any value within a range.

• Example: Height, Weight, Temperature.

✅ Discontinuous Data (Discrete Data) — Data that can only take specific values.

• Example: Number of students, Number of cars.

Key Difference:

Aspect Continuous Data Discontinuous Data

Value Type Can take infinite values in a range. Can take fixed values only.

Example Height (e.g., 5.4 ft, 5.5 ft, etc.) Number of Students (e.g., 10, 15, 20, etc.)

Sahil
Interview Questions & Answers

115. SELECT COUNT(*) vs SELECT COUNT(0) from Employee

Both queries return the same result — the total number of rows in the table.

✅ COUNT(*) counts all rows, including those with NULL values.


✅ COUNT(0) behaves similarly to COUNT(*).

Example Table (Employee)

EmpID Name

1 John

2 Jane

3 NULL

4 Mark

Query Results:

SELECT COUNT(*) FROM Employee; -- Output: 4


SELECT COUNT(0) FROM Employee; -- Output: 4

✅ Both return 4 because COUNT(*) and COUNT(0) ignore column values and count rows
directly.

116. What Value Does a User-Defined Function (UDF) Return in SQL?

A UDF (User-Defined Function) can return:

• Scalar Value — A single value (e.g., int, string).


• Table Value — A table-like structure.

Example: Scalar UDF

CREATE FUNCTION GetTotalSalary (@deptId INT)


RETURNS INT
AS
BEGIN
Sahil
Interview Questions & Answers
DECLARE @TotalSalary INT
SELECT @TotalSalary = SUM(Salary) FROM Employees WHERE DeptID = @deptId
RETURN @TotalSalary
END;

Calling the UDF:

SELECT [Link](1) AS TotalSalary;

117. Types of Joins & Cross Join Example

✅ Types of Joins in SQL:

• INNER JOIN — Returns matching records in both tables.


• LEFT JOIN — Returns all records from the left table and matching records from the right
table.
• RIGHT JOIN — Returns all records from the right table and matching records from the left
table.
• FULL JOIN — Returns all records from both tables.
• CROSS JOIN — Produces the Cartesian product (all combinations of rows).

Cross Join Example

Table A (4 rows)

EmpID Name

1 John

2 Jane

3 Mark

4 Lucy

Table B (0 rows - Empty table)

DeptID DeptName

Cross Join Query:

SELECT [Link], [Link], [Link], [Link]


FROM TableA A
CROSS JOIN TableB B;

✅ Output:

Sahil
Interview Questions & Answers
(No rows returned)

Since Table B has 0 rows, the CROSS JOIN result will also have 0 rows.

118. Find 4 Largest EmployeeID Without Using CTE or Ranking Function

SELECT TOP 4 EmpID


FROM Employees
ORDER BY EmpID DESC;

119. Delete Duplicate Names from Employee Table

WITH CTE AS (
SELECT Name, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY EmpID) AS
RowNum
FROM Employees
)
DELETE FROM CTE WHERE RowNum > 1;

✅ This method keeps the first occurrence and deletes the duplicates.

120. What is a Trigger? Syntax & Types

A Trigger is a special stored procedure that automatically executes in response to database


events such as INSERT, UPDATE, or DELETE.

✅ Trigger Syntax

CREATE TRIGGER trg_AfterInsert


ON Employees
AFTER INSERT
AS
BEGIN
INSERT INTO AuditLog (Action, EmpID, Date)
SELECT 'INSERT', EmpID, GETDATE() FROM inserted;
END;

✅ Types of Triggers in SQL:

• AFTER Trigger (Fires after an event)


• INSTEAD OF Trigger (Replaces the original operation)

✅ Usage in Projects:

• Tracking changes in critical tables.

Sahil
Interview Questions & Answers

• Implementing custom logic during inserts, updates, or deletes.


• Maintaining audit logs.

121. Why Use PARTITION BY Clause?

✅ PARTITION BY divides the result set into partitions, and calculations (like SUM(), AVG(),
etc.) are applied independently to each partition.

Example: Calculate Total Salary by Department

SELECT EmpID, Name, DeptID,


SUM(Salary) OVER (PARTITION BY DeptID) AS TotalDeptSalary
FROM Employees;

✅ This query calculates the total salary for each department without grouping the result
set.

Sahil

You might also like