0% found this document useful (0 votes)
12 views28 pages

Complete Guide To C

The document provides a comprehensive guide to C#, ASP.NET, and ASP.NET Core, covering key concepts such as object-oriented programming principles, important C# features, and advanced topics like dependency injection and unit testing. It also explains LINQ for data manipulation, the ASP.NET framework's MVC architecture, and the role of Entity Framework as an ORM. Additionally, it outlines the CI/CD pipeline steps for deploying applications to Azure and discusses best practices for middleware and web API development.

Uploaded by

lr9690471
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)
12 views28 pages

Complete Guide To C

The document provides a comprehensive guide to C#, ASP.NET, and ASP.NET Core, covering key concepts such as object-oriented programming principles, important C# features, and advanced topics like dependency injection and unit testing. It also explains LINQ for data manipulation, the ASP.NET framework's MVC architecture, and the role of Entity Framework as an ORM. Additionally, it outlines the CI/CD pipeline steps for deploying applications to Azure and discusses best practices for middleware and web API development.

Uploaded by

lr9690471
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/ 28

Complete Guide to C#, ASP.NET, and ASP.

NET Core

1. C# Concepts

a. Object-Oriented Programming (OOP) Principles

 Encapsulation: Protecting data using access modifiers (private, public).

 Abstraction: Hiding implementation details using abstract classes or interfaces.

 Inheritance: Reusing code by deriving new classes from existing ones.

 Polymorphism: Overloading and overriding methods for different behaviors.

b. Important C# Features

 Value Types & Reference Types: int, struct (value) vs class, string (reference).

 Delegates & Events: Function pointers for callbacks (Action, Func, Predicate).

 Async & Await: Asynchronous programming for non-blocking operations.

 Exception Handling: try-catch-finally, throw, and custom exceptions.

 Collections: List<T>, Dictionary<TKey, TValue>, HashSet<T>, Queue<T>.

Collections in C#

✅ List<T> (Dynamic Array)

 Stores elements in order, allows duplicates.

 Example:

List<int> numbers = new List<int> { 1, 2, 3 };

numbers.Add(4); // [1, 2, 3, 4]

✅ Dictionary<TKey, TValue> (Key-Value Pair)

 Fast lookup by key, keys must be unique.

 Example:

Dictionary<int, string> users = new Dictionary<int, string> {

{1, "Alice"},

{2, "Bob"}

};

Console.WriteLine(users[1]); // "Alice"
✅ HashSet<T> (Unique Items)

 Stores unique elements, no duplicates.

 Example:

HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 2, 3 };

Console.WriteLine(uniqueNumbers.Count); // Output: 3

✅ Queue<T> (FIFO – First In, First Out)

 Useful for processing items in order.

 Example:

Queue<string> tasks = new Queue<string>();

tasks.Enqueue("Task 1");

tasks.Enqueue("Task 2");

Console.WriteLine(tasks.Dequeue()); // "Task 1"

c. Advanced C# Topics

 Memory Management:

o Garbage Collection: Automates memory management by reclaiming unused


objects.

o Stack vs Heap Memory: Stack stores value types and method calls, Heap
stores reference types and dynamic memory allocation.

 SOLID Principles:

o Single Responsibility: A class should have only one responsibility.

o Open/Closed: Classes should be open for extension but closed for


modification.

o Liskov Substitution: Derived classes should be substitutable for their base


classes.

o Interface Segregation: No client should be forced to depend on interfaces


they don’t use.

o Dependency Inversion: High-level modules should not depend on low-level


modules but on abstractions.

 Design Patterns:
o Singleton: Ensures a class has only one instance.

o Factory: Creates objects without specifying exact class type.

o Repository: Provides a data access layer abstraction.

 Threading and Parallel Programming:

o Task: Represents an asynchronous operation.

o Thread: Creates and manages separate execution paths.

o Parallel.ForEach: Executes loops in parallel.

o lock, Monitor, Mutex: Synchronization mechanisms to prevent race


conditions.

 Dependency Injection (DI):

o Constructor Injection: Injects dependencies through the constructor.

o Scoped vs Transient vs Singleton: Defines object lifetime in DI.

 Unit Testing & Mocking:

o Using Moq and xUnit: Mock dependencies for isolated testing.

2. LINQ (Language Integrated Query)

a. LINQ Query Basics

var numbers = new List<int> { 1, 2, 3, 4, 5 };

var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

b. Common LINQ Methods

 Filtering: Where(x => x > 10)

 Sorting: OrderBy(x => x.Name), OrderByDescending(x => x.Age)

 Aggregation: Sum(x => x.Price), Count(), Max(x => x.Score)

 Deferred vs Immediate Execution

 Projection (SelectMany) & Grouping (GroupBy)

3. ASP.NET Framework

a. ADO.NET Components
 SqlConnection: Establishes a connection to the database.

 SqlCommand: Executes SQL commands.

 SqlDataReader: Reads data in a forward-only manner.

 DataSet: Stores multiple tables and relations in memory.

b. MVC (Model-View-Controller) Flow

1. Model: Represents data.

2. View: Displays data to users.

3. Controller: Handles user requests and updates the model.

User sends a request → Controller processes it → Model retrieves/updates data →


View displays the output

c. Repository Pattern – create a abstraction layer b/w the controller and the model

 Separates data access logic.

 Maintains a clean architecture for applications.

4. ASP.NET Core

a. Middleware in ASP.NET Core

Middleware are components that handle requests and responses.

Creating Custom Middleware

public class CustomMiddleware

private readonly RequestDelegate _next;

public CustomMiddleware(RequestDelegate next) { _next = next; }

public async Task Invoke(HttpContext context)

await _next(context); // Call next middleware

Registering Middleware
app.UseMiddleware<CustomMiddleware>();

b. Web API and JSON

 Web API:

o Exposes data in JSON format.

o Accepts JSON input and returns JSON output.

o Allows cross-platform communication (React, Angular, etc.).

 JSON Uses:

o Lightweight data format for transmitting data.

o Used in REST APIs for serialization and deserialization.

 Swagger for API Documentation:

o Displays API details (methods, parameters, endpoints).

o Allows interactive API testing.

o Helps in debugging API calls.

c. Entity Framework (ORM)

 Maps C# models to database tables.

 Database First Approach: Generate models from an existing database.

 Code First Approach: Create models and generate database schema.

 Simplifies CRUD operations without raw SQL.

d. Git Push to Azure

 When you push code using git push, it first goes to a remote Git server (e.g., GitHub,
Azure DevOps, or Bitbucket).

 From there, a CI/CD pipeline can be triggered to deploy it to Azure.

 Until deployment happens, the code is only stored in the remote Git repository.

5. Build Pipeline Steps in CI/CD

1. Code Commit: Push changes to a Git repository.

2. Trigger Pipeline: CI/CD pipeline starts after code push.

3. Build Step:
o Restore dependencies (dotnet restore).

o Compile application (dotnet build).

o Run unit tests (dotnet test).

4. Publish Artifacts: Package application into a deployable format.

5. Deploy to Azure:

o Deploy to Azure App Service / Kubernetes / VM.

o Execute dotnet publish and deploy.

6. Monitor & Feedback: Logs and alerts notify developers of success/failure.

Flow:

 Git Push to Azure:

 When you push code using git push, it first goes to a remote Git server (e.g., GitHub,
Azure DevOps, or Bitbucket).

 From there, a pipeline (CI/CD) can be triggered to deploy it to Azure.

 Until deployment happens, the code is only stored in the remote Git repository.

 Entity Framework (EF) Overview:

 EF is an ORM (Object-Relational Mapper) that maps C# models to database tables.

 It simplifies database operations like CRUD without writing raw SQL.

 It provides both Code First (starting from models) and Database First (starting from
DB) approaches.

 Web API Purpose:

 Web API is used to expose data in JSON format.

 It allows front-end applications (React, Angular, etc.) to interact with the back-end
through HTTP requests.

 Since it deals with JSON input/output, it's widely used in web and mobile apps.

 Swagger in API Documentation:

 Swagger generates API documentation automatically.

 It provides a UI where you can test API endpoints.

 It shows method types (GET, POST, PUT, DELETE), URL paths, and parameters.
3. What is the purpose of WebApi?

Purpose of Web API in .NET Development (Simple Answer)

Web API in .NET is used to create RESTful services that allow applications to communicate
over HTTP. It is mainly used for:

 Exposing Data in JSON or XML format.

 Enabling Frontend-Backend Communication (React, Angular, mobile apps).

 Supporting Cross-Platform Access (Web, Mobile, IoT, Third-party apps).

 Handling CRUD Operations using GET, POST, PUT, and DELETE.

 Providing Security & Scalability with authentication (JWT, OAuth).

4. Difference Between GET and POST Requests in Web API ?

 GET: Used to retrieve data from the server. No data is modified.

 POST: Used to send data to the server to create a new resource.

5. Purpose of the 'using' Statement in C#

 Ensures that resources (like files, database connections) are automatically disposed
of after use.

 Used for handling unmanaged resources efficiently.

Example:

using (StreamReader sr = new StreamReader("file.txt"))

Console.WriteLine(sr.ReadToEnd());

} // StreamReader is automatically closed here.

6. Difference Between 'var' and 'dynamic' in C#

 var: Type is determined at compile-time and cannot change.

 dynamic: Type is determined at runtime, allowing flexibility but less safety.

 object: Can store any data type, but requires explicit casting to access specific
properties or methods.
Example:

csharp

CopyEdit

var x = 10; // x is int, cannot change type later

dynamic y = 10; // y can change type at runtime

y = "Hello"; // Valid for dynamic, invalid for var

7. Purpose of 'async' and 'await' in C#

 async: Marks a method as asynchronous.

 await: Pauses execution until the asynchronous operation completes.

Example:

csharp

CopyEdit

async Task<int> GetDataAsync()

await Task.Delay(1000); // Simulates a delay

return 10;

8. Purpose of Entity Framework in .NET Development

 ORM (Object-Relational Mapper) that simplifies database operations in C#.

 Eliminates the need for manual SQL queries by mapping objects to database tables.

9. Difference Between Code First and Database First in Entity Framework

 Code First: Define the model classes first, and EF creates the database automatically.

 Database First: Start with an existing database, and EF generates model classes from
it.
10. Purpose of 'this' Keyword in C#

 Refers to the current instance of the class.

 Used to differentiate instance variables from parameters when they have the same
name.

Example:

csharp

CopyEdit

class Person

private string name;

public void SetName(string name)

this.name = name; // 'this' refers to the instance variable

11. Purpose of 'debugger' Keyword in JavaScript

 Pauses JavaScript execution in debugging mode.

 Works like a breakpoint in developer tools.

Example:

javascript

CopyEdit

function test() {

let x = 10;

debugger; // Execution pauses here in the browser's debugger

console.log(x);

test();
12 Difference Between ref and out Keywords

✅ ref (Reference Parameter)

 The variable must be initialized before passing to the method.

 The method can modify the value.

✅ out (Output Parameter)

 The variable does not need to be initialized before passing.

 The method must assign a value before returning.

void ModifyRef(ref int x) { x += 10; }

void ModifyOut(out int y) { y = 20; }

int a = 5;

ModifyRef(ref a); // a becomes 15

int b;

ModifyOut(out b); // b is assigned 20

13 How Does Garbage Collection Work in C#?

✅ Garbage Collection (GC) in C# automatically frees memory occupied by unused


objects.

GC.Collect(); // Forces garbage collection

GC.WaitForPendingFinalizers(); // Ensures finalizers complete

14 Difference Between String and StringBuilder

✅ String (Immutable)

 Every modification creates a new object in memory.

✅ StringBuilder (Mutable)

 Modifies the string in place, improving performance.

string str = "Hello";


str += " World"; // Creates new object each time

StringBuilder sb = new StringBuilder("Hello");

sb.Append(" World"); // Modifies same object

15 What Are Extension Methods in C#?

✅ Extension Methods add new methods to existing types without modifying their
source code.

public static class StringExtensions {

public static int WordCount(this string str) {

return str.Split(' ').Length;

// Usage

string text = "Hello World";

Console.WriteLine(text.WordCount()); // Output: 2

16 What Is Dependency Injection (DI) in .NET?

✅ Dependency Injection (DI) is a design pattern that reduces tight coupling between
classes by injecting dependencies instead of creating them inside the class.

✅ Why Use DI?


✔ Improves testability
✔ Enhances maintainability
✔ Supports Inversion of Control (IoC)

Steps to Implement Dependency Injection (DI) in .NET Core

1️. Create an Interface – Define the contract for the dependency.

2️. Implement the Interface – Create a class that implements the interface logic.

3️.Register the Service in DI Container – Add the dependency to the Services collection
in Program.cs using AddSingleton, AddScoped, or AddTransient.
4️. Inject Dependency in Constructor – Use constructor injection to pass the
dependency into the required class (e.g., controller, service, or repository).

5️. Use the Service – Call the injected service inside the class where it is needed.

This ensures loose coupling, better testability, and easier maintenance of the
application.

17. Steps to Implement Lazy Loading in EF Core :

Lazy Loading means related data is only loaded when accessed, reducing initial query
load.

1️⃣ Install Required Package – Add Microsoft.EntityFrameworkCore.Proxies if not already


included.

2️⃣ Enable Lazy Loading – In DbContext, configure UseLazyLoadingProxies().

3️⃣ Use Virtual Navigation Properties – Mark related entities as virtual to allow lazy
loading.

4️⃣ Access Related Data – The related entity is loaded only when accessed for the first
time.

5️⃣ Be Aware of Performance Issues – Avoid N+1 query problems by using Include()
when necessary.

18. Steps to Implement Middleware in ASP.NET Core

Middleware are components that handle HTTP requests and responses in the request
pipeline

1️⃣ Create a Middleware Component – Define a custom middleware class or use inline
middleware in Program.cs.

2️⃣ Use HttpContext to Process Requests – Modify request/response or perform actions


(e.g., logging, authentication).

3️⃣ Call next() to Pass Control – Ensure the request moves to the next middleware in the
pipeline.

4️⃣ Register Middleware in Pipeline – Use app.UseMiddleware<CustomMiddleware>() or


app.Use() in Program.cs.

5️⃣ Ensure Proper Order – Place middleware components correctly (e.g., UseRouting
before UseAuthorization).
19. LINQ (Language Integrated Query) is a feature in C# used to query and manipulate
data from collections, databases, XML, and other sources using a concise and readable
syntax.

It helps perform operations like filtering, sorting, grouping, and aggregation in an easy
way.

20. Difference Between ADO.NET and LINQ

1️⃣ ADO.NET

 Uses SQL queries to interact with databases.

 Requires manual handling of connections, commands, and data readers.

 More complex and verbose code.

 Better for large-scale applications needing fine-tuned performance.

2️⃣ LINQ

 Uses C# syntax to query data (LINQ to SQL, LINQ to Entities).

 Automatically manages connections and data retrieval.

 More readable and concise.

 Better for quick and maintainable data operations

 Steps to Connect to a Database Using ADO.NET


1️.Import Required Namespace – Use System.Data.SqlClient for SQL Server.
2.Establish a Connection – Create a SqlConnection object with a connection string.
3.Open the Connection – Use conn.Open() to establish the connection.
4.Create a Command – Use SqlCommand to execute SQL queries (SELECT,
INSERT, UPDATE, DELETE).
5.Execute the Query – Use ExecuteReader() for SELECT, ExecuteNonQuery()
for INSERT/UPDATE/DELETE.
6.Process the Results – Read data using SqlDataReader or store it in a DataTable.
7.Close the Connection – Always close the connection using conn.Close() or
using statement to release resources.

How Entity Framework Eliminates Manual SQL Queries (Simple Steps)


1. Install Entity Framework

 Run:

dotnet add package Microsoft.EntityFrameworkCore

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

2️. Create a Model Class (Represents a Database Table)

csharp

CopyEdit

public class Product

public int Id { get; set; }

public string Name { get; set; }

public decimal Price { get; set; }

3️⃣ Create a Database Context Class

csharp

CopyEdit

public class AppDbContext : DbContext

public DbSet<Product> Products { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder options)

options.UseSqlServer("your_connection_string_here");

4️⃣ Create & Update Database Using Migrations

 Run:

sh
CopyEdit

dotnet ef migrations add InitialCreate

dotnet ef database update

🔹 This automatically creates tables based on model classes.

5️⃣ Perform CRUD Operations Without Writing SQL

✅ Insert Data

csharp

CopyEdit

using (var context = new AppDbContext())

var product = new Product { Name = "Laptop", Price = 1200.50M };

context.Products.Add(product);

context.SaveChanges(); // Saves to the database

(Instead of writing INSERT INTO Products VALUES (...))

✅ Retrieve Data

csharp

CopyEdit

var products = context.Products.ToList();

(Instead of writing SELECT * FROM Products)

✅ Update Data

csharp

CopyEdit

var product = context.Products.FirstOrDefault(p => p.Id == 1);

if (product != null)

product.Price = 1000;

context.SaveChanges(); // Updates in the database


}

(Instead of writing UPDATE Products SET Price = 1000 WHERE Id = 1)

✅ Delete Data

csharp

CopyEdit

var product = context.Products.FirstOrDefault(p => p.Id == 1);

if (product != null)

context.Products.Remove(product);

context.SaveChanges(); // Deletes from the database

(Instead of writing DELETE FROM Products WHERE Id = 1)

Conclusion

Entity Framework removes the need to write SQL manually by allowing developers to
work with C# objects and LINQ instead of raw queries. 🚀

Data Structures & Algorithms – Interview Answers

Basic Questions

What is a Data Structure?

A data structure is a way of organizing and storing data efficiently for easy access and
modification.
🔹 Examples: Array, Linked List, Stack, Queue, Hash Table, Tree, Graph

1️⃣ Array

A collection of elements stored in contiguous memory.

 Fixed size (cannot grow dynamically).

2️⃣ Linked List

A linear data structure where each element (node) contains:

 Data and
 A pointer to the next node.

Types:

 Singly Linked List → Each node points to the next.

 Doubly Linked List → Each node points to the next & previous.

 Circular Linked List → Last node points back to the first.

3️⃣ Stack (LIFO - Last In First Out)

A collection of elements that follows LIFO order.

 Operations:

o push() → Add element

o pop() → Remove top element

o peek() → View top element

4️⃣ Queue (FIFO - First In First Out)

A collection of elements that follows FIFO order.

 Operations:

o enqueue() → Add element at the rear

o dequeue() → Remove element from the front

Types:

 Normal Queue → First element added is removed first.

 Circular Queue → Wraps around to reuse empty space.

 Priority Queue → Elements are dequeued based on priority.

5️⃣ Hash Table

A key-value based data structure that provides fast lookups.

 Uses a hash function to store data efficiently.

 Handles collisions using separate chaining or open addressing.

6️⃣ Tree

A hierarchical data structure with nodes connected by edges.

 Root Node → The topmost node.

 Parent-Child Relationship → Each node has child nodes.


 Leaf Node → A node with no children.

Types:

 Binary Tree → Each node has ≤2 children.

 Binary Search Tree (BST) → Left < Root < Right.

 Heap, AVL Tree, B-Trees → Used for balancing & efficiency.

7️⃣ Graph

A collection of nodes (vertices) connected by edges.

 Directed Graph → Edges have direction.

 Undirected Graph → Edges have no direction.

 Weighted Graph → Edges have weights

🔹 Sorting (Definition)
Sorting is the process of arranging elements in a specific order (ascending or descending) to
improve search efficiency and readability.
📌 Example: Sorting student names in alphabetical order.

🔹 Searching (Definition)
Searching is the process of finding a specific element in a dataset. Efficient searching
techniques help locate data quickly.
📌 Example: Finding a contact in your phonebook.

🔹 Sorting Algorithms
1️⃣ Bubble Sort
A simple sorting algorithm that repeatedly swaps adjacent elements if they are in the wrong
order.
📌 Time Complexity: O(n²) (Slow for large data).
📌 Best Used For: Small datasets, Teaching sorting concepts.

2️⃣ Selection Sort


Finds the smallest element and places it in the correct position one by one.
📌 Time Complexity: O(n²)
📌 Best Used For: Small datasets, When memory writes are costly.

3️⃣ Insertion Sort


Builds the sorted list one element at a time, inserting each new element into its correct
position.
📌 Time Complexity: O(n²) (O(n) for nearly sorted data).
📌 Best Used For: Small datasets, Nearly sorted data.

4️⃣ Merge Sort


A divide-and-conquer algorithm that splits the array into halves, sorts them, and merges
back.
📌 Time Complexity: O(n log n) (Efficient for large datasets).
📌 Best Used For: Large datasets, External sorting.

5️⃣ Quick Sort


Chooses a pivot, partitions elements, and sorts recursively.
📌 Time Complexity: O(n log n) (Worst case O(n²) if bad pivot).
📌 Best Used For: Fast in-memory sorting.

🔹 Searching Algorithms
1️⃣ Linear Search
Checks each element one by one until the target is found.
📌 Time Complexity: O(n) (Slow for large data).
📌 Best Used For: Unsorted lists, Small datasets.

2️⃣ Binary Search


Works only on sorted arrays, dividing the search space in half each time.
📌 Time Complexity: O(log n) (Much faster than linear search).
📌 Best Used For: Large datasets, Searching in sorted data.
3️⃣ Hashing
Uses a hash function to store and retrieve data in constant time O(1).
📌 Time Complexity: O(1) (Best), O(n) (Worst if collisions).
📌 Best Used For: Fast lookups, Databases, Caching.

1️⃣ What are the differences between an array and a linked list?

 Array: Fixed size, stored in contiguous memory, direct access (O(1) time complexity).

 Linked List: Dynamic size, stored in non-contiguous memory, sequential access (O(n)
time complexity).

2️⃣ How does a stack work? What are its real-world applications?

 Stack follows LIFO (Last In, First Out).

 Operations: push() (insert), pop() (remove), peek() (view top element).

 Applications: Function call stack, undo/redo operations, expression evaluation (e.g.,


postfix notation).

3️⃣ What is a queue, and how does it differ from a stack?

 Queue follows FIFO (First In, First Out).

 Operations: enqueue() (insert at rear), dequeue() (remove from front).

 Difference: Stack removes the last inserted item, while Queue removes the first
inserted item.

4️⃣ Explain the differences between a singly linked list and a doubly linked list.

 Singly Linked List: Each node has a data field and a next pointer (points to the next
node).

 Doubly Linked List: Each node has data, next, and an additional prev pointer (points
to the previous node).

 Advantage of DLL: Allows traversal in both directions, better for complex operations.

5️⃣ What is a hash table, and how does it work?

 Hash Table stores key-value pairs using a hash function.

 It uses hashing to compute an index, where the value is stored.

 Collision Handling Techniques: Chaining (linked lists at each index) and Open
Addressing (probing for next available slot).
Sorting & Searching

6️⃣ Explain different sorting algorithms (Bubble Sort, QuickSort, Merge Sort).

 Bubble Sort: Repeatedly swaps adjacent elements if they are in the wrong order.
O(n²) time complexity.

 QuickSort: Picks a pivot, partitions the array, and sorts recursively. O(n log n) on
average, O(n²) in the worst case.

 Merge Sort: Divides array into halves, sorts recursively, and merges them. O(n log n)
time complexity, stable sorting.

7️⃣ What is binary search, and when should you use it?

 Binary search works on a sorted array by dividing it into halves and searching
recursively.

 Time Complexity: O(log n).

 Use case: When data is sorted, and we need efficient searching.

8️⃣ How does HashMap handle collisions?

 Two common techniques:

1. Chaining: Each index contains a linked list to store multiple values.

2. Open Addressing: Finds the next available slot in case of collision (Linear
Probing, Quadratic Probing, etc.).

9️⃣ What is the time complexity of QuickSort in the worst case?

 Worst case: O(n²) (when the pivot is always the smallest or largest element).

 Average case: O(n log n) (when pivot divides the array into balanced halves).

 Optimization: Use randomized QuickSort or median-of-three to improve


performance.

🔟 What is the difference between breadth-first search (BFS) and depth-first search
(DFS)?

 BFS (Breadth-First Search):

o Uses a queue (FIFO).

o Explores all neighbors before moving deeper.

o Used in shortest path algorithms like Dijkstra’s.


 DFS (Depth-First Search):

o Uses a stack (or recursion).

o Explores as deep as possible before backtracking.

o Used in maze solving, tree traversals (preorder, inorder, postorder).

SQL
Drop table Employees;

Insert into Employees(Name,Age)Values('Mounika',21);

Delete from Customers where customer_id = 1;

SELECT first_name, age

FROM Customers;

Create table Employees(Name Varchar(50), Age int);

Update Customers set age = 29 where customer_id = 5;

SQL Joins (Types & Examples)

Joins are used to combine rows from two or more tables based on a related column.

1️⃣ INNER JOIN (Common Data in Both Tables)

Returns only matching records from both tables.

sql

CopyEdit

SELECT Employees.EmployeeID, Employees.Name, Departments.DepartmentName

FROM Employees

INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;


✔ Returns employees only if they have a department.

2️⃣ LEFT JOIN (All from Left, Matches from Right)

Returns all records from the left table and matching records from the right table.

sql

CopyEdit

SELECT Employees.EmployeeID, Employees.Name, Departments.DepartmentName

FROM Employees

LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

✔ Returns all employees, even if they don’t have a department (NULL for missing data).

3️⃣ RIGHT JOIN (All from Right, Matches from Left)

Returns all records from the right table and matching records from the left table.

sql

CopyEdit

SELECT Employees.EmployeeID, Employees.Name, Departments.DepartmentName

FROM Employees

RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

✔ Returns all departments, even if no employees belong to them (NULL for missing data).

4️⃣ FULL OUTER JOIN (All Data from Both Tables)

Returns all records from both tables, filling missing matches with NULLs.

sql

CopyEdit

SELECT Employees.EmployeeID, Employees.Name, Departments.DepartmentName

FROM Employees

FULL OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

✔ Returns all employees & departments, even if no match is found.


5️⃣ CROSS JOIN (Cartesian Product)

Returns every combination of rows from both tables.

sql

CopyEdit

SELECT Employees.Name, Departments.DepartmentName

FROM Employees

CROSS JOIN Departments;

✔ If Employees has 5 rows & Departments has 3 rows → Output = 5 × 3 = 15 rows.

6️⃣ SELF JOIN (Join Table with Itself)

Used when comparing records within the same table.

SELECT A.EmployeeID, A.Name, B.ManagerID

FROM Employees A

JOIN Employees B ON A.EmployeeID = B.ManagerID;

✔ Finds employees who report to the same manager.

SQL Aggregate Functions

Aggregate functions perform calculations on multiple rows and return a single result. They
are often used with GROUP BY.

1️⃣ COUNT() – Count Rows

Returns the number of rows in a column.

sql

CopyEdit

SELECT COUNT(*) FROM Employees; -- Counts total employees

SELECT COUNT(DepartmentID) FROM Employees WHERE Age > 30; -- Counts employees
above 30

2️⃣ SUM() – Total Sum


Returns the sum of values in a column.

sql

CopyEdit

SELECT SUM(Salary) FROM Employees; -- Total salary of all employees

SELECT SUM(Salary) FROM Employees WHERE DepartmentID = 2; -- Total salary in Dept 2

3️⃣ AVG() – Average Value

Returns the average value of a column.

sql

CopyEdit

SELECT AVG(Salary) FROM Employees; -- Average salary of all employees

SELECT AVG(Age) FROM Employees WHERE DepartmentID = 3; -- Average age in Dept 3

4️⃣ MAX() – Maximum Value

Returns the highest value in a column.

sql

CopyEdit

SELECT MAX(Salary) FROM Employees; -- Highest salary

SELECT MAX(Age) FROM Employees WHERE DepartmentID = 1; -- Oldest employee in Dept


1

5️⃣ MIN() – Minimum Value

Returns the lowest value in a column.

sql

CopyEdit

SELECT MIN(Salary) FROM Employees; -- Lowest salary

SELECT MIN(Age) FROM Employees WHERE DepartmentID = 4; -- Youngest employee in


Dept 4
6️⃣ Using Aggregate Functions with GROUP BY

sql

CopyEdit

SELECT DepartmentID, COUNT(*) AS EmployeeCount, AVG(Salary) AS AvgSalary

FROM Employees

GROUP BY DepartmentID;

✔ Groups employees by DepartmentID, counting employees and calculating average salary.

SQL Commands Explained with Examples

1️⃣ ORDER BY (Sorting Data)

Used to sort results in ascending (ASC) or descending (DESC) order.

sql

CopyEdit

SELECT * FROM Employees ORDER BY Age ASC; -- Sorts employees by age (smallest to
largest)

SELECT * FROM Employees ORDER BY Salary DESC; -- Sorts by Salary (highest to lowest)

2️⃣ GROUP BY (Grouping Data)

Used to group rows based on a column, often used with aggregate functions (COUNT, SUM,
AVG, MAX, MIN).

sql

CopyEdit

SELECT DepartmentID, COUNT(*) AS EmployeeCount

FROM Employees

GROUP BY DepartmentID;

✔ Groups employees by DepartmentID and counts how many are in each department.

3️⃣ HAVING (Filter Groups)

Used with GROUP BY to filter results after aggregation.


sql

CopyEdit

SELECT DepartmentID, COUNT(*) AS EmployeeCount

FROM Employees

GROUP BY DepartmentID

HAVING COUNT(*) > 5;

✔ Displays departments where more than 5 employees exist.

4️⃣ LIKE (Pattern Matching)

Used to search for specific patterns in a column.

sql

CopyEdit

SELECT * FROM Employees WHERE Name LIKE 'J%'; -- Names starting with 'J'

SELECT * FROM Employees WHERE Name LIKE '%son'; -- Names ending with 'son'

SELECT * FROM Employees WHERE Name LIKE '%an%'; -- Names containing 'an'

✔ % matches any number of characters, _ matches a single character.

5️⃣ IN (Multiple Values in a Condition)

Used to filter results by matching multiple values.

sql

CopyEdit

SELECT * FROM Employees WHERE DepartmentID IN (1, 3, 5);

✔ Retrieves employees from departments 1, 3, or 5.

6️⃣ BETWEEN (Range Condition)

Used to select values within a range (inclusive of both values).

sql

CopyEdit
SELECT * FROM Employees WHERE Age BETWEEN 25 AND 40;

SELECT * FROM Employees WHERE Salary BETWEEN 50000 AND 100000;

✔ Finds employees between ages 25-40 or salaries between 50,000-100,000.

7️⃣ DISTINCT (Unique Values)

Removes duplicate values from a column.

sql

CopyEdit

SELECT DISTINCT DepartmentID FROM Employees;

✔ Returns unique department IDs (no duplicates).

8️⃣ LIMIT (Fetch Specific Number of Rows)

Used to restrict the number of results returned.

sql

CopyEdit

SELECT * FROM Employees LIMIT 5; -- Fetches only the first 5 rows

SELECT * FROM Employees ORDER BY Salary DESC LIMIT 3; -- Gets top 3 highest salaries

You might also like