PostgreSQL Constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK and NOT NULL – Practical SQL Guide
Constraints are rules applied to table columns to maintain data accuracy and consistency in a PostgreSQL database. They prevent invalid data from being inserted or updated and help maintain relationships between tables. In this tutorial, you will learn the most commonly used PostgreSQL constraints with practical SQL examples. What Are Constraints in PostgreSQL? Constraints define rules that table data must follow. For example: - An employee ID should be unique. - An employee name should not be NULL. - A salary should not be negative. - An order should reference an existing customer. PostgreSQL provides several constraints to enforce these rules. 1. NOT NULL Constraint The NOT NULL constraint ensures that a column cannot contain NULL values. Suppose you have an employees table. CREATE TABLE employees ( employee_id INT, employee_name VARCHAR(100) NOT NULL, department VARCHAR(50) ); In this example, employee_name cannot contain NULL values. Insert ...