SQL Interview Questions Your Ultimate Guide
Question: How do you handle NULL values in SQL?
Answer:
In SQL, NULL represents the absence of a value or an unknown value. It is different from an empty string or zero; NULL simply means that the value is missing or undefined. Handling NULL values correctly is crucial to ensure data integrity and avoid unexpected behavior in queries. Here are several ways to handle NULL values in SQL:
1. Checking for NULL values:
- IS NULL: Used to check if a value is NULL.
- IS NOT NULL: Used to check if a value is not NULL.
SELECT * FROM Employees WHERE salary IS NULL;
SELECT * FROM Employees WHERE salary IS NOT NULL;
- Example: The query
SELECT * FROM Employees WHERE salary IS NULL;
retrieves all rows where the salary is NULL (i.e., not yet assigned).
2. Handling NULL in SELECT queries:
-
COALESCE(): This function returns the first non-NULL value in a list of expressions. It is useful for substituting a NULL with a default value.
SELECT COALESCE(salary, 0) FROM Employees;
- In this example, if
salary
is NULL, it will return0
instead.
- In this example, if
-
IFNULL() (MySQL) / NVL() (Oracle): Similar to
COALESCE()
, these functions replace NULL values with a specified value. Different databases have different implementations:- In MySQL:
IFNULL(expression, replacement_value)
- In Oracle:
NVL(expression, replacement_value)
SELECT IFNULL(salary, 0) FROM Employees; -- MySQL
- In MySQL:
-
NULLIF(): This function compares two expressions. If they are equal, it returns NULL; otherwise, it returns the first expression.
SELECT NULLIF(salary, 0) FROM Employees;
- If
salary
is 0, the result will beNULL
; otherwise, it will return the actual salary.
- If
3. NULL in Aggregates:
-
When performing aggregate functions like
SUM()
,AVG()
,COUNT()
,MIN()
, andMAX()
, NULL values are ignored. For example, theSUM()
function does not count NULL values, but it will still calculate the sum of non-NULL values.SELECT SUM(salary) FROM Employees;
- If there are NULL values in the
salary
column, they will be ignored, and only non-NULL salaries will be summed up.
- If there are NULL values in the
4. Using NULL in INSERT statements:
-
You can insert a
NULL
value into a column if the column allowsNULL
values.INSERT INTO Employees (name, salary) VALUES ('John Doe', NULL);
- In this example, the
salary
is inserted asNULL
, assuming that the column allows NULLs.
- In this example, the
5. Filtering and Handling NULL values in WHERE clause:
-
NULL values cannot be compared using
=
or!=
. Instead, you must useIS NULL
orIS NOT NULL
.SELECT * FROM Employees WHERE salary = NULL; -- Incorrect, won't work! SELECT * FROM Employees WHERE salary IS NULL; -- Correct
-
To handle NULLs when filtering, you can use
IS NULL
orIS NOT NULL
in theWHERE
clause, as shown above.
6. Default Values for NULL:
-
You can set default values for columns to avoid inserting NULL values when no data is provided. This is typically done when creating or altering the table schema.
CREATE TABLE Employees ( id INT, name VARCHAR(50), salary DECIMAL(10, 2) DEFAULT 0.00 );
- In this case, if no
salary
is provided during an insert, it will default to0.00
instead of NULL.
- In this case, if no
7. Replacing NULL values in an UPDATE statement:
-
If you want to update NULL values to something else, you can use the
UPDATE
statement with theIS NULL
condition.UPDATE Employees SET salary = 0 WHERE salary IS NULL;
- This query sets all NULL
salary
values to0
.
- This query sets all NULL
8. Handling NULLs in JOINs:
-
In JOIN operations, NULL values are treated specially:
- INNER JOIN: NULL values from either table are excluded.
- LEFT JOIN (or RIGHT JOIN): If a NULL value is in the left table, NULLs will appear in the right table columns (and vice versa).
SELECT E.name, D.department_name FROM Employees E LEFT JOIN Departments D ON E.department_id = D.department_id;
- If an employee doesn’t belong to any department, their
department_name
will be NULL in the result.
9. NULL in SQL Constraints:
-
Columns can be defined to allow
NULL
or not. If you want to prevent NULL values, you can define a column asNOT NULL
.CREATE TABLE Employees ( id INT NOT NULL, name VARCHAR(50) NOT NULL, salary DECIMAL(10, 2) NULL );
- The
salary
column can accept NULL values, whileid
andname
cannot be NULL.
- The
Key Takeaways:
- NULL represents an unknown or missing value and cannot be treated like other values (e.g., zero or empty string).
- Use IS NULL or IS NOT NULL to check for NULL values.
- Functions like COALESCE(), IFNULL(), and NVL() help handle NULLs by substituting default values.
- Aggregate functions ignore NULL values, but you can use COUNT() to include NULL values by counting rows.
- When inserting, updating, or selecting, carefully handle NULLs to avoid errors and unexpected results.
Question: Write a SQL query to find employees who have not received a salary in the last month.
Answer:
To find employees who have not received a salary in the last month, we need to compare the salary_date
(or similar date column) with the current date and filter out employees who received their last salary payment in the past month. Here’s a SQL query to achieve this:
Assuming the following table structure:
- Employees table with columns:
employee_id
,name
- Salaries table with columns:
employee_id
,salary_amount
,salary_date
SELECT E.employee_id, E.name
FROM Employees E
LEFT JOIN Salaries S ON E.employee_id = S.employee_id
WHERE S.salary_date < CURDATE() - INTERVAL 1 MONTH OR S.salary_date IS NULL;
Explanation:
- LEFT JOIN: We use a
LEFT JOIN
to ensure that even employees who don’t have any salary records are included in the result. - S.salary_date < CURDATE() - INTERVAL 1 MONTH: This condition filters out employees who received their last salary more than a month ago.
- S.salary_date IS NULL: This condition includes employees who haven’t received any salary at all (i.e., they don’t have any entries in the
Salaries
table).
This query will return all employees who have not received a salary in the last month or have never received a salary.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as SQL interview questions, SQL interview experiences, and details about various SQL job positions. Click here to check it out.
Tags
- SQL
- SQL interview questions
- SQL joins
- SQL queries
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL JOIN
- Subqueries
- SQL normalization
- SQL denormalization
- Primary key
- Foreign key
- GROUP BY
- HAVING vs WHERE
- SQL views
- SQL indexes
- DENSE RANK
- ROW NUMBER
- SQL DISTINCT
- SQL SELECT INTO
- CHAR vs VARCHAR
- NULL values in SQL
- SQL performance optimization
- SQL aggregate functions
- SQL database design
- SQL DELETE vs TRUNCATE
- SQL DISTINCT
- SQL query optimization