Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧠 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:
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
✅ 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 |
A: SQL is a query language, not a general-purpose programming language. It’s used to communicate with databases.
A: SQL is a language. MySQL is a database management system (DBMS) that uses SQL.
A: Yes. Libraries like JDBC (Java) or sqlite3/sqlalchemy (Python) allow SQL integration.
A: A JOIN combines rows from two or more tables based on a related column between them.
A: The process of structuring data to reduce redundancy and improve integrity.
A: WHERE filters rows before aggregation. HAVING filters groups after aggregation.
A: SQL keywords are case-insensitive, but string comparisons may be case-sensitive, depending on the DBMS.
A: SQL can handle moderate volumes. For large-scale datasets, use SQL-based engines like Presto, Hive, or BigQuery.
A: A view is a virtual table based on the result of a query. It doesn't store data itself.
A: Use parameterized queries or prepared statements instead of dynamic SQL strings
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)