Reviewed by Aditya Kumar · Last reviewed 2026-08-08
To achieve this, first join df1 and df2 on id , then filter for country = 'Singapore' . To sort cities by population count, pre calculate the total count for each city and use that order when pivoting…
This medium-level SQL question appears frequently in data engineering interviews at companies like JP Morgan. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (join) will help you answer variations of this question confidently.
Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.
To achieve this, first join df1 and df2 on id, then filter for country = 'Singapore'. To sort cities by population count, pre-calculate the total count for each city and use that order when pivoting the data by city, aggregating the count for each id and name.
inner join on the common id column combines the dataframes. If df1 is significantly smaller than df2 (e.g., fits in memory on each Spark executor), consider a broadcast join to avoid a costly shuffle for df1.country = 'Singapore' immediately after the join. This reduces the dataset size early, improving subsequent operation performance.count for each city within 'Singapore'.
* Collect these cities in descending order of their total count.
* Pass this ordered list of cities to the pivot function to ensure the columns appear in the desired sequence.
id and name, then pivot on the city column using the pre-determined ordered list of cities. Aggregate the count using first('count'), assuming (id, name, city) uniquely identifies a single count after the initial join and filter.* Pivot Cardinality: Be mindful of the number of unique cities. Pivoting creates a new column for each unique city. If there are too many cities, the resulting dataframe can become excessively wide, leading to performance issues and memory pressure. Alternatives like collect_list or map_from_entries might be better if the number of cities is very high.
* Spark Shuffle: The join and groupBy operations are wide transformations that can trigger a Spark shuffle, moving data across network. Optimizing partition sizes and avoiding data skew are crucial for performance.
Sorting: The existing answer's .orderBy(col('count').desc()) would sort the rows of the intermediate, unpivoted data. For sorting the columns* of the final pivoted output, the pre-calculation method shown below is necessary.
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, first, sum, desc
# Assuming spark session and df1, df2 are defined
# 1. Pre-calculate total count per city to determine column order
city_order_df = df2.filter(col('country') == 'Singapore') \
.groupBy('city').agg(sum('count').alias('total_count')) \
.orderBy(desc('total_count'))
ordered_cities = [row.city for row in city_order_df.collect()]
# 2. Join, filter, and pivot using the determined city order
result_df = df1.join(df2, 'id') \
.filter(col('country') == 'Singapore') \
.groupBy('id', 'name') \
.pivot('city', ordered_cities) \
.agg(first('count'))
Discuss potential data skew in the id column during the join or groupBy, and how to mitigate it (e.g., salting, repartitioning).
Red Flag: Pivot on high-cardinality column without limit—schema explosion. Pro-Move: 'We filtered to top 20 cities by count before pivot to keep schema manageable; used melt for reverse transform.'
Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.
According to DataEngPrep.tech, this is one of the most frequently asked SQL interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.