Posts

Showing posts with the label materialized view

Pivot in PostgreSQL

Image
Introduction Pivot (or Pivot Table / Crosstab) is a technique used to transform data from rows to columns. This technique is very popular in data analysis and reporting, helping group scattered data rows into an easy-to-read summary table. Example of initial data (Long format): | Year | Quarter | Revenue | | : --- | : ------ | : ------ | | 2023 | Q1 | 100 | | 2023 | Q2 | 150 | | 2024 | Q1 | 120 | | 2024 | Q2 | 180 | Data after Pivot (Wide format): | Year | Q1 | Q2 | | : --- | : --- | : --- | | 2023 | 100 | 150 | | 2024 | 120 | 180 | How to Implement Unlike SQL Server or Oracle (which have native PIVOT syntax), PostgreSQL does not have a direct PIVOT keyword. You can accomplish this using the following common approaches: Using conditional aggregate functions ( SUM + FILTER or CASE ) is the simplest method, requiring no additional extensions and optimizing performance well. Using the tablefunc extension and the crosstab() fun...

Aggregate Constraint

Image
Introduction In PostgreSQL (and standard SQL in general), Aggregate Constraint is not an officially supported syntax or keyword, but rather a concept referring to constraints based on aggregated data (Aggregate Constraint / Cross-row Constraint), which is a very common problem in data processing. In practice, PostgreSQL directly prohibits using Aggregate Functions such as SUM, COUNT, AVG, MAX, MIN inside a table's CHECK constraint. The reason is that a CHECK constraint is evaluated on individual rows upon insertion or modification, whereas aggregate functions compute values across sets of multiple rows. For example, you cannot use CHECK with SUM to create a constraint ensuring the total revenue percentage of categories does not exceed 100% . Postgres will throw an error regarding the use of aggregate functions within a CHECK Constraint . Alternative Solutions To enforce an aggregate constraint rule, you can apply the following solutions: Using Triggers This is the most commo...