Mastering SQL: The Ultimate Guide to Querying and Managing Relational Databases

0 0 0 0 0

📘 Chapter 5: Advanced SQL Features

🧠 Introduction

After mastering the basics of querying, manipulating, and joining data in SQL, developers and data analysts can benefit from learning advanced SQL features. These features include:

  • Views
  • Indexes
  • Stored Procedures and Functions
  • Triggers
  • Window Functions
  • Common Table Expressions (CTEs)
  • Transactions and Locks
  • Temporary Tables and Variables

These tools allow for more efficient, reusable, and scalable data operations in real-world applications.


👁️ 1. SQL Views

🔹 What is a View?

A View is a virtual table based on a SELECT query. It simplifies complex queries and enhances security.

Creating a View

sql

 

CREATE VIEW ActiveCustomers AS

SELECT CustomerID, Name, Country

FROM Customers

WHERE Status = 'Active';

Querying the View

sql

 

SELECT * FROM ActiveCustomers;

📋 View Advantages

Benefit

Description

Reusability

Encapsulates complex queries

Security

Restrict access to specific columns

Simplification

Cleaner code


2. Indexes

🔹 What is an Index?

An index improves query performance by allowing faster data lookup, similar to a book index.

Creating an Index

sql

 

CREATE INDEX idx_name ON Customers(Name);

📋 Types of Indexes

Type

Use Case

Single Column

Fast search on one column

Composite

Search/filter on multiple columns

Unique Index

Enforce uniqueness

Full-Text

For text search (MySQL, SQL Server)

️ Indexes speed up reads but can slow down writes (INSERT, UPDATE, DELETE).


🛠️ 3. Stored Procedures

🔹 What is a Stored Procedure?

A Stored Procedure is a precompiled SQL block stored in the database, reusable for multiple calls.

Syntax Example

sql

 

CREATE PROCEDURE GetCustomersByCountry(IN countryName VARCHAR(50))

BEGIN

    SELECT * FROM Customers WHERE Country = countryName;

END;

Calling the Procedure

sql

 

CALL GetCustomersByCountry('India');

📋 Benefits

Feature

Advantage

Encapsulation

Logic reused across apps

Performance

Executes faster after first compile

Maintainability

Centralized logic changes


🧮 4. SQL Functions

🔹 What is a User-Defined Function (UDF)?

Like procedures, functions return values and can be used in expressions.

Example: Scalar Function

sql

 

CREATE FUNCTION GetDiscount(price DECIMAL(10,2))

RETURNS DECIMAL(10,2)

BEGIN

    RETURN price * 0.90;

END;

sql

 

SELECT Name, GetDiscount(Price) AS DiscountedPrice FROM Products;


🔁 5. Triggers

🔹 What is a Trigger?

A trigger is a special procedure that executes automatically in response to INSERT, UPDATE, or DELETE.

Example: Track Changes

sql

 

CREATE TRIGGER after_update_order

AFTER UPDATE ON Orders

FOR EACH ROW

INSERT INTO AuditLog(OrderID, ChangedOn) VALUES (OLD.OrderID, CURRENT_TIMESTAMP);


📋 When to Use Triggers

Use Case

Example

Audit Trail

Log updates or deletes

Enforce Business Rules

Prevent invalid changes

Automatic Updates

Modify related tables on changes


📊 6. Window Functions

🔹 What Are Window Functions?

Window functions perform calculations across a set of rows related to the current row.

Example: Running Total

sql

 

SELECT CustomerID, OrderID, Amount,

       SUM(Amount) OVER (PARTITION BY CustomerID ORDER BY OrderID) AS RunningTotal

FROM Orders;


📋 Common Window Functions

Function

Description

ROW_NUMBER()

Unique row number within group

RANK()

Rank with gaps

DENSE_RANK()

Rank without gaps

LEAD()/LAG()

Look ahead or behind in rows

SUM()/AVG()

Aggregate over partition


🔁 7. Common Table Expressions (CTEs)

🔹 What is a CTE?

A CTE is a temporary named result set you can reference in a query.

Example:

sql

 

WITH HighValueOrders AS (

    SELECT * FROM Orders WHERE Amount > 500

)

SELECT * FROM HighValueOrders WHERE CustomerID = 1;


🔒 8. Transactions & Locking

🔹 What is a Transaction?

A transaction is a logical unit of work with ACID properties (Atomicity, Consistency, Isolation, Durability).

Syntax

sql

 

START TRANSACTION;

 

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

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

 

COMMIT;

Use ROLLBACK; to undo changes on error.


📋 Transaction Isolation Levels

Level

Description

READ UNCOMMITTED

Dirty reads allowed

READ COMMITTED

No dirty reads

REPEATABLE READ

No non-repeatable reads

SERIALIZABLE

Fully isolated (slowest)


📁 9. Temporary Tables & Variables

🔹 Temporary Tables

sql

 

CREATE TEMPORARY TABLE TempData (

    ID INT,

    Info VARCHAR(50)

);

Useful for staging or intermediate data in complex queries.


🔹 Variables

sql

 

DECLARE @total INT;

SET @total = (SELECT COUNT(*) FROM Orders);


🧪 Real-World Application

Scenario: Multi-Step Discount Processing

  1. Create a view for high-value customers.
  2. Store their order data in a temp table.
  3. Use a window function to apply ranked discount tiers.
  4. Save results via a stored procedure.

Summary Table


Feature

Purpose

Common Use Case

View

Virtual table

Encapsulate and reuse queries

Index

Speed up SELECTs

Optimize performance

Stored Procedure

Logic in database

Business rules, reusable actions

Trigger

Auto-execute on data change

Auditing, enforcing constraints

Window Function

Row-wise aggregation

Ranking, running totals

CTE

Temporary subquery

Readable modular queries

Transactions

Group operations together

Banking, e-commerce, sensitive ops

Temp Table

Temporary data store

Batch processing, report staging

Back

FAQs


1. Q: Is SQL a programming language?

A: SQL is a query language, not a general-purpose programming language. It’s used to communicate with databases.

2. Q: What's the difference between SQL and MySQL?

A: SQL is a language. MySQL is a database management system (DBMS) that uses SQL.

3. Q: Can SQL be used with Python or Java?

A: Yes. Libraries like JDBC (Java) or sqlite3/sqlalchemy (Python) allow SQL integration.

4. Q: What is a JOIN in SQL?

A: A JOIN combines rows from two or more tables based on a related column between them.

5. Q: What is normalization?

A: The process of structuring data to reduce redundancy and improve integrity.

6. Q: What’s the difference between WHERE and HAVING?

A: WHERE filters rows before aggregation. HAVING filters groups after aggregation.

7. Q: Is SQL case-sensitive?

A: SQL keywords are case-insensitive, but string comparisons may be case-sensitive, depending on the DBMS.

8. Q: Can SQL handle big data?

A: SQL can handle moderate volumes. For large-scale datasets, use SQL-based engines like Presto, Hive, or BigQuery.

9. Q: What is a view in SQL?

A: A view is a virtual table based on the result of a query. It doesn't store data itself.

10. Q: How do I prevent SQL injection?

A: Use parameterized queries or prepared statements instead of dynamic SQL strings