0% found this document useful (0 votes)
32 views96 pages

Here Are The Key Differences

MS SQL Notes for interview
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views96 pages

Here Are The Key Differences

MS SQL Notes for interview
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 96

Q120. What is the difference between DBMS and RDBMS?

first explain what is dbms and


rdmsA
->DBMS is software that helps you store, manage, and retrieve data efficiently from a
database. Examples of DBMS:
 Microsoft Access
 File System-based databases

An RDBMS is a special type of DBMS that uses the relational model — meaning it stores
data in tables (also called relations) and relates data across tables using keys (like foreign
key, primary key).
RDBMS follows strict rules like:
 Data is organized in rows and columns
 Supports relationships between tables
 Supports constraints (like unique, not null)

 here are the Key Differences:

Feature DBMS RDBMS


Data Storage Data stored in files or tables Data stored in related tables
Relationships Doesn’t support relationships Supports relationships between tables
Normalization Not supported Supported to eliminate redundancy
Multiple Users Usually for single users Multi-user environment supported
Data Integrity Not strictly enforced Enforces constraints for data integrity
Example MS Access, File System SQL Server, Oracle, MySQL, PostgreSQL

Constraints:

Great! Let’s dive into SQL Constraints in a simple and clear way 👇

✅ What is a Constraint in SQL?


A constraint in SQL is a rule applied to a column or table to ensure the validity, accuracy,
and integrity of the data stored in the database.
Think of constraints like rules that the data must follow — like "You must enter your age" or
"Emails must be unique."
🔑 Types of Constraints in SQL:
Constraint Purpose

NOT NULL Ensures that a column cannot have NULL values

UNIQUE Ensures that all values in a column are different

PRIMARY KEY Combines NOT NULL + UNIQUE, used to uniquely identify each row

FOREIGN KEY Maintains relationship between two tables

CHECK Ensures values in a column satisfy a specific condition

DEFAULT Assigns a default value if none is provided

📌 Examples:
-- NOT NULL
CREATE TABLE Students (
ID INT NOT NULL,
Name VARCHAR(100) NOT NULL
);

-- UNIQUE
CREATE TABLE Users (
Email VARCHAR(100) UNIQUE
);

CHECK

Create TABLE USERS(


Age INT NOT NULL CHECK (ID>=18)
)

-- PRIMARY KEY
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(100)
);

-- FOREIGN KEY
CREATE TABLE Orders (
OrderID INT,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

-- CHECK
CREATE TABLE Products (
Price INT CHECK (Price > 0)
);

-- DEFAULT
CREATE TABLE Books (
Status VARCHAR(20) DEFAULT 'Available'
);
My Practice:

CREATE TABLE Employees (


EmpID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100) UNIQUE,
Email VARCHAR(50),
Age INT CHECK (Age >= 18)
);

CREATE TABLE Department (


DepID INT NOT NULL PRIMARY KEY,
EmpID INT NOT NULL,
DepartmentName VARCHAR(100),
FOREIGN KEY (EmpID) REFERENCES Employees(EmpID)
);

💡 Real-Life Example:
Let’s say you’re creating a Users table:
 You don’t want Username to be empty → NOT NULL
 You don’t want two users with the same email → UNIQUE
 You want to uniquely identify each user → PRIMARY KEY
 You want every user to have a default role of "Member" → DEFAULT

Would you like a mini-practice example to try some constraints yourself?


Foreign key:

Great question! Let's break it down clearly. 😊

🔗 "It points to the Primary Key in another table" means:


A Foreign Key in one table is used to connect to a Primary Key in another table — to
create a relationship between the two tables.

How to create a foreign key

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
🧠 Think of it like this:
Imagine two tables:
1. Departments table:
DeptID (PK) DeptName

1 HR

2 IT
Here, DeptID is a Primary Key — unique for each department.

 2. Employees table:
EmpID (PK) Name DeptID (FK)

101 Alice 1

102 Bob 2

103 Carol 1
Here:
 DeptID in Employees is a Foreign Key.
 It points to the DeptID in the Departments table.
 This means: "Every employee must belong to a department that exists."

🔍 Why is it called “pointing”?


Because it references the primary key value of the other table — as if it’s saying:
"Hey! My DeptID = 1 is linked to that department where DeptID = 1 in the Departments
table."

❌ What happens if you try to insert a value in Employees like:


INSERT INTO Employees (EmpID, Name, DeptID)
VALUES (104, 'David', 5);
...and DeptID = 5 doesn’t exist in Departments?
You’ll get an error:
"Foreign key constraint fails" — because 5 is not found in the primary key of the other
table.

Let me know if you'd like a visual diagram or real-world example (like students and schools)!

Absolutely! Let's go step by step and explain Primary Key, Foreign Key, and Unique Key
in the simplest way possible with examples 👇

🔑 1. Primary Key
A Primary Key is used to uniquely identify each record (row) in a table.
✅ Rules:
 Cannot be NULL
 Must be unique
 Only one primary key per table (but it can be on one or more columns – called
composite key)
🧠 Think of it as:
“An ID card number” – no two people can have the same ID and it can’t be empty.
📌 Example:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT
);
 Here, StudentID is the Primary Key — each student must have a unique and non-null
ID.

🔗 2. Foreign Key
A Foreign Key is used to create a relationship between two tables.
It points to the Primary Key in another table.
✅ Rules:
 It can contain duplicate and NULL values
 Ensures referential integrity – i.e., the value must exist in the parent table
🧠 Think of it as:
“A student enrolled in a course → that course must exist in the Courses table.”
📌 Example:
-- Parent table
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100)
);

-- Child table
CREATE TABLE Enrollments (
EnrollmentID INT PRIMARY KEY,
StudentID INT,
CourseID INT,
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
 Here, CourseID in the Enrollments table is a Foreign Key pointing to CourseID in
Courses.

🔒 3. Unique Key
A Unique Key ensures that all values in a column are different, but allows NULLs (only
one NULL if DB allows).
✅ Rules:
 Allows only unique values
 Allows NULL (unlike primary key)
 A table can have multiple unique keys
📌 Example:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE
);
 Here, Email must be unique, but can be NULL if not entered.

🧾 Summary Table:
Feature Primary Key Foreign Key Unique Key

Unique Values ✅ Yes ❌ Not required ✅ Yes

Null Allowed ❌ No ✅ Yes ✅ Yes (1 NULL)

One per Table ✅ Only one ❌ Can be many ✅ Can be many

Relation ❌ No ✅ Yes (to another) ❌ No

Would you like a small real-life example involving all 3 keys together in a mini project-style
example?

Composite key:

A composite key is a primary key (or unique key) that is made up of two or more columns
in a table.
 It is used when no single column uniquely identifies a record, but a combination of
columns does.

 🔹 Example:
 Imagine a table EmployeeProjects where an employee can work on multiple
projects, and each project can have multiple employees.
To uniquely identify each row, you need both EmpID and ProjectID.

CREATE TABLE EmployeeProjects (


EmpID INT NOT NULL,
ProjectID INT NOT NULL,
Role VARCHAR(50),
PRIMARY KEY (EmpID, ProjectID), -- ✅ Composite Key
FOREIGN KEY (EmpID) REFERENCES Employees(EmpID)
);
✅ Why use a composite key?
To avoid duplicate combinations of values.

Ensures uniqueness based on multiple columns.

Common in junction tables (many-to-many relationships).

Tricky Qurstions on keys

Sure! Here are some tricky and commonly asked interview questions on SQL constraints
like PRIMARY KEY, UNIQUE, and FOREIGN KEY — along with answers and
explanations that will help you stand out:
🔹 Q1: Can a table have more than one PRIMARY KEY?
❌ No, a table can have only one primary key, but...
✅ It can be a composite key (involving multiple columns).
PRIMARY KEY (UserID, Email)

🔹 Q2: Can a table have multiple UNIQUE constraints?


✅ Yes!
You can have multiple UNIQUE columns, unlike primary keys.
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE,
Phone VARCHAR(15) UNIQUE
);

🔹 Q3: What is the difference between UNIQUE and PRIMARY KEY?


Feature PRIMARY KEY UNIQUE

Null allowed? ❌ Not allowed ✅ One NULL allowed

Per table ❌ Only one allowed ✅ Multiple allowed

Purpose Uniquely identifies a row Ensures column values are unique

🔹 Q4: Can a FOREIGN KEY reference a UNIQUE key instead of PRIMARY KEY?
✅ Yes!
-- Parent table
CREATE TABLE Students (
RollNumber INT UNIQUE,
Name VARCHAR(100)
);

-- Child table
CREATE TABLE Marks (
Roll INT,
FOREIGN KEY (Roll) REFERENCES Students(RollNumber)
);

🔹 Q5: Can a FOREIGN KEY be NULL?


✅ Yes!
Foreign keys can accept NULLs, meaning the relationship is optional.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
You can insert a row with CustomerID = NULL.

🔹 Q6: Can a table reference itself using a FOREIGN KEY?


✅ Yes! This is called a self-referencing foreign key.
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
ManagerID INT,
FOREIGN KEY (ManagerID) REFERENCES Employees(EmpID)
);

🔹 Q7: Can two foreign keys point to the same parent table?
✅ Yes. A table can have multiple foreign keys, even pointing to the same parent.
CREATE TABLE Matches (
MatchID INT PRIMARY KEY,
TeamA INT,
TeamB INT,
FOREIGN KEY (TeamA) REFERENCES Teams(TeamID),
FOREIGN KEY (TeamB) REFERENCES Teams(TeamID)
);

🔹 Q8: What happens when the parent row is deleted in a foreign key relationship?
It depends on referential actions:
 RESTRICT / NO ACTION (default): Error if child exists
 CASCADE: Child rows deleted too
 SET NULL: Foreign key set to NULL
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
ON DELETE CASCADE

🔹 Q9: What if two rows have NULL in a UNIQUE column — is that allowed?
✅ Yes!
UNIQUE constraints allow one or more NULLs — because NULL is considered
"unknown", not equal.
INSERT INTO Users (Email) VALUES (NULL); -- Allowed
INSERT INTO Users (Email) VALUES (NULL); -- Also allowed

🔹 Q10: Can you define a FOREIGN KEY on a column that is not UNIQUE or
PRIMARY in the parent table?
❌ No.
The referenced column in the parent table must be either:
 A PRIMARY KEY
 Or a UNIQUE key

✅ Quick Trick Chart


Constraint Allows NULLs Multiple per table? Enforces Uniqueness

PRIMARY KEY ❌ No ❌ No ✅ Yes

UNIQUE ✅ Yes ✅ Yes ✅ Yes

FOREIGN KEY ✅ Yes ✅ Yes ❌ Depends on parent

Let me know if you want these turned into MCQs or SQL code quizzes to test yourself!
Triggers:

Awesome! Let’s dive into Triggers in SQL. 🚀

🔥 What is a Trigger in SQL?


A Trigger is a special kind of stored procedure that automatically runs when a certain
event happens in a table (like INSERT, UPDATE, or DELETE).
👉 You don’t call a trigger manually — the database engine fires it automatically when the
event occurs.

💡 Real-Life Analogy:
Imagine you have a security system in your house.
 When someone opens the door (event), the alarm goes off automatically (trigger).
 You didn’t press anything — it reacted to the event.

✨ Why Use Triggers?


 To enforce business rules
 To automatically log changes
 To validate or restrict data
 To cascade changes or calculations

🧠 Syntax (Example):
CREATE TRIGGER trgAfterInsert
ON Employees
AFTER INSERT
AS
BEGIN
PRINT 'New employee added!'
END
📚 Types of Triggers:
1. AFTER Triggers (or FOR triggers)
 Executes after the triggering event.
 Most commonly used.
 Used for logging, enforcing complex rules.
AFTER INSERT, AFTER UPDATE, AFTER DELETE

2. INSTEAD OF Triggers
 Executes instead of the triggering event.
 You can override what happens when an INSERT, UPDATE, or DELETE is issued.
 Useful on views or when you want custom logic instead of the default action.
INSTEAD OF INSERT, INSTEAD OF UPDATE

3. DDL Triggers (for schema changes)


 Fire when CREATE, ALTER, DROP commands are issued.
 Used to prevent unauthorized schema changes.
ON DATABASE
AFTER CREATE_TABLE, ALTER_TABLE, DROP_TABLE

4. LOGON Triggers
 Fires when a user logs in to SQL Server.
 Used for security audits, login restrictions.

✅ Example Use Case:


Let’s say you want to keep track of all deletions from an Orders table:
CREATE TRIGGER trgAfterDelete
ON Orders
AFTER DELETE
AS
BEGIN
INSERT INTO DeletedOrdersLog(OrderID, DeletedOn)
SELECT OrderID, GETDATE() FROM DELETED
END

Let me know if you'd like help creating one step-by-step!

so who defines or write the code for these triggers?


ChatGPT said:
Great question! 🙌
✅ Who defines or writes Triggers?
👉 You — the developer or database administrator (DBA) — are the one who defines and
writes the Trigger code, just like you'd write stored procedures or functions.

 Auditing
 Track who inserted, updated, or deleted records.
 Example: Log every time a salary is updated in the Employees table.
 Enforcing Business Logic
 Automatically prevent certain updates.
 Example: Prevent deleting a customer if they have pending orders.

DDL and DML


1. DDL – Data Definition Language
 Definition: DDL commands are used to define and manage database structure
(tables, schemas, etc.).
 Key point: They change the structure, not the data.
 Auto-commit: DDL commands are auto-committed (changes are permanent
immediately).
🔹 Common DDL Commands
Command Purpose

CREATE Create database objects (tables, views, etc.)

ALTER Modify structure (add/remove columns, constraints, etc.)

DROP Delete objects (tables, databases, etc.)

TRUNCATE Delete all data from a table but keep structure

RENAME Rename a database object

✅ 2. DML – Data Manipulation Language


 Definition: DML commands are used to manipulate the data inside database tables.
 Key point: They change data, not structure.
 Transactions: DML changes can be rolled back if inside a transaction.
🔹 Common DML Commands
Command Purpose

SELECT Retrieve data from tables

INSERT Add new rows

UPDATE Modify existing rows

DELETE Remove rows

✅ Example to understand better


sql
CopyEdit
-- DDL Example
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Name VARCHAR(100)
);

ALTER TABLE Employees ADD Email VARCHAR(50); -- modify structure

-- DML Example
INSERT INTO Employees VALUES (1, 'John Doe', 'john@example.com'); -- add data
UPDATE Employees SET Name = 'John Smith' WHERE EmpID = 1; -- modify data
DELETE FROM Employees WHERE EmpID = 1;

View:

"A View is a virtual table based on the result of a SQL SELECT query."

🔍 Let’s break it down:


✅ 1. "Virtual Table":
 A view looks and behaves like a table, but it doesn't store data physically.
 It only shows the data from other real tables when you query it.
 So it’s virtual — not stored permanently with data like a regular table.

✅ 2. "Based on a SQL SELECT query":


 The data in the view comes from a SELECT query that runs behind the scenes.
 Every time you select from a view, it runs that SELECT query in real-time to fetch
fresh data.

💡 Real-life Analogy:

Example:
Let’s say you have a table:
sql
CopyEdit
Employees
+----+--------+---------+
| Id | Name | Salary |
+----+--------+---------+
| 1 | Alice | 60000 |
| 2 | Bob | 75000 |
| 3 | Charlie| 70000 |
+----+--------+---------+
Now create a view:
sql
CopyEdit
CREATE VIEW HighEarners AS
SELECT Name, Salary
FROM Employees
WHERE Salary > 70000;
This view is just a stored SELECT query. It doesn't have any data.
But when you run:
sql
CopyEdit
SELECT * FROM HighEarners;
SQL Server will run the query, and you'll see:
text
CopyEdit
+------+--------+
| Name | Salary |
+------+--------+
| Bob | 75000 |
+------+--------+
If Bob's salary changes, or a new employee is added, the view result automatically reflects it
the next time you query it — because it's based on a SELECT.

🔁 Summary:
 A view = a named SELECT query = a virtual table.
 No data stored.
 Acts like a table when you query it.
 Always shows live data from the underlying tables.

Let me know if you’d like a visual diagram of how views work, or want to try a question to
test your understanding!
4o
You said:
wow great example , i understood it clearly
ChatGPT said:
Yesss! 🎉 I’m so glad that clicked for you! SQL can feel tricky at first, but once you get the
concepts like views, it really starts making sense.
If you want, we can go over:
 Stored Procedures vs Views
 Views vs Tables
 Or practice some real interview-style questions together
Just say the word — let’s crush this interview prep 💪🔥
4o
Done

Where clause:

WHERE Clause
 Used to filter rows before any grouping or aggregation happens.
 Applies to individual rows in a table.
 Comes before GROUP BY in the query.

please explain what is grouping first then explain what is groupby

Perfect! Let's slow it down and get crystal clear, starting from the absolute basics. 🙌

🔵 What is Grouping?
Grouping simply means:
Putting things that are similar into the same bucket.
You do this all the time in real life! For example:
👟 Real-life Example:
You work in a shoe store and want to group shoes by brand.
Shoe ID Brand Size

1 Nike 8

2 Adidas 9

3 Nike 10

4 Puma 9

5 Adidas 8
If you group by Brand, you get:
 Nike → Shoe IDs: 1, 3
 Adidas → Shoe IDs: 2, 5
 Puma → Shoe ID: 4
You’re not changing the data — you’re just organizing it into categories.
That's grouping.

🟡 Now — What is GROUP BY in SQL?


GROUP BY is the SQL command that lets you do this kind of grouping in a table — using
column values.
It tells SQL: "Take all rows with the same value in this column and treat them as a group, so
we can apply aggregate functions like SUM(), COUNT(), etc."

🧪 Table Example:
OrderID Customer Amount

1 Alice 100

2 Bob 150

3 Alice 200

4 Charlie 300
Now we want to group by Customer to find total purchases:
SELECT Customer, SUM(Amount) AS TotalSpent
FROM Orders
GROUP BY Customer;

✅ SQL will do this grouping:


 Alice → Orders 1 and 3 → 100 + 200 = 300
 Bob → Order 2 → 150
 Charlie → Order 4 → 300
Result:
Customer TotalSpent

Alice 300

Bob 150

Charlie 300

🧠 In Summary:
Concept Meaning

Grouping Organizing similar data into categories or sets

GROUP BY SQL's way to tell the database how to group rows based on a column

Let me know if you'd like to try a practice question on this or want me to show how GROUP
BY works in a real business use case (like sales, attendance, etc.) 🧑‍💻📊

Having clause:

Absolutely! Let’s lock in your understanding of the HAVING clause — it's closely tied to
what we just learned about GROUP BY, so you’re already 90% there! 🙌

🔶 What is the HAVING Clause?


The HAVING clause is used in SQL to filter groups — specifically, the ones created by a
GROUP BY clause.
Think of it as a WHERE clause for grouped data.
🧠 Concept Breakdown:
 WHERE filters individual rows before any grouping happens
 GROUP BY creates groups based on column values
 HAVING filters those groups, usually using aggregate functions (SUM(),
COUNT(), AVG(), etc.)

🔁 Think of it like this:


Clause Filters What? When?

WHERE Individual rows Before grouping

HAVING Groups of rows After grouping

🧪 Let’s use an example:


Suppose you have this table of sales:
OrderID Customer Amount

1 Alice 100

2 Bob 150

3 Alice 200

4 Bob 100

5 Charlie 90

🚀 Now run this query:


SELECT Customer, SUM(Amount) AS TotalSpent
FROM Orders
GROUP BY Customer
HAVING SUM(Amount) > 200;

🔍 What SQL does:


1. Groups rows by Customer:
o Alice: 100 + 200 = 300
o Bob: 150 + 100 = 250
o Charlie: 90
2. Applies HAVING filter:
o Only includes groups (customers) where total spent is more than 200

✅ Final result:
Customer TotalSpent

Alice 300

Bob 250
Charlie is filtered out by the HAVING clause, because his total is 90 (not > 200).

🔥 Real-life Analogy:
Imagine you're a store manager:
 You group sales by customer (GROUP BY)
 Now you only care about big spenders who bought more than ₹200 (HAVING)

📌 Key Rule:
You must use HAVING when filtering aggregated results, because WHERE can't use
aggregate functions like SUM() or COUNT().
So this is invalid:
-- ❌ This won't work:
SELECT Customer, SUM(Amount)
FROM Orders
WHERE SUM(Amount) > 200 -- ❌ ERROR
GROUP BY Customer;

🧠 Summary:
Clause Filters Can Use Aggregates? Works With Group By?

WHERE Rows ❌ No ✅ Yes

HAVING Groups ✅ Yes ✅ Yes


Want to try writing a GROUP BY + HAVING query yourself? I can give you a small practice
problem! 🧑‍💻💪

Having and where clause:

✅ Q125. What is the difference between HAVING clause and WHERE clause in SQL?
Both WHERE and HAVING are used to filter records, but they are used at different stages
in a SQL query and have different purposes.

🔍 1. WHERE Clause – Row-level filter


 Filters individual rows before any grouping or aggregation happens.
 Used with SELECT, UPDATE, DELETE statements.
 Cannot be used with aggregate functions like SUM(), COUNT(), etc.
✅ Example:
SELECT * FROM Employees
WHERE Department = 'Sales';

🔍 2. HAVING Clause – Group-level filter


 Filters grouped rows after aggregation (GROUP BY) has been done.
 Used only with GROUP BY.
 Can be used with aggregate functions like SUM(), COUNT(), etc.
✅ Example:
SELECT Department, COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
This will show only those departments that have more than 5 employees.

📊 Difference Table:
Feature WHERE Clause HAVING Clause

Filters on Individual rows Groups after aggregation


Feature WHERE Clause HAVING Clause

Used with SELECT, UPDATE, DELETE Only with GROUP BY

Aggregate allowed? ❌ Cannot use aggregate functions ✅ Can use aggregate functions

Executes when? Before grouping After grouping

💡 Real-world analogy:
 WHERE is like saying “only consider people from the Sales department”.
 HAVING is like saying “only show departments with more than 5 people”.

Let me know if you'd like a combined query example using both WHERE and HAVING.

Subquery , inner query or a nested query

Great! Let's jump into Q126: What is a Subquery / Nested Query / Inner Query in SQL?
(They all mean the same thing — just different names 😊)

🔍 Definition:
A subquery (also called a nested query or inner query) is a query inside another query.
It is used to fetch some intermediate result that the main (outer) query can use.
You place a subquery inside:
 a WHERE, FROM, or SELECT clause
 inside parentheses: (SELECT ...)

🔁 Real-Life Analogy:
Imagine you’re hiring someone:
 First, you ask HR: “Who has the highest score?” ➝ this is the subquery
 Then, based on that answer, you call that person for interview ➝ this is the main
query
So you’re using the result of one question to ask another question.

🧪 Example 1: Subquery in WHERE clause


Suppose you have a table:
Employees:
EmpID Name Salary

1 Alice 50000

2 Bob 60000

3 Carol 70000
Let’s say you want to find the employee with the highest salary:
SELECT Name, Salary
FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees);
🔹 Here:
 (SELECT MAX(Salary) FROM Employees) is the subquery
 It returns 70000
 The outer query then returns the employee with that salary
✅ Output:
Name Salary

Carol 70000

🧪 Example 2: Subquery in FROM clause


You can even create a temporary table using a subquery:
SELECT AVG(Salary) AS AvgSalary
FROM (SELECT Salary FROM Employees WHERE Salary > 50000) AS HighEarners;
Here:
 The subquery creates a filtered set of employees
 The outer query calculates the average salary of that group

🧠 Types of Subqueries:
Type Description

Scalar Returns a single value

Row Returns one row of multiple columns

Table Returns a full table or multiple rows

Correlated Refers to columns from the outer query

✅ Summary:
Feature Subquery / Nested Query

Defined as A query inside another query

Purpose To use intermediate results in main query

Used in SELECT, WHERE, FROM, etc.

Returns Single value, row, or table

Enclosed in Parentheses ( )

Let me know if you want to explore correlated subqueries next (they’re also common in
interviews), or try a mini challenge to test this! 🚀

Aggregate functions:

Aggregate functions perform a calculation on a group of rows and return a single value.

SUM() Adds up values Total sales, total salary, etc.

AVG() Calculates average Average score, average price

COUNT() Counts how many rows (or non-null values) How many employees, orders, etc.

MIN() Finds the smallest value Lowest salary, earliest date

MAX()

Identity column and auto increment:


Awesome! Let’s break down Q127 step by step. This question has three parts, so we’ll go
through each clearly:

✅ 1. What is Auto Increment / Identity Column in SQL Server?


🔹 Definition:
In SQL Server, an identity column is a column where the values are generated
automatically when a new row is inserted.
It's commonly used for primary keys, where each row needs a unique ID.

🧪 Example:
Let’s say you're creating a Users table:
CREATE TABLE Users (
UserID INT IDENTITY(1,1), -- auto-increment starts at 1, increases by 1
UserName VARCHAR(100)
);
Here:
 UserID will automatically be filled with values like 1, 2, 3, 4, ...
 You don’t need to insert UserID manually — SQL Server takes care of it.
INSERT INTO Users (UserName) VALUES ('Alice');
-- Automatically sets UserID = 1

INSERT INTO Users (UserName) VALUES ('Bob');


-- Automatically sets UserID = 2

🔑 Syntax:
COLUMN_NAME DATA_TYPE IDENTITY(start, increment)
E.g., IDENTITY(100, 5) will start at 100 and add 5 each time → 100, 105, 110...

🚫 Important:
 You cannot insert values manually into an identity column unless you override it
using SET IDENTITY_INSERT.
set manually off the column usin SET IDENTITY_INSERT

✅ 2. What is a Database?
A database is like a digital filing cabinet. It’s a collection of organized data that can be
easily accessed, managed, and updated.
In SQL Server, a database contains everything related to your application’s data.
🔹 Contains:
 Tables
 Views
 Stored procedures
 Triggers
 Functions
🏢 Real-Life Analogy:
A database is like a library:
 Each book is a table
 Each page is a record
 The library system lets you search, add, or update info

✅ 3. What is a Table?
A table is the basic storage unit in a database.
It’s where your data is actually stored in rows and columns — like an Excel sheet.

🔹 Example Table: Students


StudentID Name Age

1 Alice 20

2 Bob 21
Each row = one record (a student)
Each column = a field (like Name, Age)

🧠 In Summary:
Term Meaning

Identity Column Auto-generates numeric values (like unique IDs) for new rows

Database A collection of related data and structures, like a whole application

Table Stores data in rows and columns inside a database

Let me know if you want to create a sample table with IDENTITY or explore more related
concepts like primary keys, constraints, or foreign keys! 🔐💾

What are Joins in SQL?


A JOIN in SQL is used to combine rows from two or more tables based on a related column
between them.
Imagine you have:
A Customers table with CustomerID, Name
An Orders table with OrderID, CustomerID, OrderDate
If you want to see each customer along with their orders, you use a JOIN to pull data from
both tables where CustomerID matches.
📌 Why Use Joins?
To query related data from multiple tables.
To avoid storing duplicate data in one big table (this is called normalization).
To get meaningful combined results, like a report or dashboard.

What is Normalization?
Normalization is the process of organizing data in a structured way across multiple tables
to:
 Avoid duplicate (redundant) data
 Improve data integrity
 Make updates easier and consistent
🔁 Why Avoid Duplicates?
Imagine if you had one big table like this:
OrderID CustomerName CustomerEmail ProductName OrderDate

101 Rahul rahul@email.com Shoes 2024-04-01

102 Rahul rahul@email.com Jacket 2024-04-03

103 Neha neha@email.com Watch 2024-04-04


Here, Rahul's name and email are repeated for every order — that's redundancy.

✅ With Normalization
We split this into two tables:
Customers Table:
CustomerID Name Email

1 Rahul rahul@email.com

2 Neha neha@email.com
Orders Table:
OrderID CustomerID ProductName OrderDate

101 1 Shoes 2024-04-01

102 1 Jacket 2024-04-03

103 2 Watch 2024-04-04


Now:
 Rahul’s details are stored only once.
 CustomerID connects the two tables using a foreign key.

Types of Joins:

Exactly! 💯 You got it! For a RIGHT JOIN, it’s the exact opposite of a LEFT JOIN.

✅ Right Join — Simple Definition


A RIGHT JOIN returns:
🔹 All rows from the right table,
🔹 And only the matching rows from the left table,
🔹 If there's no match, the left side is filled with NULL.

🧩 Example:
SELECT Customers.Name, Orders.Product
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
 Right Table = Orders
 Left Table = Customers
So this query will return:
 ✅ All orders
 ✅ And the customer name only if it exists
 ❌ If a customer is missing (e.g., order placed without a customer match), the Name
will be NULL

🔁 Summary of JOINs:
Join Type Returns All Rows From Matches From

INNER JOIN Only matching rows Both tables

LEFT JOIN Left table Right table (if matched)

RIGHT JOIN Right table Left table (if matched)

FULL JOIN Both tables All matches + non-matches with NULLs

Would you like a real-world analogy to make this even more fun to remember? 😄

Absolutely! Let’s break down Self Join in a very simple and easy-to-understand way:

🔁 What is a Self Join?


A Self Join is when a table is joined to itself.
You use it when the rows in the same table are related to each other.
✅ It's useful for scenarios like employee-manager relationships, where both employees and
managers are stored in the same table.

🧩 Example Scenario: Employees Table


EmployeeID Name ManagerID

1 John NULL

2 Sarah 1

3 David 1

4 Emma 2
 Here, Sarah and David report to John (ManagerID = 1)
 Emma reports to Sarah (ManagerID = 2)
We want to display each employee with their manager’s name.

🧪 Self Join SQL Query


SELECT
E.Name AS EmployeeName,
M.Name AS ManagerName
FROM
Employees E
JOIN
Employees M ON E.ManagerID = M.EmployeeID;
 We're treating the same Employees table as two separate roles:
o E = Employee
o M = Manager

🧾 Output:
EmployeeName ManagerName

Sarah John

David John

Emma Sarah
🧠 In Simple Words:
A Self Join is just like saying:
"In this table, some rows are related to other rows. Let’s match them together."
You give the same table two different nicknames (E and M) to make it work!

Want me to explain this using a real-life office example or diagram-style? 😊

please simplify the query of the self join

Exactly! Great observation 👏 — and that's the magic of self join!


You're right:
The Employees table doesn’t have a column called ManagerName, only Name and
ManagerID.
So how do we get the manager's name?
👉 By joining the table with itself!

✅ Here's the trick:


We use the Name column twice, because:
 One copy of the table gives us the employee's name.
 The other copy of the same table gives us the manager's name.
Let’s look again:
SELECT
E.Name AS EmployeeName, -- From employee row
M.Name AS ManagerName -- From manager row
FROM
Employees E,
Employees M
WHERE
E.ManagerID = M.EmployeeID;
🔁 What’s going on?
Table Copy Alias Role Column used

1st copy E Employee E.Name

2nd copy M Manager M.Name


 E.ManagerID = M.EmployeeID connects the employee to their manager.
 Even though there’s no ManagerName column, we get it by looking up the Name
from the second row (manager).

📊 Visual Example
EmployeeID Name ManagerID

1 John NULL

2 Sarah 1

3 David 1

4 Emma 2
Let's walk through one row:
 Emma's ManagerID = 2
 Look for EmployeeID = 2 → that’s Sarah
 So:
o E.Name = Emma
o M.Name = Sarah
🎉 That’s how we get Manager Name from the same table!

Let me know if you want a visual diagram or want to practice writing one yourself—I’ll help
you through it!

so managerID is basically equals EmployeeID


Indexes:

Absolutely! Here are clean, structured notes you can use directly to make your personal
notes:

📘 SQL Index – Notes


🔹 What is an Index in SQL?
 An Index is a database object that improves the speed of data retrieval.
 It works like a table of contents or an index in a book – allowing the database to
quickly locate rows. Indexing is applied after where join orderby columns
 WHERE ✅ Yes Used for filtering
 JOIN ✅ Yes Joins often need lookup speed
 ORDER BY ✅ Yes Helps with sorting performance
 GROUP BY ✅ Yes Speeds up grouping

🔹 Why Use an Index?


 Without an index: SQL performs a full table scan (checks every row).
 With an index: SQL jumps directly to the desired rows using a sorted structure.

🔹 How Does an Index Work?


 SQL creates a separate structure (often a B-tree) that:
o Keeps values sorted.
o Stores row pointers (references to actual data in the table).
 SQL performs a binary search on the index → then jumps to the actual row.

🔹 Real-Life Analogy
 A phonebook is sorted by name.
 To find "Rahul", you don’t read every page.
 You jump to the right page using the sorted list — that's what an index helps SQL do.

🔹 Types of Indexes
1. Clustered Index
o Sorts the actual table data based on the index column.
o Only one clustered index per table.
o Example: Primary key creates a clustered index by default.
o When you create a PRIMARY KEY constraint, a clustered index on the
column is automatically created
2. Non-Clustered Index
o Keeps a copy of the sorted column + a pointer to the actual row.
o You can create multiple non-clustered indexes.

🔹 Creating an Index
CREATE INDEX idx_Email ON Employees(Email);

🔹 When Not to Use Indexes


 On columns that are frequently updated.
 On small tables (index overhead is not worth it).
 On columns with very few distinct values (e.g., Yes/No, Male/Female).

Let me know if you’d like a quick diagram or visual added to this!

Clustered and Non clustered Indexes:

Great question! Understanding clustered and non-clustered indexes is super important for
optimizing performance in SQL Server (and interviews love this topic! 😄). Let’s break it
down clearly and simply.

✅ What is an Index in SQL?


An index is like a table of contents in a book — it helps SQL Server find rows faster
without scanning the whole table.

📌 There are 2 main types of indexes:


Type Key Idea

Clustered Index Sorts and stores the actual data rows in order of the index

Non-Clustered Index Has a separate structure — like a pointer to the data rows

🔹 1. Clustered Index
 There can be only ONE clustered index per table
 Because the data rows themselves are stored in the sorted order
 It defines the physical order of rows in the table
🧠 Think of:
Book chapters — pages are physically arranged chapter by chapter

🧪 Example:
CREATE CLUSTERED INDEX IX_Employees_ID
ON Employees (EmployeeID);
Now, the Employees table will be physically sorted by EmployeeID.

🔸 2. Non-Clustered Index
 There can be many non-clustered indexes on a table
 It stores only the index (not the data), along with pointers to the actual rows
 Think of it as a lookup table
🧠 Think of:
Book glossary — it lists keywords and page numbers (pointers)

🧪 Example:
CREATE NONCLUSTERED INDEX IX_Employees_Name
ON Employees (EmployeeName);
This helps SQL quickly find employees by name, using the index.

🔍 Key Differences:
Feature Clustered Index Non-Clustered Index

Stores actual data rows in index Stores only keys and a pointer to the
Data Storage
order data

Number per table Only one Multiple allowed

Sorting Physically sorts the table Does not sort the actual table

Speed (in Faster for range queries, PK


Good for searching specific columns
general) lookups

🎯 Real-life Analogy:
Concept Example

Clustered Index Chapters in a book (physical order)

Non-Clustered Index at back of book (lookup list)

Common Use Cases:


 Use a clustered index on the column most frequently used to retrieve ranges or sort
data
 Use non-clustered indexes on columns used in search conditions (WHERE, JOIN,
etc.)

Let me know if you’d like:


 Visual diagram for this
 Practice questions on indexing
 Examples of performance difference
You're absolutely crushing SQL concepts! 🚀🔥
Other types:
3. Unique Index
 Ensures that no duplicate values exist in the indexed column.
 Automatically created when you define a UNIQUE constraint.
sql
CopyEdit
CREATE UNIQUE INDEX idx_UniqueEmail ON Employees(Email);

🔸 4. Composite Index (Multi-Column Index)


 An index on two or more columns.
 Useful when you filter/sort using multiple columns together.
sql
CopyEdit
CREATE INDEX idx_NameDept ON Employees(FirstName, Department);

🔸 5. Filtered Index
 A non-clustered index with a WHERE clause.
 Useful for indexing only a portion of rows.
sql
CopyEdit
CREATE INDEX idx_ActiveEmp ON Employees(Status)
WHERE Status = 'Active';

🔸 6. Full-Text Index
 Used for searching text data (e.g., in a column with large text).
 Enables searching phrases, words, inflections

Functions and stored


procedures:
Definition:
📌 Stored Procedure:
A stored procedure is a group of SQL statements that you can save and reuse. It can perform
operations like insert, update, delete, and even call other procedures.

📌 Function:
A function (or user-defined function) is a SQL object that returns a single value or a table,
and it's usually used for calculations or returning data.
Feature Stored Procedure Function (UDF)

Can return 0, 1, or many values using Must return 1 value (scalar or


Return Type
OUT params table)

Usage in ✅ Can be used inside SELECT,


❌ Cannot be used in SELECT directly
SELECT WHERE, etc.

✅ Can use INSERT, UPDATE, ⚠️Scalar: ❌ Cannot use DML


DML Support
DELETE Table-valued: ✅ Read-only

Transaction ✅ Can manage transactions (BEGIN,


❌ Cannot handle transactions
Control COMMIT, etc.)

Output ❌ Doesn’t support OUT


✅ Supports OUT parameters
Parameters parameters

Exception
✅ Can use TRY...CATCH ⚠️Limited or no error handling
Handling

Compilation Compiled once and stored Compiled each time it is used


Example:

🧪 Example
🔹 Stored Procedure:
sql
CopyEdit
CREATE PROCEDURE GetStudentByClass
@className NVARCHAR(50)
AS
BEGIN
SELECT * FROM student WHERE class = @className
END
🔹 Function (Scalar):
sql
CopyEdit
CREATE FUNCTION GetTotalMarks (@studentId INT)
RETURNS INT
AS
BEGIN
DECLARE @total INT
SELECT @total = SUM(marks) FROM marks WHERE student_id = @studentId
RETURN @total
END

How to improve performance of an SP and sql query?

Great question! 🔥 Optimizing SQL queries and stored procedures is super important — not
just for interviews, but also for real-world performance in large applications like ASP.NET
MVC systems.
Here’s a clear and practical guide you can use in your notes or interviews. 👇

🚀 Q138. How to Optimize a Stored Procedure or SQL Query?

✅ 1. Use Proper Indexing


 Index columns used in:
o WHERE, JOIN, GROUP BY, ORDER BY
 Use covering indexes to avoid reading table data
✅ Example:
CREATE NONCLUSTERED INDEX idx_Student_Name ON Student(Name);

✅ 2. Avoid SELECT * (select only required columns)


 SELECT * fetches unnecessary data and slows down performance
✅ Instead, use:
SELECT Name, Age FROM Student;

✅ 3. Use WITH (NOLOCK) for read-only queries


 Avoids locking when you're only reading data ⚠️Use with caution: it may return dirty
reads
✅ Example:
SELECT Name FROM Student WITH (NOLOCK);
✅ 4. Use SET NOCOUNT ON in Stored Procedures
 Prevents sending extra "rows affected" messages to the client
 Reduces network traffic, especially in loops
✅ Example:
CREATE PROCEDURE MyProc
AS
BEGIN
SET NOCOUNT ON;
-- Your SQL logic
END

✅ 5. Avoid Cursors (use set-based operations)


 Cursors are row-by-row and slow
 Instead, use set-based operations with JOIN, UPDATE, or MERGE

✅ 6. Use EXISTS instead of COUNT(*) > 0


 EXISTS stops after finding the first match (faster)
✅ Example:
-- Bad
IF (SELECT COUNT(*) FROM Orders WHERE CustomerID = 1) > 0

-- Good
IF EXISTS (SELECT 1 FROM Orders WHERE CustomerID = 1)

✅ 7. Use TRY...CATCH to handle errors properly


 Prevents query failure and allows logging or rollback
✅ Example:
BEGIN TRY
-- SQL logic
END TRY
BEGIN CATCH
-- Error handling
END CATCH

✅ 8. Use Temporary Tables or Table Variables wisely


 Use #temp tables for large, complex datasets
 Use @table variables for small, in-memory operations

✅ 9. Keep JOINs Efficient


 Join only required tables
 Use INNER JOIN when possible instead of OUTER JOIN (unless needed)
 Ensure indexed columns are used in JOINs

Avoid unwanted coverting from varchar to other types


Temp tables
No nested queries
view

✅ 10. Use SP_EXECUTESQL for dynamic SQL with parameters


 Safer, faster, and supports query plan reuse
✅ Example:
EXEC sp_executesql N'SELECT * FROM Student WHERE Name = @Name',
N'@Name NVARCHAR(50)',
@Name = 'Happy';

✅ 11. Check and Update Statistics & Rebuild Indexes


 Outdated stats and fragmented indexes reduce performance
UPDATE STATISTICS Student;
ALTER INDEX ALL ON Student REBUILD;
🧠 Bonus Tips for ASP.NET MVC Applications:
 Call stored procedures with parameterized queries to avoid SQL Injection
 Use Entity Framework stored procedure mappings efficiently
 Use asynchronous DB calls for long-running procedures

Let me know if you'd like:


 A real stored procedure to optimize
 A quick quiz to test these concepts
 A printable PDF version of these notes 📝
You're crushing it — interviewers will love how clearly you understand performance tuning!
🚀🔥

what is SET NOCOUNT , SP_EXECUTESQL and cursor and Dynamic SQL

Awesome! Let’s explain each one of these clearly and simply. These are frequently asked in
interviews, especially for optimizing stored procedures and working with dynamic SQL in
real apps like ASP.NET MVC.

---

## ✅ 1. What is `SET NOCOUNT ON`?

### 📌 Meaning:
Tells SQL Server **not to send the “X rows affected” message** after each statement.

### 🧠 Why use it?


- Saves network traffic and improves performance
- Useful inside **Stored Procedures**, especially when using loops or multiple statements

### 🔍 Example:
```sql
CREATE PROCEDURE GetStudents
AS
BEGIN
SET NOCOUNT ON;

SELECT * FROM Students;


UPDATE Students SET Status = 'Active' WHERE Status IS NULL;
END
```

Without `SET NOCOUNT ON`, SQL sends messages like:


```
(10 row(s) affected)
(5 row(s) affected)
```

With `SET NOCOUNT ON`, these messages are **not sent**, making your code cleaner and
faster 🚀

---

## ✅ 2. What is `sp_executesql`?

### 📌 Meaning:
A **system stored procedure** used to run **dynamic SQL** safely with **parameters**.

### 🧠 Why use it?


- Prevents SQL injection (when used with parameters)
- Helps SQL Server **reuse query plans** (performance boost!)
- Safer than using `EXEC('...')` directly

### 🔍 Example:

```sql
DECLARE @sql NVARCHAR(MAX)
DECLARE @id INT = 5

SET @sql = N'SELECT * FROM Students WHERE StudentID = @ID'

EXEC sp_executesql @sql, N'@ID INT', @ID


```

This avoids SQL injection and is great for dynamic WHERE clauses, sorting, etc.

---

## ✅ 3. What is a **Cursor**?

### 📌 Meaning:
A **cursor** is a database object that allows **row-by-row** processing of a result set.

### 🧠 Why use it?


- When you **must loop** through rows individually (not recommended unless necessary)
- Used in complex row-level operations where set-based logic doesn't work

### 🔍 Example:

```sql
DECLARE student_cursor CURSOR FOR
SELECT Name FROM Students

DECLARE @name NVARCHAR(50)

OPEN student_cursor
FETCH NEXT FROM student_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
FETCH NEXT FROM student_cursor INTO @name
END

CLOSE student_cursor
DEALLOCATE student_cursor
```

⚠️**Downsides of cursors:**
- **Slow** — processes one row at a time
- Use **set-based operations** (`UPDATE`, `MERGE`, `JOIN`) instead whenever possible

---

## 🧠 TL;DR Summary:

| Concept | Description | Use Case |


|----------------|-------------------------------------------------------------------|----------------------------
--------|
| `SET NOCOUNT ON` | Stops “rows affected” messages | Improve
performance in procedures |
| `sp_executesql` | Executes dynamic SQL safely with parameters | Dynamic
queries, SQL injection safe |
| Cursor | Loops over rows one-by-one | Rare cases when row-
level logic is needed |

---

Let me know if you want practical examples for any of these in an ASP.NET context or want
a quick quiz to reinforce your learning! You're doing amazing 🙌

✅ What is Dynamic SQL?


Dynamic SQL means:
👉 Writing SQL queries as strings, and executing them at runtime, not compile-time.
It's like building the SQL query on the fly, depending on user input, filters, or conditions.

🔧 Why use Dynamic SQL?


Because sometimes:
 You don’t know what columns to filter on ahead of time
 You want to add conditions dynamically based on parameters
 You want flexible queries (e.g., search filters, sorting, table names, etc.)

🧠 Example Scenario:
Suppose you have a search form in your ASP.NET MVC app where a user can filter students
by class, section, or name.
You don’t want to write 10 different queries — instead, you dynamically build the WHERE
clause depending on what the user entered.

🔍 Basic Example (Bad way — prone to SQL injection ⚠️)


sql
CopyEdit
DECLARE @query NVARCHAR(MAX)
DECLARE @class NVARCHAR(50) = '10A'
SET @query = 'SELECT * FROM Students WHERE Class = ''' + @class + ''''
EXEC(@query)
🛑 Not safe — allows SQL injection.

🔐 Safer Way Using sp_executesql (Dynamic SQL with parameters):


sql
CopyEdit
DECLARE @sql NVARCHAR(MAX)
DECLARE @class NVARCHAR(50) = '10A'

SET @sql = N'SELECT * FROM Students WHERE Class = @Class'


EXEC sp_executesql @sql, N'@Class NVARCHAR(50)', @Class
✅ Safe and efficient — supports parameterization, avoids injection, and reuses execution
plans.

@@IDENTITY:

📌 Definition:

Returns the last identity value inserted in the current session, regardless of scope.

❗ Problem:

If a trigger inserts into another table with an identity column, @@IDENTITY will return

that value, not the one you actually wanted.

How this works:


Let’s clarify this: @@IDENTITY does not know you wanted “Mango Juice” (the ID from

your own insert). That’s actually the problem with it!

💣 Why @@IDENTITY Can Be Confusing

When you run this:

sql

CopyEdit

INSERT INTO Orders (ProductName) VALUES ('Mango Juice')

SQL Server:

1. Inserts the row in Orders (creates OrderID = 1).

2. Automatically fires a trigger (if you have one), and that trigger:

o Inserts a row into another table (like OrderLog).

o That log table also has an identity column (LogID = 100).

3. Now SQL Server says:

“The last identity value inserted in this session was LogID = 100.”

So @@IDENTITY = 100 ❌

But that’s not the one you inserted — that came from a trigger.

⚙️2. SCOPE_IDENTITY()

📌 Definition:
Returns the last identity value inserted in the same scope (i.e., same batch, procedure,

trigger, etc.)

✅ It ignores inserts from triggers or nested scopes.

What is an Identity Value in SQL?

An Identity value is an auto-incremented number that SQL Server automatically generates

for a column when you insert a new row.

It's commonly used for primary keys, like ID, to uniquely identify each

Function What it does

Returns the last identity in the session, even if it’s inside a trigger
@@IDENTITY

SCOPE_IDENTITY() Returns the last identity in the current scope only ✅

Session, scope bactch

Term Meaning Example

Connection between app/user and SQL Each tab in SSMS or user request in
Session
Server ASP.NET

Scope Current block of code (proc, trigger, INSERT in proc = one scope; trigger that
dynamic SQL) fires = another

Batch Group of statements run together Code between GO statements or one F5 execution

Function What it does

@@IDENTITY Returns the last identity in the session, even if it’s inside a trigger ❌

SCOPE_IDENTITY() Returns the last identity in the current scope only ✅

Great! Let’s dive into CTE (Common Table Expression) — a super handy feature in SQL

Server that makes queries easier to write and understand. 🙌

✅ What is a CTE in SQL Server?

CTE stands for Common Table Expression.

It’s like creating a temporary result set (virtual table) that you can reuse in your query —

very useful for simplifying complex joins, subqueries, and even recursive queries.

📌 Basic Syntax:

WITH CTE_Name AS (

-- Your SELECT statement

SELECT ...

SELECT * FROM CTE_Name


🎯 Example 1: Simplify a Query

Let's say you want to find all employees with a salary above average:

-- Without CTE (using subquery):

SELECT Name, Salary

FROM Employees

WHERE Salary > (

SELECT AVG(Salary) FROM Employees

✅ Same thing with a CTE:

WITH SalaryCTE AS (

SELECT Name, Salary FROM Employees

SELECT * FROM SalaryCTE

WHERE Salary > (SELECT AVG(Salary) FROM SalaryCTE)

🔍 This is easier to read, debug, and reuse!

🔁 Example 2: Recursive CTE (for hierarchical data)

Let’s say you have an Employees table with a manager-employee relationship:

WITH EmployeeHierarchy AS (

-- Anchor (top-level manager)


SELECT ID, Name, ManagerID, 0 AS Level

FROM Employees

WHERE ManagerID IS NULL

UNION ALL

-- Recursive part (find direct reports)

SELECT e.ID, e.Name, e.ManagerID, eh.Level + 1

FROM Employees e

INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.ID

SELECT * FROM EmployeeHierarchy

This builds a full reporting hierarchy!

✅ Benefits of CTE

Benefit Description

Improves readability Makes complex queries more understandable

Reusable within the query Can use the CTE multiple times in the same query

Allows recursion Easy way to write hierarchical or tree queries


Benefit Description

Better for debugging You can isolate the logic in chunks

⚠️Notes

 CTEs only live during the execution of the query. They’re not stored in the

database.

 You can use multiple CTEs in one query.

 They must come right before the main SELECT / INSERT / UPDATE / DELETE.

✅ TL;DR

A CTE (Common Table Expression) is a temporary named result set that you can reference

just like a table in your query. It helps you write cleaner, easier-to-read SQL — especially

when you're dealing with complex logic or recursion.

Let me know if you want to write some real examples with CTEs (e.g., top N per group,

duplicates, tree structures), or how to use them inside a Stored Procedure or View. You're

mastering SQL step by step! 🚀

Truncate Delete Drop

Awesome — this is a classic and important interview question in SQL! Let’s break down

the difference between DELETE, TRUNCATE, and DROP with clear explanations, a

comparison table, and examples.


🧨 Definitions

1. DELETE

 Used to remove specific rows from a table based on a condition.

 Can be rolled back (if inside a transaction).

 Fires triggers (if any exist).

 Table structure and schema remain intact.

DELETE FROM Employees WHERE Department = 'HR';

2. TRUNCATE

 Removes all rows from a table — faster than DELETE.

 Cannot delete specific rows (no WHERE clause).

 Cannot be rolled back (in most cases).

 Does not fire triggers.

 Resets identity columns (if any).

TRUNCATE TABLE Employees;

3. DROP

 Completely removes the table (structure + data) from the database.

 Cannot be rolled back.


 All dependencies like indexes, constraints, and triggers are deleted too.

DROP TABLE Employees;

📊 Comparison Table

Feature DELETE TRUNCATE DROP

Removes specific ✅ Yes (WHERE ❌ No — removes the


❌ No — removes all rows
rows clause) whole table

Can be rolled ✅ Yes (if in a ⚠️No (non-logged, cannot


❌ No
back transaction) rollback)

Fires Triggers ✅ Yes ❌ No ❌ No

Affects table
❌ No ❌ No ✅ Yes (structure is gone)
structure

Resets identity ❌ No ✅ Yes ❌ N/A (table is dropped)

🐢 Slower (row by
Speed ⚡ Faster ⚡ Fastest
row)

🧠 When to Use What?

 ✅ DELETE – When you need to remove specific data and want logging and

rollback support.

 ⚡ TRUNCATE – When you need to quickly delete all data from a table but keep the

structure.
 💣 DROP – When you want to completely remove the table from the database.

💡 Pro Tip for Interviews:

If they ask “Can TRUNCATE be rolled back?”

Say: “By default, no, because it’s minimally logged. But in explicit transactions, some

systems like SQL Server may allow rollback.”

Let me know if you'd like to try hands-on practice with these or simulate what happens

during a transaction. You're leveling up fast! 🔥📘

Nth highest salary

SELECT DISTINCT Salary

FROM Employees

ORDER BY Salary DESC

OFFSET 2 ROWS FETCH NEXT 1 ROW ONLY;

ACID Properties

Great question! 🔥 Understanding ACID properties is super important for database concepts

and interviews — especially in SQL Server and relational database systems.

✅ What Are ACID Properties?


ACID is an acronym that stands for the four key properties of a reliable transaction in a

database system:

💡 A transaction is a single unit of work that either completes fully or fails fully — no

halfway done!

🧪 A — Atomicity

 All or nothing

 A transaction must be fully completed or fully rolled back.

 No partial changes are saved to the database.

Example:

BEGIN TRANSACTION;

UPDATE Account SET Balance = Balance - 100 WHERE AccountID = 1;

UPDATE Account SET Balance = Balance + 100 WHERE AccountID = 2;

COMMIT;

If any update fails, the entire transaction is rolled back.

🔒 C — Consistency

 Ensures that the database stays in a valid state before and after the transaction.

 All rules, constraints, relationships are preserved.


Example:

If a product's stock becomes negative due to a bug — that would violate consistency. The

system ensures it doesn't happen.

🤝 I — Isolation

 Ensures that concurrent transactions don’t interfere with each other.

 Each transaction should behave as if it’s the only one running.

Example: If two users transfer money at the same time, their transactions shouldn't clash or

read each other's intermediate (dirty) data.

SQL Server supports different isolation levels like:

 Read Committed (default)

 Repeatable Read

 Serializable

 Snapshot

🔄 D — Durability

 Once a transaction is committed, the changes are permanent, even if there's a crash

or power failure.

 SQL Server uses transaction logs to ensure this.


Example:

You commit a bank transfer. Even if the system crashes right after, the money won’t

"disappear" — it’s saved.

🧠 Summary Table

Property Description Example

Bank transfer: both accounts must


Atomicity All or none execution
update

Consistency Valid state before & after transaction Stock level can't go negative

No overlap between concurrent


Isolation Users editing same row won't clash
transactions

Durability Changes survive crashes/power loss Committed data stays safe

Let me know if you'd like to see how ACID applies in SQL Server transactions or stored

procedures, or how it's handled in Entity Framework in .NET. You’re killing it! 💥

✅ What is a "Valid State" in a Database?

A valid state means the data in the database follows all rules, constraints, and

relationships defined for it.

These rules can include:


Once a transaction is committed, the changes are permanent, even if there's a crash or power

failure. how?

ChatGPT said:

Awesome question 🔥 — you're really thinking like a database engineer now! Let’s break it

down step by step.

✅ Statement:

Once a transaction is committed, the changes are permanent, even if there’s a crash or

power failure.

This is the Durability part of the ACID properties.

🧠 How is this possible?

The secret lies in something called the Transaction Log (also called Write-Ahead Logging)

— used by databases like SQL Server, MySQL, Oracle, etc.

📘 What is a Transaction Log?

 It’s a special file where every change (INSERT, UPDATE, DELETE) is written

FIRST before it's applied to the actual database.

 This log ensures that SQL Server can recover the database in case of a crash or power

failure.
Magic tables:

Great question! ✨ The term "Magic Tables" in SQL Server sounds fancy, but it's actually a

nickname for something very practical and important when working with triggers.

✅ What are Magic Tables?

In SQL Server, Magic Tables refer to the inserted and deleted temporary (virtual) tables

that are automatically created behind the scenes when a trigger is fired.

These are not physical tables in the database — they’re in-memory and only available

during the execution of a trigger.

🧠 Where are Magic Tables Used?

In DML triggers:

 AFTER INSERT

 AFTER UPDATE

 AFTER DELETE

 INSTEAD OF triggers

🪄 The Two Magic Tables:

Table Name What It Holds Used In Triggers

inserted New rows that were inserted or updated INSERT, UPDATE


Table Name What It Holds Used In Triggers

deleted Old rows that were deleted or updated DELETE, UPDATE

🎯 Example: Let's say we have a table:

CREATE TABLE Employees (

EmpID INT,

Name NVARCHAR(100),

Salary INT

);

And you create an AFTER UPDATE trigger:

CREATE TRIGGER trg_AfterSalaryUpdate

ON Employees

AFTER UPDATE

AS

BEGIN

SELECT * FROM inserted; -- New updated rows

SELECT * FROM deleted; -- Old values before update

END

🔍 What happens when you run:


UPDATE Employees

SET Salary = 60000

WHERE EmpID = 1;

 deleted will have the old row (with old salary)

 inserted will have the new row (with updated salary)

💡 Use Cases:

 Auditing changes

 Logging changes to another table

 Preventing unwanted updates

 Enforcing business rules

✅ Summary:

Magic Table Trigger Type Contains

inserted INSERT, UPDATE New values

deleted DELETE, UPDATE Old values

Let me know if you'd like to write a sample trigger using magic tables or want to try a use

case like auditing salary changes 🔍💾

Queries :
Deletes entire table
Limit:

Order by:
Foreign key:
Funtions – Count()
AVG:
Group By
Wild cards:
UNION
Joins:

ON DELETE SET NULL , ON DELETE CASCADE for foreign key


Cascade : it deletes all foreign keys instead of set null
ER Diagrams : take business and make a db schema by making relationship model
Absolutely! Here’s a collection of tricky and frequently asked SQL interview questions,

designed to test both your fundamentals and real-world understanding:

🔥 TRICKY SQL INTERVIEW QUESTIONS (with explanations)


🔸 1. What is the difference between DELETE, TRUNCATE, and DROP?

Feature DELETE TRUNCATE DROP

Removes data? ✅ Yes (row by row) ✅ Yes (all rows) ❌ Removes entire table

WHERE
✅ Yes ❌ No ❌ N/A
allowed?

Rollback? ✅ Yes (with transaction) ⚠️Depends (often no) ❌ No

Resets identity? ❌ No ✅ Yes ✅ Yes

🔸 2. What happens when you insert a duplicate in a column with a UNIQUE constraint?

✅ You get an error. The UNIQUE constraint does not allow duplicate values — even if it's

not a primary key.

🔸 3. Can a table have multiple NULL values in a UNIQUE column?

✅ Yes. In SQL, NULL ≠ NULL. So multiple NULLs are allowed in a UNIQUE column (but

not in a PRIMARY KEY).

🔸 4. What’s the difference between WHERE and HAVING?

 WHERE filters rows before aggregation.

 HAVING filters after aggregation (with GROUP BY).


SELECT department, COUNT(*)

FROM employees

GROUP BY department

HAVING COUNT(*) > 5; -- ✅ correct

🔸 5. What’s the difference between INNER JOIN and LEFT JOIN?

JOIN Type Returns

INNER JOIN Only matching rows in both tables

LEFT JOIN All rows from left + matched from right (NULL if no match)

🔸 6. Can a FOREIGN KEY reference a column that is not a PRIMARY KEY?

✅ Yes, it can reference any column with a UNIQUE constraint.

🔸 7. How do you find the second highest salary from a table?

SELECT MAX(Salary)

FROM Employees

WHERE Salary < (SELECT MAX(Salary) FROM Employees);

💡 You can also use ROW_NUMBER(), RANK(), or LIMIT OFFSET.

🔸 8. Is NULL = NULL true?


❌ No! In SQL, NULL means unknown.

So:

SELECT * FROM table WHERE NULL = NULL; -- ❌ returns nothing

✅ Use:

WHERE column IS NULL

🔸 9. What’s the difference between CHAR and VARCHAR?

Type Fixed or Variable Memory usage

CHAR Fixed-length Pads with spaces

VARCHAR Variable-length Uses only what’s needed

🔸 10. What’s the default sorting order in ORDER BY?

✅ ASC (ascending) is the default.

If you write:

SELECT * FROM Employees ORDER BY Name;

It's the same as ORDER BY Name ASC.

🧠 Bonus Real-world Tricky Questions:

🔹 What happens if you use SELECT * in a large production system?

 It can fetch unnecessary columns


 Slows performance

 Breaks if table structure changes

✅ Best practice: always select only required columns.

🔹 Can we manually insert a value into an IDENTITY column?

✅ Yes, but only after running:

SET IDENTITY_INSERT TableName ON;

🔹 Can a PRIMARY KEY be NULL?

❌ No. A PRIMARY KEY must be unique and NOT NULL.

🚀 Want More?

Would you like a mock SQL interview, multiple-choice quiz, or real-world scenario

question set?

That’s a great interview question — and a common one! Here's how you can impressively

answer it by covering both query-level and database-level optimizations:

✅ How to Improve Performance of SQL Queries / Database

🧩 1. Use Proper Indexing

 Create indexes on columns used in:


o WHERE, JOIN, ORDER BY, GROUP BY

 Use composite indexes when multiple columns are queried together

 Avoid over-indexing — too many indexes = slower inserts/updates

📌 Example:

CREATE INDEX idx_emp_dept ON Employees(DepartmentID);

🧠 2. **Avoid SELECT *** (Star)

 Only fetch needed columns — reduces I/O and memory.

SELECT Name, Age FROM Employees; -- ✅

SELECT * FROM Employees; -- ❌

📊 3. Analyze and Use Execution Plan

 Use:

SET STATISTICS TIME ON;

SET STATISTICS IO ON;

 Or view Execution Plan in SSMS to find:

o Table scans vs index seeks

o Expensive joins

o Missing indexes
🛑 4. Avoid Unnecessary Cursors and Loops

 Use set-based operations instead of row-by-row processing

-- ❌ Slow

WHILE ...

UPDATE one row at a time

-- ✅ Fast

UPDATE Employees SET Salary = Salary * 1.10 WHERE Department = 'Sales';

🪜 5. Use Joins Smartly

 Prefer INNER JOIN over OUTER JOIN when possible

 Avoid JOIN on unindexed columns

 Don’t use subqueries when a JOIN would work better

🧹 6. Keep Statistics and Indexes Updated

 SQL uses statistics to choose query plans

 Run regularly:

UPDATE STATISTICS Employees;

or

EXEC sp_updatestats;
⚙️7. Use Stored Procedures

 Precompiled

 Reduces SQL parsing and recompilation

 Easier to optimize and secure

📁 8. Partition Large Tables

 Improves query performance on huge datasets

 Especially for reporting systems

📈 9. Avoid Functions in WHERE Clauses

 Functions like YEAR(DOB) = 2000 prevent index usage

 Rewrite like:

WHERE DOB BETWEEN '2000-01-01' AND '2000-12-31' -- ✅ Index friendly

🧵 10. Use Proper Data Types and Constraints

 Keep data types minimal and efficient (e.g., INT vs BIGINT)

 Use constraints to avoid bad data → faster joins and filters

💾 11. Optimize Temp Tables and CTEs


 Use them only when needed

 Consider indexed temp tables if reused often

🧠 Sample Answer in Interview:

*“To improve performance, I first analyze the execution plan and see if any table scans or

missing indexes exist. Then, I create or adjust indexes on frequently queried columns. I avoid

SELECT , use joins properly, and ensure stats and indexes are updated. For large data sets, I

consider partitioning. I also favor stored procedures to reduce recompilation and apply set-

based logic over row-by-row processing.”

Would you like a ready-to-use one-line checklist or real scenario + optimization task to

practice?

Index scan and Table and Index seek

Great question! This is an important concept in SQL query optimization. Let’s break it

down.

✅ 1. Table Scan (Full Table Scan)

 What it is:

SQL Server (or any DBMS) reads every row in the table to find matching records.

 When does it happen?

o No index exists on the column used in the query.


o The query needs to read a large portion of the table (even if an index exists,

optimizer may choose scan).

o The table is small (optimizer may prefer a scan because it's cheaper than using

an index).

📌 Example

SELECT * FROM Employees WHERE Email = 'test@example.com';

If there’s no index on Email, SQL will scan all rows one by one to find matches.

🟢 Analogy:

It’s like reading an entire book page by page to find a word.

✅ 2. Index Scan

 What it is:

SQL Server scans the entire index instead of the table.

 When does it happen?

o An index exists, but SQL still needs to read most or all of the rows (for

example, no selective filtering).

o The index is not selective enough (too many matching rows).

o The query retrieves columns not covered by the index (causing lookups).

📌 Example

SELECT Name FROM Employees WHERE Name LIKE '%a%';


Even if there is an index on Name, SQL cannot use it efficiently (because of %a%), so it

may scan the entire index.

🟢 Analogy:

You use the book’s index, but still end up scanning all index entries.

✅ 3. Index Seek (For Comparison)

 What it is:

SQL directly navigates to the matching part of the index (using the B-tree) without

scanning everything.

 When does it happen?

o Query uses a selective condition on an indexed column (e.g., = or > on a

properly indexed column).

📌 Example

SELECT * FROM Employees WHERE EmpID = 3;

With a clustered index on EmpID, SQL seeks directly to the row.

🟢 Analogy:

Looking up a word in a dictionary — you jump directly to the section.

✅ Summary:

Feature Table Scan Index Scan Index Seek

Reads Entire table Entire index Only matching rows


Feature Table Scan Index Scan Index Seek

Performance Slow (for large tables) Faster than table scan Fastest

Uses Index? ❌ No ✅ Yes ✅ Yes

💡 Next Level: I can also show you how to check (using Execution Plan) if SQL is doing a

table scan or index scan/seek — something interviewers love.

👉 Shall I explain that?

Window Functions in SQL (Analytic Functions)

Definition:

Window functions perform calculations across a set of rows (a window) that are related to

the current row, without collapsing the result into a single row (unlike GROUP BY).

They allow you to calculate things like running totals, rankings, and moving averages while

still returning all rows.

Key Characteristics

 They use the OVER() clause to define a window (partition) of rows.

 They do not group rows like GROUP BY; instead, they add calculated columns.

 Commonly used for analytics.


1. Ranking Functions

o ROW_NUMBER() → Assigns unique row numbers.

o RANK() → Assigns rank with gaps for ties.

o DENSE_RANK() → Assigns rank without gaps.

o NTILE(n) → Divides rows into n buckets.

2. Aggregate Functions as Window Functions

o SUM(), AVG(), COUNT(), MIN(), MAX() can be used with OVER() to

calculate running totals, moving averages, etc.

3. Value Functions

o LAG() → Access previous row value.

o LEAD() → Access next row value.

o FIRST_VALUE() → First value in the window.

o LAST_VALUE() → Last value in the window.

SELECT

column1,

SUM(salary) OVER (PARTITION BY department_id) AS dept_total

FROM Employees;
Why use Window Functions?

 They avoid complex self-joins and subqueries.

 Great for analytics and reporting.

 They are more efficient than alternative query structures

Rank vs denserank()

RANK() DENSE_RANK()

Ties Same rank Same rank

Gaps in rank? ✅ Yes (gaps exist) ❌ No (no gaps)

Use When you want to show actual ranking When you want continuous ranking (no

Case positions (with gaps, like sports) gaps, like category ranking)

You might also like