I have a travel logs table with vehicle IDs and travel dates. I want to compare whether two different vehicles have traveled on the same day. How would you write a SQL query to find pairs of vehicles that share the same travel date?
💡 Model Answer
Use a self‑join on the travel_logs table, matching rows with the same travel_date but different vehicle_id values. To avoid duplicate pairs (e.g., 101‑102 and 102‑101), enforce an ordering condition such as vehicle_id1 < vehicle_id2. The query returns each unique pair once.
Example:
SELECT
a.travel_date,
a.vehicle_id AS vehicle_1,
b.vehicle_id AS vehicle_2
FROM travel_logs a
JOIN travel_logs b
ON a.travel_date = b.travel_date
AND a.vehicle_id < b.vehicle_id
ORDER BY a.travel_date, vehicle_1, vehicle_2;This produces a list of dates and the vehicle pairs that were on the same date. If you need to count how many days each pair shared, wrap the above in a subquery and group by the pair:
SELECT vehicle_1, vehicle_2, COUNT(*) AS shared_days
FROM (
SELECT a.travel_date, a.vehicle_id AS vehicle_1, b.vehicle_id AS vehicle_2
FROM travel_logs a
JOIN travel_logs b
ON a.travel_date = b.travel_date
AND a.vehicle_id < b.vehicle_id
) t
GROUP BY vehicle_1, vehicle_2
ORDER BY shared_days DESC;The approach runs in O(n log n) time due to the join, but for typical log sizes it is efficient.
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