Dialect note:
IFNULLis MySQL-specific; standard SQL usesCOALESCE.GREATEST,LEAST, andROUNDcan differ across databases, especially forNULLand tie handling.
Turning Raw Data into Clean and Useful Information
In real-world databases, data is rarely stored exactly how we want to display it.
Sometimes we need to:
- round decimal values
- convert negative numbers into positive values
- find the highest score among multiple columns
- replace missing values with defaults
- select the first available value from multiple columns
SQL provides several built-in utility functions to solve these problems efficiently.
Today we'll learn:
- ROUND()
- ABS()
- GREATEST()
- LEAST()
- IFNULL()
- COALESCE()
These functions are heavily used in reports, dashboards, analytics, and production applications.
Dataset Used
We'll use the following students table throughout this lesson.
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30) NULL,
phone VARCHAR(20) NULL,
fee_paid DECIMAL(10,2) NULL,
score_change DECIMAL(10,2) NULL,
test1 INT NULL,
test2 INT NULL,
test3 INT NULL
);(Use the same INSERT statements you've already added.)
Student Table
| id | name | city | phone | fee_paid | score_change | test1 | test2 | test3 |
|---|---|---|---|---|---|---|---|---|
| 1 | Aisha | Delhi | NULL | 2804.45 | -12.25 | 55 | 60 | 58 |
| 2 | Rohan | Mumbai | '' | 3303.06 | -80 | 40 | NULL | 52 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
1. ROUND()
What is ROUND()?
ROUND() rounds a numeric value to a specified number of decimal places.
Syntax
ROUND(number, decimal_places)If decimal places are omitted:
ROUND(number)SQL rounds to the nearest integer.
Example
SELECT
id,
name,
fee_paid,
ROUND(fee_paid,0) AS fee_rupees,
ROUND(fee_paid,2) AS fee_2dp
FROM students
ORDER BY id;Output
| name | fee_paid | fee_rupees | fee_2dp |
|---|---|---|---|
| Aisha | 2804.45 | 2804 | 2804.45 |
| Arjun | 3717.94 | 3718 | 3717.94 |
| Deepak | NULL | NULL | NULL |
Standard Rounding Rules
0.5 or above
↓
Round UpExample
8.5 → 98.6 → 9Less than 0.5
↓
Round DownExample
8.4 → 88.2 → 8Real-Life Use Cases
ROUND() is commonly used for:
- displaying prices
- invoice totals
- GST calculations
- average ratings
- financial reports
Example:
Instead of showing
₹2804.453246display
₹2804.45Important Rules
- ROUND() works only on numeric values.
- NULL remains NULL.
- It does not modify the stored value, only the displayed result.
2. ABS()
What is ABS()?
ABS() returns the absolute value of a number.
It measures the distance from zero.
Negative numbers become positive.
Positive numbers stay unchanged.
NULL remains NULL.
Syntax
ABS(number)Example
SELECT
id,
name,
score_change,
ABS(score_change) AS abs_score_change
FROM students
ORDER BY id;Output
| name | score_change | abs_score_change |
|---|---|---|
| Aisha | -12.25 | 12.25 |
| Rohan | -80 | 80 |
| Arjun | 10 | 10 |
| Meenal | NULL | NULL |
Internal Understanding
Think of ABS() as removing the minus sign.
-50
↓
50120
↓
120Real-Life Use Cases
Useful for:
- score differences
- stock price movement
- balance adjustments
- profit/loss comparison
- measuring deviations
Sometimes you only care about
How much did it change?not
Whether it increased or decreased.Important Rules
- Positive values remain unchanged.
- Negative values become positive.
- NULL stays NULL.
3. GREATEST() and LEAST()
These two functions compare multiple values in the same row.
Unlike MIN() and MAX(), they do not aggregate multiple rows.
They simply compare multiple expressions.
GREATEST()
Returns the largest value.
Syntax
GREATEST(value1, value2, value3...)LEAST()
Returns the smallest value.
Syntax
LEAST(value1, value2, value3...)Example
SELECT
id,
name,
test1,
test2,
test3,
GREATEST(test1,test2,test3) AS greatest_score,
LEAST(test1,test2,test3) AS least_score
FROM students
ORDER BY id;Output
| name | test1 | test2 | test3 | greatest | least |
|---|---|---|---|---|---|
| Aisha | 55 | 60 | 58 | 60 | 55 |
| Arjun | 72 | 70 | 75 | 75 | 70 |
| Pallavi | 92 | 90 | 91 | 92 | 90 |
Mental Model
Imagine comparing three exam scores.
55
60
58Highest
↓
60Lowest
↓
55SQL does exactly this for every row.
Real-Life Use Cases
Useful for:
- highest exam score
- lowest temperature
- maximum quarterly sales
- minimum stock price
- best employee rating
Important Rule About NULL
One very important behavior in MySQL:
If any argument passed to GREATEST() or LEAST() is NULL, the result is also NULL.
Example
78
NULL
65Result
GREATEST → NULLLEAST → NULLBecause SQL cannot compare an unknown value.
Difference Between MAX() and GREATEST()
| MAX() | GREATEST() |
|---|---|
| Works across multiple rows | Works across multiple columns |
| Aggregate Function | Scalar Function |
| Used with GROUP BY | Used per row |
Example:
MAX(salary)Highest salary among employees.
GREATEST(test1,test2,test3)Highest score for one student.
Summary
| Function | Purpose |
|---|---|
| ROUND() | Round numbers |
| ABS() | Remove negative sign |
| GREATEST() | Largest value in a row |
| LEAST() | Smallest value in a row |
4. IFNULL()
What is IFNULL()?
IFNULL() is used to replace NULL values with another value.
Think of it as saying:
"If this value is missing, show something else."
It does not filter rows. It only changes what is displayed.
Syntax
IFNULL(expression, replacement_value)It accepts exactly 2 arguments:
- expression → value to check
- replacement → value to show if expression is NULL
Example
SELECT
id,
name,
IFNULL(phone, 'Not Provided') AS phone_status
FROM students;Output
| Name | Phone Status |
|---|---|
| Aisha | Not Provided |
| Rohan | (empty) |
| Meenal | 8888000004 |
| Neha | Not Provided |
| Tanya | (empty) |
Why Didn't Rohan Become "Not Provided"?
Because his phone number is not NULL.
It is an empty string ('').
NULL
↓
Missing value''
↓
Value exists
But emptyIFNULL only replaces NULL, not empty strings.
Handling NULL and Empty Strings Together
Production databases usually contain:
- NULL
- ''
- ' ' (spaces)
We should normalize them first.
SELECT
id,
name,
phone,
IFNULL(NULLIF(phone,''),'Not Provided') AS final_phone
FROM students;How This Works
Step 1
NULLIF(phone,'')Converts:
''
↓
NULLStep 2
IFNULL(...,'Not Provided')Converts
NULL
↓
Not ProvidedFinal Output
| Name | Phone | Final Phone |
|---|---|---|
| Aisha | NULL | Not Provided |
| Rohan | '' | Not Provided |
| Meenal | 8888000004 | 8888000004 |
Real-Life Use Cases
Useful for:
- Missing phone numbers
- Missing addresses
- Missing profile pictures
- Missing product images
- Missing salaries
- Missing coupon codes
Important Rules
✅ Replaces only NULL
❌ Does not replace ''
❌ Does not remove spaces
5. COALESCE()
What is COALESCE()?
COALESCE returns the first NON-NULL value from a list.
Think of it as trying one option after another until it finds data.
Syntax
COALESCE(value1, value2, value3, ...)Unlike IFNULL(),
COALESCE can accept multiple values.
Dataset Used
CREATE TABLE coalesce_demo (
id INT PRIMARY KEY,
primary_email VARCHAR(80),
work_email VARCHAR(80),
personal_email VARCHAR(80),
hours_logged DECIMAL(10,2),
default_hours DECIMAL(10,2)
);Scenario 1 — First Available Email
SELECT
id,
COALESCE(primary_email,
work_email,
personal_email) AS contact_email
FROM coalesce_demo;Output
| id | Contact Email |
|---|---|
| 1 | aisha@company.com |
| 2 | rohan@company.com |
| 3 | meera@yahoo.com |
| 4 | NULL |
| 5 | '' |
Internal Working
SQL checks one value at a time.
Primary Email
↓
NULL ?
↓
Yes
↓
Check Work Email
↓
NULL ?
↓
Yes
↓
Check Personal Email
↓
Found!
↓
Return ItAs soon as SQL finds a non-null value,
it stops checking.
Scenario 2 — Default Email
SELECT
id,
COALESCE(
primary_email,
work_email,
personal_email,
'hello@tuf'
) AS contact_email
FROM coalesce_demo;Output
| id | Contact Email |
|---|---|
| 1 | aisha@company.com |
| 2 | rohan@company.com |
| 3 | meera@yahoo.com |
| 4 | hello@tuf |
| 5 | '' |
Why?
For id = 4, every email is NULL.
So SQL reaches the default value.
Scenario 3 — Skip Empty Strings Too
SELECT
id,
COALESCE(
NULLIF(TRIM(primary_email),''),
work_email,
personal_email
) AS contact_email
FROM coalesce_demo;Why TRIM()?
Suppose data contains
' 'It is not NULL.
It is only spaces.
TRIM removes spaces.
' '
↓
''Then
NULLIF('', '')becomes
NULLNow COALESCE ignores it.
Final Output
| id | Contact Email |
|---|---|
| 1 | aisha@company.com |
| 2 | rohan@company.com |
| 3 | meera@yahoo.com |
| 4 | NULL |
| 5 | raj@gmail.com |
Real-Life Use Cases
COALESCE is heavily used for:
- Contact emails
- Delivery address
- Phone numbers
- Backup addresses
- Default prices
- Missing salaries
IFNULL() vs COALESCE()
| Feature | IFNULL() | COALESCE() |
|---|---|---|
| Number of arguments | Exactly 2 | Two or more |
| Returns | Replacement value | First non-NULL value |
| MySQL | ✅ | ✅ |
| PostgreSQL | ❌ | ✅ |
| ANSI SQL | ❌ | ✅ |
IS NULL vs IS NOT NULL vs IFNULL() vs COALESCE()
| Concept | Purpose | Used In | MySQL | PostgreSQL |
|---|---|---|---|---|
| IS NULL | Find missing values | WHERE | ✅ | ✅ |
| IS NOT NULL | Find available values | WHERE | ✅ | ✅ |
| IFNULL() | Replace NULL | SELECT | ✅ | ❌ |
| COALESCE() | Return first non-NULL value | SELECT | ✅ | ✅ |
Mental Model
IS NULL
Is this value missing?
↓
TRUE / FALSEUsed for filtering rows.
IFNULL()
NULL ?
↓
Yes
↓
Show replacementCOALESCE()
Value 1
↓
NULL?
↓
Yes
↓
Value 2
↓
NULL?
↓
Yes
↓
Value 3
↓
Found!
↓
Return ItCommon Mistakes to Avoid
1. IFNULL() does NOT replace empty strings
IFNULL('', 'Unknown')Result
''Not
Unknown2. Forgetting NULLIF()
Production data often contains
''instead of NULL.
Always normalize first.
IFNULL(NULLIF(phone,''),'Not Provided')3. Confusing IFNULL() with COALESCE()
Wrong thinking:
They are identical.Not true.
IFNULL
↓
Only 2 valuesCOALESCE
↓
Unlimited values4. Using COALESCE() in PostgreSQL
Good practice:
Prefer COALESCE because it is ANSI SQL standard.
5. Forgetting TRIM()
Sometimes data contains:
' 'instead of
''Always use
TRIM()before
NULLIF()6. Assuming COALESCE Ignores Empty Strings
It does not.
''
↓
Valid ValueCOALESCE returns it immediately.
7. Replacing NULL in WHERE
This is incorrect:
WHERE IFNULL(city,'Delhi')Use
WHERE city IS NULLfor filtering.
Use IFNULL only for displaying values.
Review Tips
Remember this rule:
- IS NULL → Filter missing rows.
- IS NOT NULL → Filter available rows.
- IFNULL() → Replace NULL with one default value.
- COALESCE() → Return the first available value from multiple options.
- NULLIF() → Convert a specific value (like
'') intoNULL. - TRIM() → Remove leading and trailing spaces before cleaning data.
Quick Revision Table
| Function | Purpose | Example |
|---|---|---|
ROUND() | Round numbers | ROUND(price,2) |
ABS() | Absolute value | ABS(-20) → 20 |
GREATEST() | Largest value in a row | GREATEST(test1,test2,test3) |
LEAST() | Smallest value in a row | LEAST(test1,test2,test3) |
IFNULL() | Replace NULL | IFNULL(phone,'N/A') |
COALESCE() | First non-NULL value | COALESCE(work_email, personal_email, 'default@mail.com') |
NULLIF() | Convert matching value to NULL | NULLIF(phone,'') |
TRIM() | Remove leading/trailing spaces | TRIM(city) |