Posts

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

PostgreSQL Views and Materialized Views: Practical SQL Guide

Views and materialized views help organize complex SQL queries and simplify data access. They are useful for reporting, analytics, reusable query logic, and database applications. What Is a View? A view is a named SQL query that can be queried like a table. A regular view stores the query definition rather than maintaining a separate stored copy of its result rows. 1. Create a View Suppose you have an employees table with employee names, departments, and salaries. CREATE VIEW employee_details AS SELECT employee_id, employee_name, department, salary FROM employees; You can now query the view: SELECT * FROM employee_details; This returns the rows produced by the view's underlying query. 2. Create a View with a WHERE Condition You can create a view that returns only employees earning more than 50000. CREATE VIEW high_salary_employees AS SELECT employee_name, department, salary FROM employees WHERE salary > 50000; Query the view: SELECT * F...

PostgreSQL Transactions Explained: BEGIN, COMMIT and ROLLBACK

Transactions help PostgreSQL execute a group of database operations as a single logical unit. They are essential when multiple changes must succeed together to keep data consistent. What Is a Transaction? A transaction is a sequence of database operations treated as one unit of work. For example, transferring money between two bank accounts requires reducing one account's balance and increasing another's balance. Both changes should succeed together. 1. BEGIN a Transaction Use BEGIN to start a transaction explicitly. BEGIN; UPDATE accounts SET balance = balance - 1000 WHERE account_id = 1; UPDATE accounts SET balance = balance + 1000 WHERE account_id = 2; COMMIT; This example assumes an accounts table with account_id and balance columns. The transaction transfers 1000 from account 1 to account 2. Both updates are committed together if the transaction succeeds. In a real banking system, additional checks are needed to confirm that the sender has sufficient funds ...

PostgreSQL Constraints Explained: PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK and NOT NULL

  PostgreSQL constraints enforce rules on table data. They help maintain data accuracy, prevent invalid records, and preserve relationships between tables. What Are Constraints? A constraint is a rule applied to a table or column. PostgreSQL checks the rule when data is inserted or updated. 1. NOT NULL Constraint NOT NULL prevents a column from storing NULL values. CREATE TABLE employees ( employee_id INT, employee_name VARCHAR(100) NOT NULL, department VARCHAR(50) ); The employee name must be provided for every inserted row. 2. PRIMARY KEY Constraint A primary key uniquely identifies each row. It cannot contain duplicate or NULL values. CREATE TABLE departments ( department_id INT PRIMARY KEY, department_name VARCHAR(100) NOT NULL ); Each department must have a unique department_id . 3. UNIQUE Constraint A UNIQUE constraint prevents duplicate values in a column or combination of columns. CREATE TABLE users ( user_id INT PRIMARY KEY, emai...

PostgreSQL Indexes Explained: Improve SQL Query Performance

  Indexes in PostgreSQL help the database find rows more efficiently without scanning an entire table in many cases. They are especially useful when working with large datasets and frequently queried columns. What Is an Index? An index is a database structure that helps PostgreSQL locate rows based on indexed column values. Without a suitable index, PostgreSQL may need to scan many rows to find matching records. With an appropriate index, it may be able to locate matching rows more efficiently. Indexes are not always beneficial. They consume storage and can slow down inserts, updates, and deletes because the index may also need to be maintained. 1. Create a Table CREATE TABLE employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(100), department VARCHAR(50), salary NUMERIC(10, 2) ); A primary key automatically creates a unique index to enforce uniqueness. 2. Create an Index Suppose queries frequently search employees by department. CREATE INDEX i...

PostgreSQL String Functions: Practical SQL Guide for Beginners

PostgreSQL string functions help you clean text, search for specific patterns, combine values, and transform data for reporting. They are useful for data analysts, SQL developers, and database administrators. Sample Table Assume an employees table contains these records. employee_id employee_name department 1 Rahul Naidu IT 2 Priya Sharma HR 3 Arjun Kumar Finance 1. UPPER() and LOWER() UPPER() converts text to uppercase, while LOWER() converts text to lowercase. SELECT employee_name, UPPER(employee_name) AS uppercase_name, LOWER(employee_name) AS lowercase_name FROM employees; These functions are useful for standardizing text. 2. LENGTH() LENGTH() returns the number of bytes in a string. For ordinary ASCII text, this matches the character count. SELECT employee_name, LENGTH(employee_name) AS name_length FROM employees; For counting characters in multibyte text, use CHAR_LENGTH() . 3. CONCAT() CONCAT() combines multiple val...

PostgreSQL Date and Time Functions: Practical SQL Guide

Date and time functions are essential in PostgreSQL for analyzing daily sales, monthly revenue, customer activity, employee attendance, and business trends. In this tutorial, you will learn how to extract dates, calculate date differences, group data by month, and filter records using practical SQL examples. 1. Understanding Date and Timestamp Data Types PostgreSQL supports several date and time data types. Data Type Description Example DATE Stores a calendar date 2026-10-28 TIME Stores a time of day 14:30:00 TIMESTAMP Stores date and time without a time zone 2026-10-28 14:30:00 TIMESTAMPTZ Stores a time-zone-aware instant 2026-10-28 14:30:00+05:30 Use DATE for dates such as order dates and TIMESTAMPTZ when the time zone matters, such as recording events across different regions. 2. Get the Current Date and Time PostgreSQL provides functions for retrieving the current date and time. SELECT CURRENT_DATE; Returns the current date according to the...