Skip to main content

Duckdb group by with null

data analysis
Author

Joram Mutenge

Published

2026-11-23

I sometimes use Excel, but only for one-off tasks. Whenever there’s a tool that allows me to analyze Excel data outside a spreadsheet, I prefer to use it. This helps me avoid the ever-so-common copy-paste errors. In this article, I’ll analyze some Excel data using DuckDB. Specifically, I’ll perform GROUP BY operations involving null values. My goal is to address a SQL quirk that you’re likely to encounter.

The dataset

To demonstrate this problem, I’ll use a simple dataset containing 20 customers and their sales. It also includes the region where each customer is based and their internal account segment designation:

  • Platinum
  • Gold
  • Silver

DuckDB can be extended to read Excel files by installing the appropriate extensions. Since the Excel file is stored in a GitHub repository, I’ll need to install two extensions: httpfs and excel. Let’s install and load both.

I’ll start by installing the extension that allows me to query files hosted elsewhere on the internet.

INSTALL httpfs;
LOAD httpfs;

The second extension enables me to query Excel files.

INSTALL excel;
LOAD excel;

I’ll check whether both extensions are properly installed.

SELECT
    extension_name,
    loaded,
    installed
FROM duckdb_extensions()
WHERE extension_name IN ('httpfs', 'excel');
┌────────────────┬─────────┬───────────┐
│ extension_name │ loaded  │ installed │
│    varchar     │ boolean │  boolean  │
├────────────────┼─────────┼───────────┤
│ excel          │ true    │ true      │
│ httpfs         │ true    │ true      │
└────────────────┴─────────┴───────────┘

Now that I have the relevant extensions installed, I can read the data. I’ll create a temporary table called sales to store the data in DuckDB’s in-memory storage.

CREATE TEMP TABLE sales AS (
    SELECT *
    FROM read_xlsx(
        'https://github.com/chris1610/pbpython/raw/master/data/sales_9_2022.xlsx'
    )
);
Warning

Loading this data may take a little longer than usual. If you don’t see an error message, give it some time. It will eventually load. Mine took a little over five minutes. Loading the file doesn’t take nearly as long when it’s stored on your local drive.

Let’s query the entire sales table.

FROM sales;
┌─────────────┬────────────────────────────────┬─────────┬──────────┬──────────┐
│ Customer ID │         Customer Name          │ Region  │ Segment  │  Sales   │
│   double    │            varchar             │ varchar │ varchar  │  double  │
├─────────────┼────────────────────────────────┼─────────┼──────────┼──────────┤
│    740150.0 │ Barton LLC                     │ US      │ Gold     │ 215000.0 │
│    714466.0 │ Trantow-Barrows                │ EMEA    │ Silver   │ 430000.0 │
│    218895.0 │ Kulas Inc                      │ EMEA    │ Platinum │ 410000.0 │
│    307599.0 │ Kassulke, Ondricka and Metz    │ EMEA    │ NULL     │  91000.0 │
│    412290.0 │ Jerde-Hilpert                  │ EMEA    │ Gold     │ 630000.0 │
│    729833.0 │ Koepp Ltd                      │ US      │ NULL     │ 230000.0 │
│    737550.0 │ Fritsch, Russel and Anderson   │ US      │ Gold     │ 630000.0 │
│    146832.0 │ Kiehn-Spinka                   │ US      │ Silver   │ 615000.0 │
│    688981.0 │ Keeling LLC                    │ US      │ Platinum │ 515000.0 │
│    786968.0 │ Frami, Hills and Schmidt       │ US      │ Gold     │ 215000.0 │
│    239344.0 │ Stokes LLC                     │ US      │ Silver   │ 230000.0 │
│    672390.0 │ Kuhn-Gusikowski                │ APAC    │ Platinum │ 630000.0 │
│    141962.0 │ Herman LLC                     │ APAC    │ Gold     │ 215000.0 │
│    424914.0 │ White-Trantow                  │ US      │ NULL     │ 230000.0 │
│    527099.0 │ Sanford and Sons               │ US      │ Platinum │ 615000.0 │
│    642753.0 │ Pollich LLC                    │ US      │ Gold     │ 419000.0 │
│    383080.0 │ Will LLC                       │ US      │ Silver   │ 415000.0 │
│    257198.0 │ Cronin, Oberbrunner and Spenc… │ US      │ Platinum │ 425000.0 │
│    604255.0 │ Halvorson, Crona and Champlin  │ US      │ NULL     │ 430000.0 │
│    163416.0 │ Purdy-Kunde                    │ APAC    │ Silver   │ 410000.0 │
└─────────────┴────────────────────────────────┴─────────┴──────────┴──────────┘
  20 rows                                                            5 columns

Looking at the data types, I see that the dataset has only one numeric column, Sales. Let’s calculate the total sales.

SELECT
    SUM(Sales) AS Total_Sales
FROM sales;
┌────────────────┐
│  Total_Sales   │
│     double     │
├────────────────┤
│   8000000.0    │
│ (8.00 million) │
└────────────────┘

Grouping the data

I’ll now perform a simple GROUP BY operation to determine the total sales by region.

SELECT
    Region,
    SUM(Sales) AS Total_Sales
FROM Sales
GROUP BY ALL
ORDER BY ALL;
┌─────────┬─────────────┐
│ Region  │ Total_Sales │
│ varchar │   double    │
├─────────┼─────────────┤
│ APAC    │   1255000.0 │
│ EMEA    │   1561000.0 │
│ US      │   5184000.0 │
└─────────┴─────────────┘
Tip

GROUP BY ALL is DuckDB syntax that allows you to group by all non-aggregated columns in the SELECT statement without having to list them individually.

Let’s double-check the calculation by adding the totals for the three regions above. I’ll create a common table expression (CTE) using the query above and then sum the values in the Total_Sales column.

WITH region_sum AS (
    SELECT
        Region,
        SUM(Sales) AS Total_Sales
    FROM Sales
    GROUP BY ALL
    ORDER BY ALL
)

SELECT
    SUM(Total_Sales)
FROM region_sum;
┌──────────────────┐
│ sum(Total_Sales) │
│      double      │
├──────────────────┤
│    8000000.0     │
│  (8.00 million)  │
└──────────────────┘

The value is still 8 million, so the calculation checks out. I’ll now perform a more complicated GROUP BY operation involving two columns.

SELECT
    Region,
    Segment,
    SUM(Sales) AS Total_Sales
FROM sales
GROUP BY Region, Segment
ORDER BY Region, Segment;
┌─────────┬──────────┬─────────────┐
│ Region  │ Segment  │ Total_Sales │
│ varchar │ varchar  │   double    │
├─────────┼──────────┼─────────────┤
│ APAC    │ Gold     │    215000.0 │
│ APAC    │ Platinum │    630000.0 │
│ APAC    │ Silver   │    410000.0 │
│ EMEA    │ Gold     │    630000.0 │
│ EMEA    │ Platinum │    410000.0 │
│ EMEA    │ Silver   │    430000.0 │
│ EMEA    │ NULL     │     91000.0 │
│ US      │ Gold     │   1479000.0 │
│ US      │ Platinum │   1555000.0 │
│ US      │ Silver   │   1260000.0 │
│ US      │ NULL     │    890000.0 │
└─────────┴──────────┴─────────────┘
  11 rows                3 columns

Looking closely at the result set, I see that some rows have null values in the Segment column. Since null is not a valid segment designation, we may want to exclude these rows from the result set. By default, DuckDB includes null values in its GROUP BY operations. This is a mistake that many people make when working with grouped data.

Here’s a query that excludes rows with null values in the Segment column.

SELECT
    Region,
    Segment,
    SUM(Sales) AS Total_Sales
FROM sales
WHERE Segment IS NOT NULL
GROUP BY ALL
ORDER BY ALL;
┌─────────┬──────────┬─────────────┐
│ Region  │ Segment  │ Total_Sales │
│ varchar │ varchar  │   double    │
├─────────┼──────────┼─────────────┤
│ APAC    │ Gold     │    215000.0 │
│ APAC    │ Platinum │    630000.0 │
│ APAC    │ Silver   │    410000.0 │
│ EMEA    │ Gold     │    630000.0 │
│ EMEA    │ Platinum │    410000.0 │
│ EMEA    │ Silver   │    430000.0 │
│ US      │ Gold     │   1479000.0 │
│ US      │ Platinum │   1555000.0 │
│ US      │ Silver   │   1260000.0 │
└─────────┴──────────┴─────────────┘

Notice that the result set no longer contains null values in the Segment column. More importantly, the grand total of Total_Sales is no longer 8 million. Let me demonstrate this with another query. Again, I’ll create a CTE using the query above and then calculate the sum of Total_Sales.

WITH sales_by_segment AS (
    SELECT
        Region,
        Segment,
        SUM(Sales) AS Total_Sales
    FROM sales
    WHERE Segment IS NOT NULL
    GROUP BY ALL
    ORDER BY ALL
)

SELECT
    SUM(Total_Sales) AS Total_Sales
FROM sales_by_segment;
┌────────────────┐
│  Total_Sales   │
│     double     │
├────────────────┤
│   7019000.0    │
│ (7.02 million) │
└────────────────┘

The total is now lower because we’ve excluded the rows with null values in the Segment column. This gives us the total sales for customers with known segment designations. Let’s check which columns contain null values.

SELECT
    SUM("Customer ID" IS NULL) AS Customer_ID,
    SUM("Customer Name" IS NULL) AS Customer_Name,
    SUM(Region IS NULL) AS Region,
    SUM(Segment IS NULL) AS Segment,
    SUM(Sales IS NULL) AS Sales
FROM sales;
┌─────────────┬───────────────┬────────┬─────────┬────────┐
│ Customer_ID │ Customer_Name │ Region │ Segment │ Sales  │
│   int128    │    int128     │ int128 │ int128  │ int128 │
├─────────────┼───────────────┼────────┼─────────┼────────┤
│           0 │             0 │      0 │       4 │      0 │
└─────────────┴───────────────┴────────┴─────────┴────────┘

Only the Segment column contains null values, with four missing entries.

I can rewrite the query above in a much more concise way.

SELECT
    COUNT(*) - COUNT(COLUMNS(*))
FROM sales;
┌─────────────┬───────────────┬────────┬─────────┬────────┐
│ Customer_ID │ Customer_Name │ Region │ Segment │ Sales  │
│   int128    │    int128     │ int128 │ int128  │ int128 │
├─────────────┼───────────────┼────────┼─────────┼────────┤
│           0 │             0 │      0 │       4 │      0 │
└─────────────┴───────────────┴────────┴─────────┴────────┘

A good practice is to replace null values with an informative label such as “Unknown”. This makes it clear that even though a sales value exists, the corresponding segment designation is missing.

SELECT
    Region,
    COALESCE(Segment, 'Unknown') AS Segment,
    SUM(Sales) AS Total_Sales
FROM sales
GROUP BY ALL
ORDER BY ALL;
┌─────────┬──────────┬─────────────┐
│ Region  │ Segnment │ Total_Sales │
│ varchar │ varchar  │   double    │
├─────────┼──────────┼─────────────┤
│ APAC    │ Gold     │    215000.0 │
│ APAC    │ Platinum │    630000.0 │
│ APAC    │ Silver   │    410000.0 │
│ EMEA    │ Gold     │    630000.0 │
│ EMEA    │ Platinum │    410000.0 │
│ EMEA    │ Silver   │    430000.0 │
│ EMEA    │ Unknown  │     91000.0 │
│ US      │ Gold     │   1479000.0 │
│ US      │ Platinum │   1555000.0 │
│ US      │ Silver   │   1260000.0 │
│ US      │ Unknown  │    890000.0 │
└─────────┴──────────┴─────────────┘
  11 rows                3 columns

What to remember

Performing GROUP BY operations in DuckDB includes null values by default. If you don’t want nulls to be part of the aggregation, you must filter them out. Alternatively, you can replace them with an informative value such as "Unknown".

This is an important consideration when analyzing data. Many analysts overlook null values when grouping their data, which can lead to unexpected results and inaccurate reporting.