w3resource

Confirm Effective Index Usage in Query Execution


PostgreSQL: Verifying Index Usage with EXPLAIN

Write a PostgreSQL query to use EXPLAIN to verify that an index is utilized in a query filtering on an indexed column.

Solution:

-- Specify the action to check the query execution plan.
EXPLAIN  
-- Define the query to retrieve all columns from the Users table.
SELECT * FROM Users  
-- Add a condition to filter rows where the email matches the specified value.
WHERE email = '[email protected]'; 

Explanation:

  • Purpose of the Query:
    • To confirm that the query planner is using the appropriate index for efficient lookups.
    • Ensures that the database leverages indexing to speed up searches.
  • Key Components:
    • WHERE email = '[email protected]' : The condition that should trigger index usage.
    • EXPLAIN : Outputs the execution plan to inspect index scans.
  • Real-World Application:
    • Vital for troubleshooting slow queries and verifying that indexes are effective.

Notes:

  • Review the plan output for terms like “Index Scan” to validate index usage.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL query using EXPLAIN to verify that an index is used for filtering on the "username" column in the "Users" table.
  • Write a PostgreSQL query using EXPLAIN to ensure an index is utilized in a JOIN between "Orders" and "Customers" on the foreign key column.
  • Write a PostgreSQL query using EXPLAIN to check if an index scan is used for a query filtering on the "email" column in the "Contacts" table.
  • Write a PostgreSQL query using EXPLAIN to confirm that a composite index is used for a query filtering on multiple columns in the "Transactions" table.


Go to:


PREV : Estimating Query Costs with EXPLAIN in PostgreSQL.
NEXT : Analyzing UPDATE Performance with EXPLAIN ANALYZE.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.