Skip to the page
Tecyfy

Databricks interview question · hard

Darkseid wants to quickly visualize the distribution of a categorical variable within a large Delta table directly within a Databricks notebook. What are the most efficient ways to achieve this without resorting to external visualization libraries or downloading the data?

The short answerAggregate in Spark first, then chart the small result: group by the column and count, display() the result and add a bar chart from the + menu above it.

The full answer

Aggregate in Spark first, then chart the small result: group by the column and count, display() the result and add a bar chart from the + menu above it. Only the counts reach the browser, so the size of the table does not matter.

1. Group, count and chart

from pyspark.sql import functions as F

counts = (spark.read.table("main.sales.orders")
          .groupBy("status")
          .agg(F.count("*").alias("orders"))
          .orderBy(F.desc("orders")))
display(counts)

Or in a SQL cell:

SELECT status, count(*) AS orders
FROM main.sales.orders
GROUP BY status
ORDER BY orders DESC;

Above the result, choose + and then Visualization, pick Bar, put the column on the X axis and the count on the Y axis, and save. The chart stays with the cell and refreshes when the cell is run again.

2. Let the chart aggregate for you

You can also display() the raw column and set the bar chart's Y axis to Count. Databricks then aggregates over the whole dataset, not just the first 64,000 rows shown in the table. Grouping yourself is still clearer and lets you add a WHERE filter or a share column.

3. Data profile

From the same + menu, Data Profile gives summary statistics and a distribution for every column, including the most frequent values of categorical columns. It is the fastest first look at a new table.

4. Many categories

If the column has hundreds of distinct values, chart the top 20 and group the rest:

WITH c AS (SELECT status, count(*) AS n FROM main.sales.orders GROUP BY status)
SELECT CASE WHEN rank() OVER (ORDER BY n DESC) <= 20 THEN status ELSE 'Other' END AS status,
       sum(n) AS orders
FROM c GROUP BY 1 ORDER BY orders DESC;

5. Two categorical columns

Group by both columns and use a stacked bar chart or a heatmap, or use df.crosstab("col_a", "col_b") for a contingency table.

What to avoid: calling toPandas() on the full table or collecting it to the driver to plot. That moves every row to one machine, which is slow and can run out of memory.

Why this is efficient: the expensive part, scanning the table and counting, runs in parallel on the cluster or SQL warehouse, close to the data. What comes back is one row per category, a few kilobytes even for a table of billions of rows. If the counts are needed again, save them as a small summary table or a materialized view and chart that, rather than recounting the large table each time someone opens the notebook.

Last updated 16 October 2026

Asked next