Query optimization helps your database find answers faster. It saves time and computer power.
Common query optimization patterns in PostgreSQL
Start learning this pattern below
Jump into concepts and practice - no test required
-- Example pattern: Use indexes CREATE INDEX index_name ON table_name(column_name); -- Example pattern: Use EXPLAIN to check query plan EXPLAIN SELECT * FROM table_name WHERE column_name = 'value';
Indexes help the database find rows quickly, like an index in a book.
EXPLAIN shows how the database plans to run your query, helping you spot slow parts.
CREATE INDEX idx_users_email ON users(email);
EXPLAIN SELECT * FROM users WHERE email = 'alice@example.com';
SELECT id, name FROM users WHERE active = true;
SELECT * FROM orders WHERE order_date >= '2024-01-01' AND order_date < '2024-02-01';
This example creates a products table, adds some data, creates an index on the category column, and then runs a query filtered by category. EXPLAIN ANALYZE shows how the index helps speed up the query.
CREATE TABLE products ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, category TEXT NOT NULL, price NUMERIC NOT NULL ); INSERT INTO products (name, category, price) VALUES ('Pen', 'Stationery', 1.20), ('Notebook', 'Stationery', 2.50), ('Coffee Mug', 'Kitchen', 5.00), ('Desk Lamp', 'Electronics', 15.00); -- Create index on category CREATE INDEX idx_products_category ON products(category); -- Query using the index EXPLAIN ANALYZE SELECT * FROM products WHERE category = 'Stationery';
Indexes speed up searches but slow down inserts and updates, so use them wisely.
Always test your queries with EXPLAIN or EXPLAIN ANALYZE to see if your changes help.
Selecting only needed columns reduces data size and speeds up queries.
Use indexes to help the database find data faster.
Check query plans with EXPLAIN to understand performance.
Write queries that only get the data you need.
Practice
Solution
Step 1: Understand what an index does
An index helps the database find rows faster by creating a quick lookup structure.Step 2: Match the purpose to the options
Only speeding up searches matches the purpose of an index; other options are unrelated.Final Answer:
To speed up searches on that column -> Option AQuick Check:
Index = Speed up search [OK]
- Thinking indexes reduce database size
- Confusing indexes with backups
- Assuming indexes encrypt data
Solution
Step 1: Recall the command to view query plans
PostgreSQL uses EXPLAIN to show how it will run a query.Step 2: Compare options to the correct command
Only EXPLAIN SELECT * FROM users; is valid syntax for query plans.Final Answer:
EXPLAIN SELECT * FROM users; -> Option AQuick Check:
EXPLAIN = Query plan check [OK]
- Using SHOW PLAN which is invalid
- Trying PLAN or DESCRIBE which are not PostgreSQL commands
- Missing the EXPLAIN keyword
SELECT id, name FROM employees WHERE department = 'Sales';Which optimization pattern does this query follow?
Solution
Step 1: Analyze the SELECT clause
The query selects only 'id' and 'name', not all columns with '*'.Step 2: Identify the optimization pattern
Selecting only needed columns reduces data transfer and improves speed.Final Answer:
Selecting only needed columns instead of * -> Option DQuick Check:
Selective columns = Better performance [OK]
- Confusing JOIN usage with column selection
- Thinking ORDER BY is always an optimization
- Assuming subqueries are used here
SELECT * FROM orders WHERE order_date = '2023-01-01';It runs slowly. Which fix will likely improve performance?
Solution
Step 1: Identify the cause of slowness
Query filters on order_date but may scan all rows without an index.Step 2: Apply optimization by indexing
Adding an index on order_date lets PostgreSQL find matching rows faster.Final Answer:
Add an index on the order_date column -> Option BQuick Check:
Index on filter column = Faster query [OK]
- Removing WHERE loses filtering purpose
- Changing SELECT * to COUNT(*) changes result, not speed
- Using GROUP BY without aggregation is incorrect
Solution
Step 1: Identify key optimization needs
Joining large tables and filtering by date needs indexes on join and filter columns.Step 2: Use EXPLAIN to verify query plan
Checking the plan helps confirm indexes are used and query is efficient.Final Answer:
Create indexes on join columns and filter columns; use EXPLAIN to check plan -> Option CQuick Check:
Indexes + EXPLAIN = Best optimization [OK]
- Selecting all columns wastes resources
- Avoiding indexes slows queries
- Removing WHERE loses filtering benefits
