Posts

Showing posts with the label check constraint

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

Data Integrity

Image
Introduction This is a term referring to the accuracy, completeness, consistency and reliability of data throughout its lifecycle, from when it is entered, stored, processed until it is deleted. Data with Integrity is data that correctly reflects objective reality and is not distorted, biased or contaminated due to system errors, human errors or hacker destruction. In database management systems like PostgreSQL, Data Integrity acts like strict rules, preventing any behavior that intentionally or unintentionally makes data absurd. To ensure data is always clean and correct, PostgreSQL provides the following core constraints: Entity Integrity When creating a table with a primary key, using a Unique Constraint or Unique Index means that the values in this column must be unique Ensures that the system can always distinguish between different entities, there is no such thing as two completely identical data rows or an "anonymous" data row existing. If you do not use the above meth...