SQL Functions Interview Questions
3 questions with answers · SQL Interview Guide
Built-in SQL functions including COALESCE, CASE, CAST, string functions, date functions, and the difference between scalar and aggregate functions.
What is the SQL CASE statement used for? Explain with an example
The CASE statement is SQL's way of doing conditional logic inline within a query, similar to an if-else in application code. It lets you return different values based on conditions and is useful for bucketing data, transforming output labels, or handling NULLs dynamically. You can use either a simple CASE that compares one expression to multiple values, or a searched CASE that evaluates separate boolean conditions.
SELECT name, salary,
CASE
WHEN salary < 40000 THEN 'Entry Level'
WHEN salary BETWEEN 40000 AND 80000 THEN 'Mid Level'
WHEN salary > 80000 THEN 'Senior Level'
ELSE 'Unknown'
END AS salary_band
FROM employees;What is the STUFF function and how does it differ from the REPLACE function in SQL
STUFF inserts a string into another string by first deleting a specified number of characters at a given position, then inserting the new string there. REPLACE, on the other hand, searches for all occurrences of a substring and replaces every one of them throughout the entire string. The key difference is that STUFF works by position and length, giving you surgical control over where the change happens, while REPLACE works by pattern matching and replaces every match it finds.
-- STUFF: delete 3 chars starting at position 2, insert 'XYZ'
SELECT STUFF('ABCDEF', 2, 3, 'XYZ'); -- Result: AXYZEF
-- REPLACE: replaces every occurrence of 'o' with '0'
SELECT REPLACE('foo bar foo', 'foo', 'baz'); -- Result: baz bar bazWrite the Syntax for STUFF function in an SQL server
STUFF inserts a string into another string after deleting a specified number of characters from the start position. It takes four arguments: the original string, the starting position, the number of characters to delete, and the string to insert. A common use case is removing or replacing a substring within a larger string.
-- STUFF(original_string, start, length, replacement_string)
SELECT STUFF('Hello World', 6, 5, 'SQL Server');
-- Result: 'Hello SQL Server'
-- Starting at position 6, delete 5 chars ('World'), insert 'SQL Server'Knowing the answers is half the battle
The other half is explaining them clearly under pressure.
Try a free mock interviewarrow_forward