0% found this document useful (0 votes)
9 views22 pages

SQL

The document provides an overview of SQL concepts including different types of keys (Primary, Foreign, Candidate, Composite, Alternate, Unique), SQL commands (DDL, DML, DQL, DCL, TCL), types of joins, views, normalization, triggers, ACID properties, indexing, GROUP BY and HAVING clauses, stored procedures, and aggregate functions. It explains the purpose and usage of each concept with examples and key points for better understanding. The document serves as a comprehensive guide for SQL database management and operations.

Uploaded by

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

SQL

The document provides an overview of SQL concepts including different types of keys (Primary, Foreign, Candidate, Composite, Alternate, Unique), SQL commands (DDL, DML, DQL, DCL, TCL), types of joins, views, normalization, triggers, ACID properties, indexing, GROUP BY and HAVING clauses, stored procedures, and aggregate functions. It explains the purpose and usage of each concept with examples and key points for better understanding. The document serves as a comprehensive guide for SQL database management and operations.

Uploaded by

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

1.

Different keys in sql:

1. Primary Key:
- Uniquely identifies each record in a table.
- Cannot be NULL and must be unique.
- Only one primary key per table.

2. Foreign Key:
- A field in one table that refers to the primary key in another table.
- Used to maintain referential integrity.

3. Candidate Key:
- A set of fields that can uniquely identify a record.
- One of them is chosen as the primary key.

4. Composite Key:
- A primary key made up of two or more columns.
- Used when a single column cannot uniquely identify rows.

5. Alternate Key:
- Candidate keys that are not selected as the primary key.

6. Unique Key:
- Ensures all values in a column are different.
- Can have one NULL value.

🎓 Table: Students
| StudentID (PK) | Name | Email (Unique) |
|----------------|--------|--------------------|
| 101 | Alice | alice@gmail.com |
| 102 | Bob | bob@gmail.com |

- Primary Key: StudentID (uniquely identifies each student)


- Unique Key: Email (no two students can have the same email)

📚 Table: Courses
| CourseID (PK) | CourseName |
|---------------|-------------|
| C1 | SQL Basics |
| C2 | Java |

📝 Table: Enrollments
| StudentID (FK) | CourseID (FK) | EnrollmentDate |
|----------------|---------------|----------------|
| 101 | C1 | 2024-01-01 |
| 102 | C2 | 2024-01-02 |

- Foreign Key: StudentID and CourseID in Enrollments table reference Students and
Courses respectively.
- Composite Key: (StudentID, CourseID) together form the Primary Key of Enrollments
— because a student can enroll in multiple courses, and a course can have multiple
students, but each student-course pair must be unique.

2. DDL, DML, DCL, DQL, TCL:

1. DDL (Data Definition Language)


Used to define or modify database structures.
Commands:
- CREATE – create tables or databases
- ALTER – modify existing structures
- DROP – delete tables/databases
- TRUNCATE – remove all records (faster than DELETE, no rollback)

2. DML (Data Manipulation Language)


Used to manipulate data in tables.
Commands:
- INSERT – add new records
- UPDATE – modify existing records
- DELETE – remove records

3. DQL (Data Query Language)


Used to retrieve data.
Command:
- SELECT – fetch data from one or more tables

4. DCL (Data Control Language)


Used to control access and permissions.
Commands:
- GRANT – give user access
- REVOKE – remove access

5. TCL (Transaction Control Language)


Used to manage transactions in SQL.
Commands:
- COMMIT – save changes
- ROLLBACK – undo changes
- SAVEPOINT – set a point for partial rollback

Example:

🧱 DDL (Data Definition Language)


Creating a table for customers:
sql
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(50),
Balance DECIMAL
);
✏ DML (Data Manipulation Language)
Adding a new customer:
sql
INSERT INTO Customers VALUES (101, 'Alice', 5000);

Updating a balance:
sql
UPDATE Customers SET Balance = Balance + 1000 WHERE CustomerID = 101;

Deleting a customer:
sql
DELETE FROM Customers WHERE CustomerID = 101;

🔍 DQL (Data Query Language)


Fetching customer details:
sql
SELECT FROM Customers WHERE Balance > 1000;

🔐 DCL (Data Control Language)


Giving access to another user:
sql
GRANT SELECT, INSERT ON Customers TO user123;

Revoking access:
sql
REVOKE INSERT ON Customers FROM user123;

🔁 TCL (Transaction Control Language)


Making a transaction safe:
sql
BEGIN;

UPDATE Customers SET Balance = Balance - 1000 WHERE CustomerID = 101;


UPDATE Customers SET Balance = Balance + 1000 WHERE CustomerID = 102;

COMMIT;

If something goes wrong:


sql
ROLLBACK;

3. Types of Joins:
🔗 1. INNER JOIN
- Returns only matching rows from both tables.
- Ignores unmatched rows.

Example:
Get customers who have placed orders.

sql
SELECT Customers.Name, Orders.OrderID
FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result: Only customers who have orders.

Diagram:

Customers ∩ Orders (common part only)

🟢 2. LEFT JOIN (LEFT OUTER JOIN)


- Returns all rows from the left table + matched rows from the right table.
- If no match, shows NULL for right table columns.

Example:
List all customers, even if they haven’t placed any order.

sql
SELECT Customers.Name, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result: All customers + their orders if any.

Diagram:

Customers ⟶ [All Left + Matching Right]

🔴 3. RIGHT JOIN (RIGHT OUTER JOIN)


- Returns all rows from the right table + matched rows from the left table.
- If no match, shows NULL for left table columns.

Example:
List all orders, even if the customer info is missing.

sql
SELECT Customers.Name, Orders.OrderID
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result: All orders + customer details if available.

Diagram:

Orders ⟵ [All Right + Matching Left]

🟡 4. FULL JOIN (FULL OUTER JOIN)


- Returns all rows from both tables.
- If no match, shows NULL on the side with no match.

Example:
List all customers and all orders, even if they don’t match.

sql
SELECT Customers.Name, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Result: All customers + all orders.

Diagram:

Customers ∪ Orders (All + Matches + Unmatched)

🔄 5. CROSS JOIN
- Returns cartesian product: every row of the first table combined with every row
of the second table.

Example:
Match every customer with every product.

sql
SELECT Customers.Name, Products.ProductName
FROM Customers
CROSS JOIN Products;

Result: All combinations.

Diagram:

m rows × n rows = mn results


❓ 6. SELF JOIN
- A table joined with itself.

Example:
Find employees and their managers (both in the same table).

sql
SELECT A.Name AS Employee, B.Name AS Manager
FROM Employees A
JOIN Employees B ON A.ManagerID = B.EmployeeID;

4. Views:

✅ What is a View?
A View is a virtual table based on the result of an SQL query.
It does not store data, only the query logic.

🧠 Why Use Views?


- Simplifies complex queries
- Provides security by showing only selected columns
- Allows readability and reusability

🛠 Creating a View
sql
CREATE VIEW view_customer_orders AS
SELECT Customers.Name, Orders.OrderID
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

👀 Using the View


sql
SELECT FROM view_customer_orders;

🧹 Dropping a View
sql
DROP VIEW view_customer_orders;

⚠ Key Points:
- Views can be updated if based on a single table without group functions.
- Acts like a table, but data is fetched live when queried.

5. Normalization:
✅ What is Normalization?

Normalization is the process of organizing data in a database to:

Remove redundancy (duplicate data)


Ensure data integrity
Improve efficiency

🧱 Goals of Normalization:

Eliminate data redundancy


Avoid update, insert, and delete anomalies
Make the database more consistent and maintainable

✅ 1NF – First Normal Form


Rule:
- Each column should have atomic (indivisible) values
- No repeating groups or arrays

Example Violation:
| StudentID | Name | Subjects |
|-----------|--------|------------------|
| 1 | Alice | Math, Science |

✅ 1NF Fix:
| StudentID | Name | Subject |
|-----------|--------|-----------|
| 1 | Alice | Math |
| 1 | Alice | Science |

✅ 2NF – Second Normal Form


Rule:
- Must be in 1NF
- No partial dependency (non-prime attribute depends on full primary key)

Violation Example (Composite key):


| StudentID | CourseID | StudentName |
|-----------|-----------|-------------|
| 1 | 101 | Alice |

StudentName depends only on StudentID, not the full key (StudentID, CourseID)

✅ 2NF Fix:
- Student: StudentID, StudentName
- Enrollment: StudentID, CourseID

✅ 3NF – Third Normal Form


Rule:
- Must be in 2NF
- No transitive dependency (non-key column depending on another non-key column)

Violation Example:
| StudentID | Dept | HOD |
|-----------|---------|-----------|
| 1 | Science | Dr. Smith |

HOD depends on Dept, not directly on StudentID

✅ 3NF Fix:
- Students: StudentID, Dept
- Department: Dept, HOD

✅ BCNF – Boyce-Codd Normal Form


Rule:
- Must be in 3NF
- Every determinant must be a candidate key

Example Violation:
| Course | Instructor | Room |
|---------|------------|-------|
| DBMS | John | 101 |
| DBMS | Alice | 102 |

Assume:
- Course → Room
- Instructor → Room
But neither Course nor Instructor alone is a candidate key.

✅ BCNF Fix:
Break into two tables:
- Course → Room
- Instructor → Room

✅ 4NF – Fourth Normal Form


Rule:
- Must be in BCNF
- No multi-valued dependency

Violation Example:
| Student | Hobby | Language |
|---------|---------|----------|
| Alice | Music | English |
| Alice | Music | French |
| Alice | Dance | English |
| Alice | Dance | French |
Here, Hobby and Language are independent multi-valued facts about Student.

✅ 4NF Fix:
Split into:
- Student-Hobby: Student, Hobby
- Student-Language: Student, Language

✅ 5NF – Fifth Normal Form (PJNF: Project-Join Normal Form)


Rule:
- Must be in 4NF
- No join dependency — data should not be reconstructable only by joining multiple
tables

Use Case:
Complex business scenarios with multiple independent many-to-many relationships

Example (rare):
A student can learn multiple subjects from multiple teachers — breaking and joining
info could give incorrect combinations.

✅ 5NF Fix:
Split into minimal tables that represent each independent relationship.

🔁 Quick Summary Table:

| Normal Form | Eliminates | Rule Summary


|
|-------------|-----------------------------------|--------------------------------
----------------|
| 1NF | Repeating groups | Atomic values only
|
| 2NF | Partial dependencies | Full dependency on the primary key
|
| 3NF | Transitive dependencies | Non-key fields depend only on the
key |
| BCNF | All anomalies from determinants | Every determinant is a candidate
key |
| 4NF | Multi-valued dependencies | No independent multi-valued facts
|
| 5NF | Join dependencies | Shouldn't need joining to
reconstruct meaning |

6. Triggers:

✅ What is a Trigger?
A Trigger is a stored procedure that automatically runs when a specific event
occurs in a table.
🔥 When Triggers are Used
- Before or after: INSERT, UPDATE, or DELETE
- For data validation, auditing, auto-logging, etc.

🧠 Types of Triggers

| Type | Description |
|--------------------|----------------------------------------------|
| BEFORE INSERT | Fires before inserting a row |
| AFTER INSERT | Fires after inserting a row |
| BEFORE UPDATE | Fires before updating a row |
| AFTER UPDATE | Fires after updating a row |
| BEFORE DELETE | Fires before deleting a row |
| AFTER DELETE | Fires after deleting a row |

🛠 Example: Logging Insertions

sql
CREATE TRIGGER log_customer_insert
AFTER INSERT ON Customers
FOR EACH ROW
BEGIN
INSERT INTO LogTable (Action, CustomerID, Timestamp)
VALUES ('Inserted', NEW.CustomerID, NOW());
END;

📌 Key Points for Interviews


- Triggers are automatic — no need to call them manually
- Can access NEW and OLD values in row-level triggers
- Useful for enforcing business rules

7. ACID properties:

ACID ensures reliable, consistent, and safe transactions in a database.

🧱 1. Atomicity
- All parts of a transaction must complete fully or not at all
- No partial transactions allowed

✅ Example: Money transfer — if debit succeeds but credit fails, rollback both.

🧱 2. Consistency
- A transaction must take the database from one valid state to another
- Maintains all rules and constraints

✅ Example: Balance can’t go negative if a constraint prohibits it.

🧱 3. Isolation
- Transactions should not interfere with each other
- Intermediate data of one transaction must be invisible to others

✅ Example: Two users booking the same seat won’t clash.

🧱 4. Durability
- Once a transaction is committed, it stays saved — even after power failure

✅ Example: Order placed stays recorded even after a crash.

🎯 Quick Summary Table:

| Property | Ensures that... |


|--------------|---------------------------------------------|
| Atomicity | All or nothing |
| Consistency | Rules are always followed |
| Isolation | Transactions don’t affect each other |
| Durability | Data stays safe even after system failure |

8. Indexing:

✅ What is an Index in SQL?


An index is a data structure used to speed up retrieval of rows from a table.

It works like a book’s index — helps find data faster without scanning the whole
table.

🔍 Why use Indexes?


- Speeds up SELECT queries
- Reduces search time (especially on large tables)

📌 Types of Indexes

| Type | Description |
|----------------|---------------------------------------------|
| Single-column Index | Index on one column |
| Composite Index | Index on multiple columns |
| Unique Index | Ensures all values in column are unique |
| Full-text Index | Used for searching large text data |
| Clustered Index | Alters the way records are stored (only one per table) |
| Non-clustered Index | Separate structure from the actual table data |

🛠 Creating an Index

sql
CREATE INDEX idx_customer_name
ON Customers (Name);

⚠ Important Notes
- Indexes speed up read operations, but slow down insert/update/delete
- Use indexes wisely (only on frequently searched columns)

9. Group BY and Having:

✅ GROUP BY Clause

- GROUP BY is used to group rows that have the same values in specified columns.
- Often used with aggregate functions like SUM(), COUNT(), AVG(), etc.

---

🧠 Example:
sql
SELECT Department, COUNT() AS EmployeeCount
FROM Employees
GROUP BY Department;

🔹 This query counts how many employees are in each department.

✅ HAVING Clause

- HAVING is used to filter groups created by GROUP BY


- Similar to WHERE, but HAVING works after grouping

🧠 Example with HAVING:


sql
SELECT Department, COUNT() AS EmployeeCount
FROM Employees
GROUP BY Department
HAVING COUNT() > 5;

🔹 This shows only departments with more than 5 employees.

🆚 WHERE vs HAVING

| Clause | Works On | When It Filters |


|---------|------------------|---------------------|
| WHERE | Rows | Before grouping |
| HAVING| Groups | After grouping |

📌 Key Points to Remember


- Use GROUP BY to group similar data
- Use HAVING to filter groups
- Cannot use aggregate functions in WHERE — use them in HAVING

10. Stored Procedures:


✅ What is a Stored Procedure?
A Stored Procedure is a precompiled set of SQL statements stored in the database
that can be executed as a single unit.

🧠 Why Use It?


- Code reusability
- Improves performance
- Security (hide logic)
- Easier to maintain

🛠 Basic Syntax:
sql
CREATE PROCEDURE GetEmployeeByDept(IN dept_name VARCHAR(50))
BEGIN
SELECT FROM Employees WHERE Department = dept_name;
END;

🔹 Call it using:
sql
CALL GetEmployeeByDept('HR');

📌 Key Features
- Can take input, output, or both types of parameters
- Supports control flow (IF, LOOP, etc.)
- Reduces code duplication

✅ Benefits in One Line:


Stored procedures encapsulate business logic, making queries faster, safer, and
reusable.

11. Aggregate Functions:

✅ What are Aggregate Functions?


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

Used with GROUP BY to summarize data.

📊 Common Aggregate Functions

| Function | Description |
|---------------|----------------------------------------|
| COUNT() | Counts number of rows |
| SUM() | Adds up numeric values |
| AVG() | Returns average of numeric values |
| MIN() | Returns the smallest value |
| MAX() | Returns the largest value |

🧠 Example:
sql
SELECT Department, COUNT() AS TotalEmployees, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department;

🔹 Shows total employees and average salary per department.

📌 Key Notes
- Can be used with or without GROUP BY
- Often used with HAVING to filter grouped results

12. use of database in real time scenario:

Databases are used in real-time systems like banking for transactions, e-commerce
for managing products and orders, hospitals for patient records, and airlines for
booking systems — ensuring fast, consistent, and secure data access.

13. Case in SQL :

✅ What is CASE in SQL?

The CASE statement is SQL’s version of if-else logic. It lets you perform
conditional logic inside a query, especially useful in SELECT, WHERE, ORDER BY,
etc.

🧠 Syntax:

sql
SELECT
Name,
Salary,
CASE
WHEN Salary > 50000 THEN 'High'
WHEN Salary BETWEEN 30000 AND 50000 THEN 'Medium'
ELSE 'Low'
END AS SalaryLevel
FROM Employees;

🔹 This classifies salaries into "High", "Medium", or "Low".

📌 Where You Can Use CASE:

| Clause | Use Case Example |


|------------|----------------------------------------------------|
| SELECT | Create derived columns based on conditions |
| WHERE | Filter rows based on complex conditions |
| ORDER BY | Change sorting order dynamically |

🚀 Simple Example (Short version):

sql
SELECT Name,
CASE Gender
WHEN 'M' THEN 'Male'
WHEN 'F' THEN 'Female'
ELSE 'Other'
END AS GenderFull
FROM Students;

14. SQL Constraints:

✅ What are SQL Constraints?

SQL constraints are rules applied to table columns to ensure the validity,
integrity, and accuracy of data in a database.

🔒 Types of Constraints:

| Constraint | Description |
|----------------|-------------------------------------------------------|
| NOT NULL | Ensures column cannot have NULL values |
| UNIQUE | Ensures all values in a column are different |
| PRIMARY KEY | Combines NOT NULL + UNIQUE, uniquely identifies rows |
| FOREIGN KEY | Ensures referential integrity between two tables |
| CHECK | Ensures values meet a specific condition |
| DEFAULT | Sets a default value if none is provided |

🧠 Example:

sql
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT CHECK (Age >= 18),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(ID)
);

15. String Functions:

✅ What are String Functions?


String functions are used to manipulate and handle text data (like names, emails,
etc.) in SQL.

🔧 Common String Functions:

| Function | Description | Example


|
|------------------|---------------------------------------------|-----------------
---------------------|
| UPPER() | Converts text to uppercase | UPPER('dhanish')
→ 'DHANISH' |
| LOWER() | Converts text to lowercase | LOWER('SQL') →
'sql' |
| LENGTH() / LEN() | Returns length of string | LENGTH('hello') → 5
|
| SUBSTRING() | Extracts part of a string |
SUBSTRING('hello', 2, 3) → 'ell' |
| CONCAT() | Combines two or more strings | CONCAT('Hello', '
', 'World') |
| TRIM() | Removes spaces from both ends | TRIM(' hello ')
→ 'hello' |
| REPLACE() | Replaces part of a string | REPLACE('cat',
'c', 'b') → 'bat' |

🧠 Example Use Case:


sql
SELECT UPPER(Name), LENGTH(Name)
FROM Students;

🔹 This returns student names in uppercase along with their length.

16. Limits and Offsets;

- LIMIT is used to restrict the number of rows returned by a query.

sql
SELECT FROM Employees
LIMIT 5;

🔹 Returns first 5 rows only.

- OFFSET skips a specified number of rows before starting to return the result.

sql
SELECT FROM Employees
LIMIT 5 OFFSET 10;

🔹 Skips the first 10 rows, then shows next 5 rows.


🧠 Use Case:
Used in pagination (e.g., showing 10 results per page in web apps).

🔁 Alternate Syntax (MySQL, PostgreSQL):


sql
SELECT FROM Employees
LIMIT 10 OFFSET 20;
-- or
SELECT FROM Employees
LIMIT 20, 10; -- LIMIT offset, count

17. Unions:

🔀 UNION

- Combines results of two SELECT queries


- Removes duplicates (use UNION ALL to include duplicates)
- Rows are added vertically
- Columns in both queries must match in number and data type

🧠 Example:
sql
SELECT Name FROM Students
UNION
SELECT Name FROM Teachers;

18. SubQuery:

✅ What is a Subquery?

A subquery is a query inside another query.


It returns data that the main (outer) query uses.

🧠 Types of Subqueries:

1. Single-row Subquery → Returns one value


2. Multi-row Subquery → Returns multiple values
3. Correlated Subquery → Refers to outer query row-by-row
4. Nested Subquery → Subquery inside another subquery

🔍 Example:
sql
SELECT Name FROM Students
WHERE Marks > (SELECT AVG(Marks) FROM Students);

🔹 Returns students who scored above average.


📌 Used in:
- SELECT, WHERE, FROM, HAVING clauses

19.second highest salary:

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

or

SELECT DISTINCT Salary


FROM Employees
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;

20.SQL queries for Add, Delete, and Modify

✅ 1. Add Data (INSERT)

sql
INSERT INTO Employees (ID, Name, Salary)
VALUES (101, 'John', 50000);

🗑 2. Delete Data (DELETE)

sql
DELETE FROM Employees
WHERE ID = 101;

✏ 3. Modify Data (UPDATE)

sql
UPDATE Employees
SET Salary = 55000
WHERE ID = 101;

21. Replace:

✅ Purpose of REPLACE()
Used to replace a part of a string with another string.
🧠 Example Query:
sql
SELECT REPLACE('SQL is cool', 'cool', 'awesome') AS Result;

🔹 Output: SQL is awesome

📌 Use Case in Table:


sql
SELECT Name, REPLACE(Name, 'Mr.', '') AS CleanName
FROM Employees;

🔹 Removes 'Mr.' from employee names.

22. Upper to Lower Case:

🔽 Using LOWER() Function:

sql
SELECT LOWER('DHANISH') AS LowerName;

🔹 Output: dhanish

🧠 From a Table Column:

sql
SELECT Name, LOWER(Name) AS LowerCaseName
FROM Employees;

23. Create normal and temporary table:

✅ 1. Normal Table
Stored permanently in the database.

sql
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Salary DECIMAL(10, 2)
);

🧪 2. Temporary Table
Exists only during the session. Automatically deleted after.

sql
CREATE TEMPORARY TABLE TempEmployees (
ID INT,
Name VARCHAR(50)
);

24. Merge Statement:

The MERGE statement is used to combine INSERT, UPDATE, and DELETE in a single query
based on a condition.

📌 It's also called "Upsert" — insert if not exists, update if exists.

🧠 Basic Syntax:
sql
MERGE INTO TargetTable AS T
USING SourceTable AS S
ON T.ID = S.ID
WHEN MATCHED THEN
UPDATE SET T.Name = S.Name
WHEN NOT MATCHED THEN
INSERT (ID, Name) VALUES (S.ID, S.Name);

🔍 Use Cases:
- Syncing data between two tables
- Implementing UPSERT (update if exists, insert if not)
- Data warehousing and ETL processes

25. Join EmployeeT and Dept.T :

✅ Query using INNER JOIN:


sql
SELECT
E.ID,
E.Name,
E.Salary,
D.DeptName
FROM
Employee E
INNER JOIN
Department D ON E.DeptID = D.ID;

🧠 Explanation:
- E.DeptID is the foreign key in the Employee table.
- D.ID is the primary key in the Department table.
- INNER JOIN returns only employees who are assigned to a department.

26.**SQL Injection** :
### ✅ **What is SQL Injection?**

**SQL Injection** is a **security vulnerability** that allows an attacker to


**interfere with the queries** an application makes to its database. It happens
when **user input is directly included in SQL statements** without proper
validation or escaping.

### 🔍 **Example:**
```sql
SELECT * FROM users WHERE username = 'admin' AND password = '123';
```

If the attacker enters:


```sql
username: ' OR '1'='1
password: anything
```

The query becomes:


```sql
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = 'anything';
```

➡ This always returns true, allowing **unauthorized access**.

### 🚫 **Why is it dangerous?**


- Attackers can **bypass login**, **delete data**, or **extract sensitive info**.
- It can lead to **data breaches** and **loss of control** over the database.

### 🛡 **How to prevent it?**


- **Use Prepared Statements / Parameterized Queries**
- **Validate and sanitize user input**
- **Use ORM frameworks** (like Hibernate)
- **Limit database permissions**

27.**Clustered** and **Non-Clustered Index** in SQL

### 📌 **Clustered Index:**


- **Sorts and stores** the data rows in the table based on the index key.
- There can be **only one** clustered index per table.
- It **rearranges the actual data** in the table.

🟢 **Example:**
If a table has a clustered index on `ID`, the rows are physically stored in order
of `ID`.

### 📌 **Non-Clustered Index:**


- Stores the **index separately** from the actual data.
- Contains a **pointer** to the data row in the clustered index or table.
- You can create **multiple non-clustered indexes** on a table.

🟢 **Example:**
Searching by `Email` can use a non-clustered index while the data remains sorted by
`ID`.

28.Can static methods be overridden? Why or why not?

**No**, **static methods cannot be overridden** in Java.

### ⚙ **Why?**
- **Static methods belong to the class**, not to instances (objects).
- Overriding in Java is based on **runtime polymorphism**, which works with
objects.
- Static methods are **resolved at compile-time**, not runtime.

### 🔍 Example:

```java
class Parent {
static void show() {
System.out.println("Parent");
}
}

class Child extends Parent {


static void show() {
System.out.println("Child");
}
}

public class Test {


public static void main(String[] args) {
Parent obj = new Child();
obj.show(); // Output: Parent
}
}
```

👉 Even though `obj` is a `Child` object, it calls `Parent`’s static method


because static methods are **not polymorphic**.

### ✅ This is called **method hiding**, not overriding.

29.

You might also like