Creating Indexes in PostgreSQL: Understanding CREATE TABLE and Separate Statements
- CREATE TABLE: This command defines the structure of a table, specifying columns, data types, and constraints like primary keys.
- Indexes: These are additional structures that improve query performance by allowing faster data retrieval based on specific columns.
There are two key points to remember:
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10,2) NOT NULL
);
In this example, defining id
as the primary key automatically creates an index on that column.
Creating a Separate Index:
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL
);
CREATE INDEX idx_customer_email ON customers (email);
This example creates a table with a primary key and a unique email constraint. Then, a separate CREATE INDEX
statement creates an index named idx_customer_email
on the email
column.
Specifying Sort Order and Handling NULL Values:
CREATE INDEX idx_products_name_desc ON products (name DESC NULLS LAST);
- Using CREATE TABLE with a FOREIGN KEY referencing an existing indexed table:
- This approach leverages existing indexes. Define a FOREIGN KEY constraint in your table that references a column in another table with an existing index.
- When querying your table using the foreign key column, the optimizer might utilize the existing index on the referenced table to speed up the search.
Example:
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
-- Assuming an index already exists on customers.customer_id
- Post-deployment Indexing based on Query Analysis:
- Analyze your application's query patterns after deployment. Tools like
EXPLAIN
andpg_stat_statements
can reveal frequently used WHERE clauses that might benefit from indexing. - Based on this analysis, create targeted indexes using separate
CREATE INDEX
statements.
Benefits:
- This method avoids unnecessary indexes that might not be used in practice.
- It tailors indexes to specific query patterns, potentially offering better performance gains.
- Using materialized views (advanced):
- Materialized views are pre-computed results of a complex query stored as a separate table.
- If your queries involve joins or aggregations, a materialized view with proper indexes can significantly improve performance.
postgresql