๐ง Day 8 โ Views, Analytical Functions & Set Operators in SQL
๐ง Day 8 โ Views, Analytical Functions & Set Operators in SQL
๐ช Views in SQL
A view is a virtual table that stores only the SQL query, not the actual data.
When the base (master) table data changes โ the view reflects it automatically (except in Materialized Views).
๐งฉ Types of Views
1๏ธโฃ Simple View
-
Created from a simple SQL query (single table, no joins).
-
Example:
2๏ธโฃ Complex View
-
Created using joins, group functions, or multiple tables.
-
Example:
3๏ธโฃ Materialized View
-
Stores a physical copy (snapshot) of data.
-
Changes in master table wonโt appear automatically.
-
Must refresh to sync.
๐ Refreshing Materialized Views
-
Complete Refresh โ Reloads entire data.
-
Fast Refresh โ Applies only incremental changes.
-
Force Refresh โ Chooses between fast or complete depending on availability.
Alternate syntax:
๐งฎ Analytical / Window Functions
These allow you to perform rankings, comparisons, or running totals across rows without grouping.
| Function | Description |
|---|---|
| LEAD() | Shows value ahead of current row |
| LAG() | Shows value behind the current row |
| RANK() | Gives rank but skips next number for ties |
| DENSE_RANK() | Gives rank without skipping numbers for ties |
| ROW_NUMBER() | Assigns a unique sequential number |
๐ก Examples
๐ง Example (Ranking difference):
| Salary | RANK | DENSE_RANK |
|---|---|---|
| 500 | 1 | 1 |
| 200 | 2 | 2 |
| 200 | 2 | 2 |
| 100 | 5 | 3 |
| 100 | 5 | 3 |
| 50 | 9 | 4 |
๐ข Sorting (ORDER BY)
| Keyword | Meaning |
|---|---|
| ASC | Ascending order (default) |
| DESC | Descending order |
๐งฉ Pseudo Columns
Pseudo columns act like table columns but arenโt actually stored in the table.
| Pseudo Column | Description |
|---|---|
| ROWNUM | Sequence number of returned rows |
| ROWID | Physical address of row in DB |
| SYSDATE | Current date |
| SYSTIMESTAMP | Current date + time |
| DISTINCT / UNIQUE | Remove duplicates |
Examples:
โ๏ธ SET Operators
Used to combine results from multiple queries.
๐ Rules:
-
Number of columns must match.
-
Data types must be same.
| Operator | Description |
|---|---|
| UNION | Combines results, removes duplicates |
| UNION ALL | Combines all, keeps duplicates |
| INTERSECT | Returns only common rows |
| MINUS | Returns rows in first query not in second |
๐ป Examples
โ Summary
| Concept | Key Point |
|---|---|
| View | Virtual table that stores SQL logic |
| Materialized View | Physical snapshot that needs refresh |
| Analytical Functions | Compare or rank rows without grouping |
| Sorting | ORDER BY sorts results |
| Pseudo Columns | Special system-generated columns |
| Set Operators | Combine query results |