SQL Interview Questions for Java Developers — 50 Q&A with Examples Interview Questions | JiQuest

add

#

SQL Interview Questions for Java Developers — 50 Q&A with Examples

JAVA INTERVIEW PREPARATION
SQL Interview Questions for Java Developers
50 SQL interview questions with working examples covering JOINs, ACID transactions, isolation levels, window functions, CTEs, JPQL, N+1 problem, and query optimisation techniques.
⏱ 18 min read 📝 50 Q&As 🎯 All Levels

SQL proficiency is expected in every Java backend role. Whether you use Hibernate, Spring Data JPA, or raw JDBC, you must understand relational database fundamentals, query optimisation, and transaction management.

⚡ Quick Reference
INNER JOINReturns rows matching in both tables
LEFT JOINAll rows from left + matching from right (NULL if no match)
WHERE vs HAVINGWHERE filters rows before grouping; HAVING filters groups after
ACIDAtomicity, Consistency, Isolation, Durability
N+1 Problem1 query for list + N queries for each item — fix with JOIN FETCH
IndexB-tree structure — use on columns in WHERE/JOIN/ORDER BY
SQL JOIN Types
A
B
INNER JOIN
(intersection)
LEFT JOIN — all A
RIGHT JOIN — all B
FULL OUTER — all rows
CROSS — cartesian product

1. What is the difference between WHERE and HAVING?

-- WHERE filters individual rows BEFORE grouping
SELECT department, COUNT(*) FROM employees
WHERE salary > 50000            -- filters rows first
GROUP BY department;

-- HAVING filters groups AFTER aggregation
SELECT department, AVG(salary) as avg_sal FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;   -- filters groups

2. What are ACID properties?

Atomicity — transaction is all-or-nothing. Either all statements commit or all are rolled back. Consistency — database moves from one valid state to another. Isolation — concurrent transactions don't see each other's uncommitted data. Durability — committed transactions survive system failures (written to disk/WAL).

3. Transaction Isolation Levels

Isolation LevelDirty ReadNon-RepeatablePhantom
READ UNCOMMITTED✕ Possible✕ Possible✕ Possible
READ COMMITTED✓ Safe✕ Possible✕ Possible
REPEATABLE READ✓ Safe✓ Safe✕ Possible
SERIALIZABLE✓ Safe✓ Safe✓ Safe

4. DELETE vs TRUNCATE vs DROP

FeatureDELETETRUNCATEDROP
WHERE clauseYesNoNo
RollbackYesNo (DDL)No (DDL)
SpeedSlow (row-by-row log)Fast (deallocate pages)Fastest
Table exists afterYesYesNo

5. What is the N+1 problem in JPA and how do you fix it?

// N+1 PROBLEM: 1 query to load orders + N queries for each order's items
List<Order> orders = orderRepo.findAll(); // 1 query
for (Order o : orders) {
    System.out.println(o.getItems().size()); // N lazy queries!
}

// FIX 1: JOIN FETCH in JPQL
@Query("SELECT o FROM Order o JOIN FETCH o.items")
List<Order> findAllWithItems();

// FIX 2: @EntityGraph
@EntityGraph(attributePaths = {"items"})
List<Order> findAll();

// FIX 3: Batch fetching (hibernate.default_batch_fetch_size=10)

6. Window Functions

-- Rank employees by salary within each department
SELECT name, department, salary,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank,
    SUM(salary) OVER (PARTITION BY department) AS dept_total
FROM employees;

-- Running total
SELECT order_date, amount,
    SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;

❓ Frequently Asked Questions

Q: What is a CTE and when do you use it?

A: A Common Table Expression (WITH clause) creates a named temporary result set for the duration of a query. Use for readability, recursive queries (org charts), and re-using sub-results without repeating subqueries.

Q: What is normalisation?

A: Normalisation eliminates data redundancy. 1NF: atomic values, no repeating groups. 2NF: no partial dependencies on composite key. 3NF: no transitive dependencies. Denormalise when read performance outweighs write consistency.

Q: When should you add an index?

A: Add indexes on columns frequently used in WHERE, JOIN ON, and ORDER BY. Avoid indexes on low-cardinality columns (boolean, gender) and on heavily-updated tables (write overhead). Use EXPLAIN to identify full table scans.

Q: JPQL vs Native SQL — when to use which?

A: Use JPQL for most queries (database-agnostic, works on entities). Use native SQL for database-specific functions, window functions, or performance-critical queries that JPQL can't express efficiently.

Q: What is an execution plan?

A: EXPLAIN (MySQL/Postgres) shows how the database executes a query — which indexes are used, estimated rows scanned, join types. Use it to identify slow queries and validate index usage.

No comments
Leave a Comment