SQL Scenarios Questions
Advanced SQL query design and optimization scenarios, including complex joins, subqueries, window functions, common table expressions (CTEs), set operations, indexing strategies, explain plans, and performance considerations across relational databases.
MediumTechnical
36 practiced
Rewrite this correlated subquery into a join/aggregate in PostgreSQL for better performance:SELECT u.user_id FROM users u WHERE (SELECT COUNT(*) FROM purchases p WHERE p.user_id = u.user_id AND p.ts > now() - interval '30 days') > 5;Provide a performant rewrite using CTE or join and explain why the rewritten query can be faster with proper indexing.
MediumTechnical
36 practiced
Write a Snowflake MERGE statement that upserts features from a staging table staging_user_features(user_id, feature_a, feature_b, last_updated) into features.user_features(user_id PRIMARY KEY, feature_a, feature_b, last_updated). Update only when incoming last_updated is newer and set new rows accordingly. Show how you handle NULLs and use COALESCE or IS DISTINCT FROM to avoid unnecessary updates.
MediumTechnical
31 practiced
Given this query in PostgreSQL that filters events by user_id, event_type, and occurred_at range and joins to users:SELECT e.* FROM events e JOIN users u ON e.user_id = u.id WHERE e.event_type = 'click' AND e.occurred_at >= now() - interval '30 days' AND u.is_active = true;Recommend index(es) on events and users to make this fast at scale. Explain index column ordering for multi-column indexes and when a covering index or a partial index is preferable.
MediumTechnical
27 practiced
Describe and compare index types in PostgreSQL: B-tree, Hash, GIN, GiST, BRIN. For each type give an example ML/data workload where it is appropriate (e.g., GIN for JSONB arrays or full-text, BRIN for huge append-only time-series). Discuss update cost and index size trade-offs.
MediumTechnical
26 practiced
You receive features from three sources (web_events, purchase_history, third_party). Write a SQL pipeline (CTEs) that joins these sources and resolves conflicting values using precedence: web_events > purchase_history > third_party. Produce final features with provenance flags indicating the source used for each feature.
Unlock Full Question Bank
Get access to hundreds of SQL Scenarios interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.