ποΈ Day 3: SQL Number & Null Functions
ποΈ Day 3: SQL Number & Null Functions
Welcome to Day 3 of your SQL learning series!
In this session, weβll explore Number Functions and Null Functions β two important categories that help us handle numeric values and missing data effectively in SQL.
π’ Number Functions in SQL
Number functions allow you to perform mathematical operations on numeric data.
Letβs look at some of the most commonly used ones.
1. ROUND()
Purpose: Rounds a number to the nearest integer or specified decimal place.
Logic:
-
If the next decimal is β₯ 5 β rounds up
-
If the next decimal is < 5 β remains same
Example:
2. TRUNC()
Purpose: Truncates (removes) the decimal part of a number without rounding.
Example:
3. ABS()
Purpose: Returns the absolute value of a number β removes any negative sign.
Example:
4. CEIL()
Purpose: Returns the next highest integer greater than or equal to the number.
Example:
5. FLOOR()
Purpose: Returns the next lowest integer less than or equal to the number.
Example:
6. SIGN()
Purpose: Identifies whether a number is positive, negative, or zero.
| Input | Output | Meaning |
|---|---|---|
| Positive number | 1 | Greater than 0 |
| Negative number | -1 | Less than 0 |
| Zero | 0 | Equal to 0 |
Example:
π§© NULL Functions in SQL
NULL represents a missing or unknown value in SQL.
These functions help handle such null values effectively in queries.
1. NVL()
Purpose: Replaces a NULL value with a specified value.
Syntax:
Example:
2. NVL2()
Purpose: Returns one value if not null, otherwise another value.
Syntax:
Example:
3. NULLIF()
Purpose: Compares two expressions.
If they are equal, returns NULL.
If different, returns the first expression.
Example:
4. COALESCE()
Purpose: Returns the first non-null value from a list of expressions.
Example:
If all values are NULL β output will be NULL.
π» Practice Examples
Here are some simple queries to test what youβve learned:
π§ Quick Summary
| Category | Function | Description |
|---|---|---|
| Number | ROUND | Rounds a number |
| TRUNC | Removes decimals | |
| ABS | Removes negative sign | |
| CEIL | Rounds up | |
| FLOOR | Rounds down | |
| SIGN | Identifies sign | |
| Null | NVL | Replace NULL with a value |
| NVL2 | Conditional replacement | |
| NULLIF | Returns NULL if both same | |
| COALESCE | Returns first non-null value |