← Amazon Interview Insights

Amazon·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Jul 2026

Summary

Amazon BI Engineer interview with a SQL problem that looks straightforward but has a subtle twist if you haven't thought about unordered pairs before.

Questions Asked (1)

Q1

Given a flights table with departure and arrival city columns, write a SQL query that returns all unique city pairs treating (A, B) and (B, A) as the same route.

Algorithms & Data StructuresData Modeling
Author's notes

I knew roughly what they wanted but blanked on the exact syntax for LEAST/GREATEST for a second.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Normalize each route by ordering the city pair so that the smaller city comes first (e.g., using LEAST and GREATEST). Then select distinct normalized pairs. This ensures (A, B) and (B, A) are treated as the same route.

Pro tip: Mention that this approach is efficient because it avoids self-joins and works well with indexing. Also, clarify that the output should contain each unique route only once, regardless of direction.

1. Understand the problem

Recognize that the goal is to return unique undirected city pairs from directed flight data. Each row represents a directed flight, but we need to treat (A, B) and (B, A) as the same.

2. Normalize the pair

For each row, create a normalized pair where the first city is the lexicographically smaller one. Use functions like LEAST and GREATEST (or CASE WHEN) to achieve this.

3. Select distinct pairs

Apply DISTINCT to the normalized pairs to eliminate duplicates. This yields each unique route exactly once.

4. Write the SQL query

Combine the normalization and distinct selection into a single query. For example: SELECT DISTINCT LEAST(departure, arrival) AS city1, GREATEST(departure, arrival) AS city2 FROM flights;

5. Consider edge cases

Discuss handling of NULLs, case sensitivity, and whether the output should be ordered. Also, mention that if the table is large, indexing on the normalized columns could help.

Key Points to Mention

  • Use of LEAST and GREATEST functions for normalization
  • DISTINCT to remove duplicates
  • Avoiding self-joins for efficiency
  • Handling NULL values appropriately
  • Potential need for indexing on normalized columns
  • Clarifying output format (e.g., column names, ordering)

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.