1.
View Example
A view in SQL is a virtual table created using a SQL query. It does not store data itself but
displays data from one or more tables. Here's an example:
Scenario
Suppose we have two tables: Orders and Customers.
Customers Table
CustomerID CustomerName City
1 Alice New York
2 Bob Los Angeles
3 Charlie Chicago
Orders Table
OrderID CustomerID Product Quantity
101 1 Laptop 1
102 1 Mouse 2
103 2 Keyboard 1
104 3 Monitor 1
Create a View
We want a view that shows customer names, cities, and the products they ordered.
CREATE VIEW CustomerOrders AS
SELECT
Customers.CustomerName,
Customers.City,
Orders.Product,
Orders.Quantity
FROM
Customers
JOIN
Orders
ON
Customers.CustomerID = Orders.CustomerID;
Output of the View (CustomerOrders)
When you query the view:
SELECT * FROM CustomerOrders;
Result
CustomerName City Product Quantity
Alice New York Laptop 1
Alice New York Mouse 2
Bob Los Angeles Keyboard 1
Charlie Chicago Monitor 1
Key Points about the View
The view combines data from both Customers and Orders tables.
It simplifies querying, especially for complex joins.
You can use the view just like a table but remember it dynamically pulls data from the
underlying tables.
2. Index Example
An index in SQL is a database object used to improve the speed of data retrieval. It allows
the database to quickly find rows without scanning the entire table. Here's an example of an
indexed table with explanation.
Scenario
Consider a table Employees:
EmployeeID Name Department Age Salary
1 Alice IT 30 70,000
2 Bob HR 45 50,000
3 Charlie IT 28 60,000
4 Diana Finance 35 80,000
5 Eve HR 25 55,000
Creating an Index
If you often query employees by the Department column, you can create an index to speed
up these queries.
CREATE INDEX idx_department ON Employees(Department);
Effect of the Index
Indexed Table View
An index creates an internal structure that maps the values of the Department column to
corresponding rows. This isn't directly visible but works behind the scenes. The indexed
representation might look like this:
Department Row Reference
Finance Row 4
HR Row 2, Row 5
IT Row 1, Row 3
Without Index
A query like the following:
SELECT * FROM Employees WHERE Department = 'IT';
Would perform a full table scan (check each row).
With Index
Using the index, the database directly looks up the department "IT" and retrieves rows 1 and
3, avoiding a full scan.
Benefits
Faster Queries: Speeds up searches and data retrieval.
Drawbacks: Adds overhead during insert/update/delete operations because the index
also needs updating.
This indexed structure is especially helpful for large tables where repeated queries on specific
columns are frequent.
3.