Write a SQL query to find the latest successful transaction per Stella.
💡 Model Answer
To retrieve the most recent successful transaction for each Stella, you can use a window function or a correlated subquery. For example, with a window function: SELECT FROM (SELECT , ROW_NUMBER() OVER (PARTITION BY stella_id ORDER BY transaction_date DESC) AS rn FROM transactions WHERE status = 'successful') t WHERE rn = 1; This partitions the rows by stella_id, orders them by transaction_date descending, and assigns a row number. The outer query filters to the first row per partition, giving the latest successful transaction. Alternatively, a correlated subquery: SELECT t.* FROM transactions t WHERE t.status = 'successful' AND t.transaction_date = (SELECT MAX(transaction_date) FROM transactions WHERE stella_id = t.stella_id AND status = 'successful'); Both approaches run in O(n) time with proper indexes on stella_id and transaction_date. Indexing these columns ensures the database can quickly locate the relevant rows, and the window function approach is often more readable and efficient on modern RDBMS engines.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500