PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - ROLLUP

In PostgreSQL, the ROLLUP operation is a type of grouping extension that allows users to produce subtotal rows by super-aggregating existing rows. ROLLUP is useful for generating reports that have subtotals in multi-dimensional data.

Essentially, the ROLLUP operation creates subtotals that roll up from the most detailed level to a grand total, following the list of grouping columns provided.

Syntax:

The syntax for using ROLLUP is:

SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
GROUP BY ROLLUP (column1, column2, ...);

Example:

Consider the following sales table:

yearmonthsales
2021Jan100
2021Feb200
2022Jan150
2022Feb250

If you want to get the total sales for each combination of year and month, as well as the total for each year and the overall total, you can use the ROLLUP function as follows:

SELECT year, month, SUM(sales) as total_sales
FROM sales
GROUP BY ROLLUP (year, month);

The result will be:

yearmonthtotal_sales
2021Jan100
2021Feb200
2021NULL300
2022Jan150
2022Feb250
2022NULL400
NULLNULL700

Here's how the result can be interpreted:

  1. Sales for each month in 2021.
  2. Total sales for the entire year of 2021 (where month is NULL).
  3. Sales for each month in 2022.
  4. Total sales for the entire year of 2022 (where month is NULL).
  5. Grand total sales for both years combined (where both year and month are NULL).

Notes:

  • The order of columns in the ROLLUP argument list is significant. The subtotals are generated in the order specified.
  • ROLLUP can be combined with other grouping sets, including CUBE and GROUPING SETS, but understanding the output requires a careful interpretation of how these operations interact.

In summary, ROLLUP in PostgreSQL is a handy tool for generating reports with multiple levels of aggregation, providing insights from detailed to high-level summaries.

  1. How to use ROLLUP in PostgreSQL: The ROLLUP operator in PostgreSQL is used for creating subtotals and grand totals in result sets when using the GROUP BY clause.

    SELECT column1, column2, SUM(value)
    FROM your_table
    GROUP BY ROLLUP(column1, column2);
    
  2. Aggregating data with ROLLUP in PostgreSQL:

    SELECT category, subcategory, SUM(sales)
    FROM sales_data
    GROUP BY ROLLUP(category, subcategory);
    
  3. Creating subtotals and grand totals with ROLLUP: The ROLLUP operator generates subtotals and grand totals for the specified grouping columns.

  4. GROUP BY and ROLLUP in PostgreSQL:

    SELECT department, employee, AVG(salary)
    FROM employee_data
    GROUP BY ROLLUP(department, employee);
    
  5. Nested ROLLUP expressions in PostgreSQL:

    SELECT region, country, city, SUM(revenue)
    FROM sales
    GROUP BY ROLLUP(region, (country, city));
    
  6. Handling NULL values with ROLLUP in PostgreSQL: ROLLUP generates NULL values for subtotals and grand totals. Handle NULLs using COALESCE or CASE statements.

  7. ROLLUP with ORDER BY in PostgreSQL:

    SELECT department, employee, AVG(salary)
    FROM employee_data
    GROUP BY ROLLUP(department, employee)
    ORDER BY department, employee;
    
  8. Using ROLLUP with aggregate functions in PostgreSQL:

    SELECT product, quarter, AVG(sales), SUM(profit)
    FROM sales_data
    GROUP BY ROLLUP(product, quarter);
    
  9. ROLLUP and window functions in PostgreSQL:

    SELECT department, employee, AVG(salary),
           AVG(salary) OVER (PARTITION BY department) AS avg_department_salary
    FROM employee_data
    GROUP BY ROLLUP(department, employee);
    
  10. Using ROLLUP with GROUPING SETS in PostgreSQL:

    SELECT category, subcategory, SUM(sales)
    FROM sales_data
    GROUP BY GROUPING SETS ((category, subcategory), (category), ());
    
  11. ROLLUP and CUBE in PostgreSQL:

    SELECT category, subcategory, SUM(sales)
    FROM sales_data
    GROUP BY CUBE(category, subcategory);
    
  12. Using ROLLUP with JOIN operations in PostgreSQL:

    SELECT e.employee_id, e.employee_name, d.department_name, SUM(s.sales)
    FROM employees e
    JOIN sales_data s ON e.employee_id = s.employee_id
    JOIN departments d ON e.department_id = d.department_id
    GROUP BY ROLLUP(e.employee_id, e.employee_name, d.department_name);
    
  13. Optimizing queries with ROLLUP in PostgreSQL: Use appropriate indexes on columns involved in the GROUP BY and ROLLUP operations for better performance.

  14. ROLLUP and filtering results in PostgreSQL: Apply filters in the WHERE clause before using ROLLUP to ensure the desired subsets of data are included.

  15. ROLLUP with CASE statements in PostgreSQL:

    SELECT department,
           CASE WHEN employee_type = 'Manager' THEN 'Managers' ELSE 'Employees' END AS employee_category,
           AVG(salary)
    FROM employee_data
    GROUP BY ROLLUP(department, employee_category);
    
  16. ROLLUP and HAVING clause in PostgreSQL:

    SELECT department, employee, AVG(salary)
    FROM employee_data
    GROUP BY ROLLUP(department, employee)
    HAVING AVG(salary) > 50000;