🧠 Day 4: SQL Aggregate, Alias, and Date Functions Explained
🧠 Day 4: SQL Aggregate, Alias, and Date Functions Explained
📊 Aggregate Functions
Aggregate functions perform calculations on multiple rows and return a single summarized result.
-
SUM() – Returns the total of all numeric values.
-
AVG() – Returns the average value.
-
MIN() – Returns the smallest value.
-
MAX() – Returns the largest value.
-
COUNT() – Counts all non-null values (includes duplicates).
-
COUNT(DISTINCT) – Counts only unique non-null values (excludes duplicates).
🧩 Example:
📝 Note:
-
Aggregate functions ignore NULL values.
-
When using aggregate functions with other columns, GROUP BY is mandatory.
🏷️ Alias (Renaming Columns)
Alias is used to give a temporary name to columns or tables for readability.
➡️ Both AS and space work for aliases.
⚖️ Difference Between WHERE and HAVING
| Feature | WHERE | HAVING |
|---|---|---|
| Filters | Rows before grouping | Groups after aggregation |
| Works on | Non-aggregated columns | Aggregated values |
| Position | Before GROUP BY |
After GROUP BY |
🧩 Example:
📅 Date Functions in SQL
-
SYSDATE → Returns the current date.
-
SYSTIMESTAMP → Current date + time.
-
ADD_MONTHS(date, n) → Adds or subtracts months.
-
MONTHS_BETWEEN(date1, date2) → Finds difference in months.
-
NEXT_DAY(date, day) → Returns next occurrence of the given weekday.
-
(1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat)
-
-
LAST_DAY(date) → Returns last day of the month.
✅ Summary:
-
Aggregate functions help summarize data.
-
Aliases make results more readable.
-
WHERE filters data before grouping, HAVING after grouping.
-
Date functions simplify calculations with dates.