SQL Functions
SQL Functions
These
functions can be categorized into several types, including aggregate functions, scalar functions, and
window functions. Here's a detailed look at these SQL functions:
Aggregate functions perform a calculation on a set of values and return a single value. They are
commonly used with the `GROUP BY` clause.
```sql
```
```sql
```
```sql
```
```sql
```
```sql
```sql
```
```sql
```
```sql
```
```sql
```
```sql
```
- **ROUND()**: Rounds a numeric value to the nearest integer or to a specified number of decimal
places.
```sql
```
```sql
SELECT NOW();
```
```sql
```
```sql
```
Window functions perform calculations across a set of table rows related to the current row. They
are used with the `OVER` clause.
```sql
SELECT name, salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num FROM
employees;
```
- **RANK()**: Assigns a rank to rows within a partition, with gaps in rank values when there are ties.
```sql
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS rank FROM employees;
```
- **DENSE_RANK()**: Assigns a rank to rows within a partition, without gaps in rank values when
there are ties.
```sql
SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank FROM
employees;
```
```sql
SELECT name, salary, NTILE(4) OVER (ORDER BY salary DESC) AS ntile FROM employees;
```
- **LEAD()**: Provides access to a row at a specified physical offset following the current row.
```sql
SELECT name, salary, LEAD(salary, 1) OVER (ORDER BY salary DESC) AS next_salary FROM
employees;
```
- **LAG()**: Provides access to a row at a specified physical offset preceding the current row.
```sql
SELECT name, salary, LAG(salary, 1) OVER (ORDER BY salary DESC) AS previous_salary FROM
employees;
```
```sql
SELECT name, salary, FIRST_VALUE(salary) OVER (ORDER BY salary DESC) AS highest_salary FROM
employees;
```
```sql
SELECT name, salary, LAST_VALUE(salary) OVER (ORDER BY salary DESC) AS lowest_salary FROM
employees;
```
### Examples
```sql
FROM employees
GROUP BY department;
```
```sql
FROM employees;
```
```sql
FROM employees;
```
These functions enhance the capabilities of SQL by allowing you to perform complex calculations and
data transformations directly within your queries. Understanding and using these functions
effectively can significantly improve your ability to manipulate and analyze data in SQL.