Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/SQL/Given two dataframes (df1: id, name and df2: id, country, address, city, count), join them, filter for rows where country = 'Singapore', and pivot the output. Sort cities in descending order of population count

Given two dataframes (df1: id, name and df2: id, country, address, city, count), join them, filter for rows where country = 'Singapore', and pivot the output. Sort cities in descending order of population count

SQLmedium2 min read

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…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
487
questions in SQL
Difficulty Split
130E|271M|86H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
JP Morgan
Key Concepts Tested
join

Why This Question Matters

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.

How to Approach This

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.

Expert Answer
451 wordsIncludes code

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.

Mechanics & Why

  • Join: An 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.
  • Filter: Apply the filter country = 'Singapore' immediately after the join. This reduces the dataset size early, improving subsequent operation performance.
  • Sort Cities (Columns): The requirement "Sort cities in descending order of population count" implies ordering the columns of the pivoted output. This is a multi-step process:
  • * First, calculate the total 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.
  • Pivot: Group the filtered data by 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.
  • Key Trade-offs & Considerations

    * 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'))

    In the interview, also mention…

    Discuss potential data skew in the id column during the join or groupBy, and how to mitigate it (e.g., salting, repartitioning).

    ⚡
    Pro Tip

    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.'

    Want all answers as a PDF for offline study?
    Seven focused volumes with 750+ in-depth answers — Answer Vault →

    Related SQL Questions

    mediumWrite an SQL query to find the second-highest salary from an employee table.FreemediumDemonstrate the difference between DENSE_RANK() and RANK()FreemediumDiscuss differences between ROW_NUMBER(), RANK(), and DENSE_RANK(), and provide examples from your projects.FreemediumExplain the differences between Data Warehouse, Data Lake, and Delta LakeFreemediumExplain the differences between Repartition and Coalesce. When would you use each?Free

    Level up your prep

    Recommended
    Educative
    Educative Unlimited

    800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

    Start learning →

    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.

    ← Back to all questionsMore SQL questions →
    Categories
    All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
    By Company
    AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
    Interview Guides
    All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
    Products
    AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
    Company
    About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
    © 2026 DataEngPrep.tech. All rights reserved.
    AboutBlogContactDisclaimer