Skip to main content

COALESCE & NULL Handling in SQL

 

🧠 1. What is NULL in SQL?  

NULL means  : 

  • 👉 missing value  
  • 👉 unknown value
  • 👉 no data available  


⚠️ NULL is NOT:  

❌ 0  

❌ Empty string  


⚡ 2. Problems with NULL Values  

NULL can affect:  

  • ❌ Calculations  
  • ❌ Comparisons
  • ❌ Reports  


Example 👇

SELECT salary + bonus

FROM employees;

If bonus is NULL → result becomes NULL ❌  


========================================================

🔥 3. COALESCE Function  

👉 Replaces NULL with another value  


✅ Syntax

COALESCE(column, value)


⚡ 4. Basic Example

SELECT name,

       COALESCE(bonus, 0) AS bonus

FROM employees;


✔️ If bonus is NULL → shows 0 instead  


⚡ 5. Multiple Values with COALESCE

SELECT name,

       COALESCE(phone, email, 'No Contact') AS contact

FROM employees;


✔️ Returns first non-NULL value  


🔥 6. IS NULL & IS NOT NULL  


👉 Find employees without bonus

SELECT * FROM employees

WHERE bonus IS NULL;


👉 Find employees with bonus

SELECT * FROM employees

WHERE bonus IS NOT NULL;


⚡ 7. NULL Handling in Aggregation

SELECT AVG(COALESCE(bonus, 0))

FROM employees;

✔️ Prevents NULL issues in calculations  


🎯 8. Practice Tasks  

1. Replace NULL bonus with 0  

2. Find rows with NULL values  

3. Find rows without NULL values  

4. Use COALESCE with multiple columns  

5. Calculate total salary safely using COALESCE  


⚡ Mini Challenge 🔥  

👉 Show employee total income:  

salary + bonus  

(If bonus is NULL → treat as 0)  


🔥 Mini Challenge Solution 💯


👉 Requirement:  

total_income = salary + bonus  

If bonus is NULL → treat it as 0  


✅ SQL Solution Using COALESCE

SELECT name,

       salary,

       COALESCE(bonus, 0) AS bonus,

       salary + COALESCE(bonus, 0) AS total_income

FROM employees;


✅ Example Output  

name : Amit, salary : 70000, bonus : 5000, total_income : 75000  

name : Neha, salary : 50000, bonus : 0, total_income : 50000  

name : Ravi, salary : 60000, bonus : 3000, total_income : 63000  


🧠 How It Works  

👉 COALESCE(bonus, 0)  

means:  

- If bonus exists → use bonus  

- If bonus is NULL → use 0  

  

Comments

Our Popular Posts

Oracle Object Oriented Concepts

An Object is a reusable application component that developers need to be aware of, rather than how it works. Object are basic entities in a system. They could represent a person, place, bank account, or any item that is handled by program. Every object consists of an attribute and one or more methods. An attribute could be any property of the object. Class:           It is a collection of attributes and functions (method) to plan the object. Object Table : ·    Object table are created by using the user defined data types. ·        In an object table each row or record is treated as an object. ·        Each row in an object table has an object Identified (OID), which is unique through out       the   database. ·       The rows or objects of an object table can be referenced by other objects with in the  database. ·    ...

About Oracle Buffer

About Oracle Buffer :- All Commands of SQL are typed at the SQL prompt. Only one SQL statement is managed in the SQL buffer. The current SQL statement replaces the previous SQL statement in the buffer. The SQL statements can be divided into different lines within the SQL buffer. Only one line i.e, the current line can be active at a time in the SQL buffer. At SQL prompt, editing is possible only in the current SQL buffer line. Every statement of SQL should be terminated using semi colon " ; ". One sql statement can contain only one semi colon. To run the previous or current SQL statement in the bufer type " / " at SQL prompt. To open the SQL editor type " ED " at SQL prompt.

IS NULL Operator

This operator tests for NULL values. It is the only operator that can be used to test for NULL’s. The negation is IS NOT NULL.       Examples :-        Select ename, deptno, comm from emp where comm IS NULL;         Select ename, deptno, comm from emp where comm IS NOT NULL;         Select ename, deptno, job, mgr from emp where mgr IS NULL;         Select ename, deptno, job, mgr from emp where mgr IS NOT NULL; HOME

Introduction to SQL

INTRODUCTION : - SQL usually pronounced as “Sequel” stands for Structured Query Language. SQL is the native language of the Oracle Server. It is the language used to communicate with the database. Again SQL consists of SQL statements and SQL*Plus commands. SQL statements are used to talk to the database. When you enter a SQL statement, it is stored in a part of the memory called the SQL Buffer and remains there until a new statement is entered. SQL*Plus is an Oracle tool that recognizes and submits  SQL statements to the Oracle server for execution and contains its own command language. Features of SQL:- It is very easy to write, it can be used by all kinds of users with little or not programming experience. It is a non-procedural language. It reduces the amount of time required for creating and maintaining systems. It is based on American National Standards Iinstitute (ANSI) standard SQL. It manipulates data and ...

Filtering and Sorting data using SQL statements

  Filtering & Sorting Data using SQL     Once you know the basics ( SELECT , FROM , WHERE ), filtering and sorting helps you get the exact rows from tables .   1. Filtering with Conditions ( AND , OR , NOT )  - Use WHERE to filter rows. - Combine with logical operators :     • AND: all conditions true      • OR: any condition true      • NOT: negate condition   - - All conditions true (AND) SELECT *  FROM employees WHERE department = 'Sales'    AND salary > 50000; -- Any condition true (OR) SELECT *  FROM employees WHERE department = 'Sales'     OR department = 'Marketing'; -- Negate condition (NOT) SELECT *  FROM employees WHERE NOT department = 'HR';   2. Pattern Matching with LIKE   - % = any sequence, _ = single char     • Names starting with 'J'      • Names with 4 letters starting with 'J'   - - N...

The "Dual Table" in Oracle

> The " DUAL " table is a one row and one column table. The owner of this table is "SYS" but it's accessible to all the db users.  > It is having single column called as " DUMMY " > It is used to test SQL expression with out querying to the main/real tables.  Eg : 1> SELECT SYSDATE FROM DUAL; O.P : It will print current date and time.       2> SELECT 'Hello, Welcome to SQL' from DUAL; O.P :  3> SELECT 5*9 AS RESULT FROM DUAL; O.P:  #SQL #LEARNSQL #DUALTABLE

LIKE operator in ORACLE

Wild Charcters :- These characters are used to provide pattern matching which means comparision to data is provided with partial value. ORACLE provides the following wild characters.            i)      _(Underscore) -> Represents single character.             ii)      %(Percentage) -> Represents group of character. Ø   Inorder to have wild characters for the comparision to partial data, LIKE operator is used. Ø   If these wild characters are formed in data, then the wild characters can be converted to data using ‘\’ (backslash). It is represented through an option called ‘ESCAPE’ , which is written after like operator. Examples :- Display employee number and employee name of all those employees whose names contain 4 characters. Ans : select empno, ename from emp           Where ename LIKE ‘---...

DISTINCT - Supressing Duplicate Rows in Output

Supressing Duplicate Rows : = Sometimes, your query results contain duplicate rows. You can eliminate such rows by adding  the keyword DISTINCT immediately after the keyword SELECT. Multiple columns can be declared after the DISTINCT qualifier. The DISTINCT qualifier affects all the selected columns, and represents a DISTINCT combination of the columns. When DISTINCT is implemented upon a column which may contain NULL values, all the NULLS in the column together treated as one DISTINCT group. A select statement should have one DISTINCT keyword. Examples :=           Ø   Select DISTINCT deptno from emp;             Ø   Select DISTINCT deptno,mgr from emp;   Ø   Select DISTINCT deptno,job from emp;        HOME