Aggregate Functions in SQL
Aggregate Functions in SQL
Aggregate functions perform calculations on a set of values and return a single value, except
for COUNT (*).
1. MIN():
o Returns the smallest value within a selected column.
o Example: SELECT MIN(salary) FROM emp;
2. MAX():
o Returns the largest value within a selected column.
o Example: SELECT MAX(salary) FROM emp;
3. COUNT():
o Returns the number of rows in a set.
o Example: SELECT COUNT(*) FROM emp;
4. SUM():
o Returns the sum of numerical values in a column.
o Example: SELECT SUM(salary) FROM emp;
5. AVG():
o Returns the average value of a numerical column.
o Example: SELECT AVG(salary) FROM emp;
COUNT(*):
o Counts the total number of rows in the table, including NULL values.
COUNT(column):
o Counts the number of records where the specified column is not NULL,
excluding NULL values.
DISTINCT Keyword
The DISTINCT keyword is used with the SELECT statement to eliminate duplicate records and
fetch unique records. In situations where multiple duplicate records exist in a table, it makes
sense to fetch only unique records.
LOWER()
UPPER()
INITCAP()
Example: SELECT UPPER (firstname), LOWER (lastname), INITCAP (firstname) FROM emp;
1. ADD_MONTHS (): Returns the date with a given number of months added.
o Example: SELECT ADD_MONTHS(DATE '2016-02-29', 1) FROM dual;
o (Output: 31-MAR-16)
2. MONTHS_BETWEEN (): Returns the number of months between two dates.
o Example: SELECT MONTHS_BETWEEN(DATE '05-JAN-81', DATE '05-JAN-80')
FROM dual; (Output: 12)
3. NEXT_DAY (): Gets the first weekday that is later than a specified date.
o Example: SELECT NEXT_DAY(SYSDATE, 'MONDAY') FROM dual;
4. LAST_DAY (): Gets the last day of the month for a specified date.
o Example: SELECT LAST_DAY(SYSDATE) FROM dual;
5. SYSDATE: Returns the current system date and time.
o Example: SELECT SYSDATE FROM dual;
6. SYSTIMESTAMP (): Returns the system date and time, including fractional seconds
and time zone.
o Example: SELECT SYSTIMESTAMP FROM dual;
7. TO_DATE (): Converts a character string to a DATE value.
o Example: SELECT * FROM EMPLOYEE12 WHERE EDOJ = TO_DATE('oct-05-
2018', 'MM-DD-YYYY');
8. TO_CHAR (): Converts a DATE or INTERVAL value to a character string in a specified
format.
o Example: SELECT * FROM EMPLOYEE12 WHERE TO_CHAR(EDOJ, 'YYYY') =
'2020';