Bird
Raised Fist0
PostgreSQLquery~10 mins

Common query optimization patterns in PostgreSQL - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to select only distinct customer IDs from the orders table.

PostgreSQL
SELECT [1] customer_id FROM orders;
Drag options to blanks, or click blank then click option'
AGROUP BY
BALL
CDISTINCT
DUNIQUE
Attempts:
3 left
💡 Hint
Common Mistakes
Using GROUP BY without aggregation can be confusing here.
Using UNIQUE is not valid SQL syntax in PostgreSQL.
2fill in blank
medium

Complete the code to create an index on the email column of the users table to speed up searches.

PostgreSQL
CREATE INDEX [1] ON users(email);
Drag options to blanks, or click blank then click option'
Aidx_email
Bemail_index
Cindex_email
Dusers_email
Attempts:
3 left
💡 Hint
Common Mistakes
Using reserved words as index names.
Using spaces or special characters in the index name.
3fill in blank
hard

Fix the error in the query that tries to filter orders with total greater than 100 but uses the wrong clause.

PostgreSQL
SELECT * FROM orders [1] total > 100;
Drag options to blanks, or click blank then click option'
AORDER BY
BHAVING
CGROUP BY
DWHERE
Attempts:
3 left
💡 Hint
Common Mistakes
Using HAVING without GROUP BY causes errors.
Using ORDER BY or GROUP BY instead of WHERE for filtering.
4fill in blank
hard

Fill both blanks to write a query that uses a CTE to get top 5 products by sales and then selects their names.

PostgreSQL
WITH top_products AS (SELECT product_id, SUM(sales) [1] sales_total FROM sales_data GROUP BY product_id ORDER BY sales_total DESC [2] 5) SELECT product_name FROM products WHERE product_id IN (SELECT product_id FROM top_products);
Drag options to blanks, or click blank then click option'
AAS
BBY
CLIMIT
DDESC
Attempts:
3 left
💡 Hint
Common Mistakes
Using BY instead of AS for aliasing.
Using DESC instead of LIMIT to restrict rows.
5fill in blank
hard

Fill all three blanks to write a query that aggregates total sales per region, filters regions with sales over 10000, and orders results descending.

PostgreSQL
SELECT region, SUM(sales) [1] total_sales FROM sales GROUP BY [2] HAVING total_sales [3] 10000 ORDER BY total_sales DESC;
Drag options to blanks, or click blank then click option'
AAS
Bregion
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using WHERE instead of HAVING to filter aggregated data.
Using < instead of > in the HAVING clause.

Practice

(1/5)
1. Which of the following is the best reason to create an index on a column in PostgreSQL?
easy
A. To speed up searches on that column
B. To reduce the size of the database
C. To automatically backup the data
D. To encrypt the data in that column

Solution

  1. Step 1: Understand what an index does

    An index helps the database find rows faster by creating a quick lookup structure.
  2. Step 2: Match the purpose to the options

    Only speeding up searches matches the purpose of an index; other options are unrelated.
  3. Final Answer:

    To speed up searches on that column -> Option A
  4. Quick Check:

    Index = Speed up search [OK]
Hint: Indexes speed up searches, not storage or encryption [OK]
Common Mistakes:
  • Thinking indexes reduce database size
  • Confusing indexes with backups
  • Assuming indexes encrypt data
2. Which of the following is the correct syntax to check the query plan in PostgreSQL?
easy
A. EXPLAIN SELECT * FROM users;
B. DESCRIBE SELECT * FROM users;
C. PLAN SELECT * FROM users;
D. SHOW PLAN SELECT * FROM users;

Solution

  1. Step 1: Recall the command to view query plans

    PostgreSQL uses EXPLAIN to show how it will run a query.
  2. Step 2: Compare options to the correct command

    Only EXPLAIN SELECT * FROM users; is valid syntax for query plans.
  3. Final Answer:

    EXPLAIN SELECT * FROM users; -> Option A
  4. Quick Check:

    EXPLAIN = Query plan check [OK]
Hint: Use EXPLAIN before your query to see the plan [OK]
Common Mistakes:
  • Using SHOW PLAN which is invalid
  • Trying PLAN or DESCRIBE which are not PostgreSQL commands
  • Missing the EXPLAIN keyword
3. Consider the query:
SELECT id, name FROM employees WHERE department = 'Sales';
Which optimization pattern does this query follow?
medium
A. Using a JOIN to combine tables
B. Using ORDER BY to sort results
C. Using a subquery to filter data
D. Selecting only needed columns instead of *

Solution

  1. Step 1: Analyze the SELECT clause

    The query selects only 'id' and 'name', not all columns with '*'.
  2. Step 2: Identify the optimization pattern

    Selecting only needed columns reduces data transfer and improves speed.
  3. Final Answer:

    Selecting only needed columns instead of * -> Option D
  4. Quick Check:

    Selective columns = Better performance [OK]
Hint: Avoid SELECT *; pick only columns you need [OK]
Common Mistakes:
  • Confusing JOIN usage with column selection
  • Thinking ORDER BY is always an optimization
  • Assuming subqueries are used here
4. You have this query:
SELECT * FROM orders WHERE order_date = '2023-01-01';
It runs slowly. Which fix will likely improve performance?
medium
A. Change SELECT * to SELECT COUNT(*)
B. Add an index on the order_date column
C. Remove the WHERE clause
D. Use GROUP BY order_date

Solution

  1. Step 1: Identify the cause of slowness

    Query filters on order_date but may scan all rows without an index.
  2. Step 2: Apply optimization by indexing

    Adding an index on order_date lets PostgreSQL find matching rows faster.
  3. Final Answer:

    Add an index on the order_date column -> Option B
  4. Quick Check:

    Index on filter column = Faster query [OK]
Hint: Index columns used in WHERE for faster filtering [OK]
Common Mistakes:
  • Removing WHERE loses filtering purpose
  • Changing SELECT * to COUNT(*) changes result, not speed
  • Using GROUP BY without aggregation is incorrect
5. You want to optimize a query that joins two large tables on a column and filters by a date range. Which combination of patterns will best improve performance?
hard
A. Use subqueries instead of JOINs; do not filter by date
B. Select all columns with *; avoid indexes to save space
C. Create indexes on join columns and filter columns; use EXPLAIN to check plan
D. Add ORDER BY on join column; remove WHERE clause

Solution

  1. Step 1: Identify key optimization needs

    Joining large tables and filtering by date needs indexes on join and filter columns.
  2. Step 2: Use EXPLAIN to verify query plan

    Checking the plan helps confirm indexes are used and query is efficient.
  3. Final Answer:

    Create indexes on join columns and filter columns; use EXPLAIN to check plan -> Option C
  4. Quick Check:

    Indexes + EXPLAIN = Best optimization [OK]
Hint: Index join and filter columns; verify with EXPLAIN [OK]
Common Mistakes:
  • Selecting all columns wastes resources
  • Avoiding indexes slows queries
  • Removing WHERE loses filtering benefits