'How to analyze the long running select query

I have a select query that has a subquery (select),

SELECT 
    count(*) AS count_1
FROM (SELECT 
          test.pg_status AS test_pg_status, test.errorcode AS test_errorcode, test.errordetails AS 
          test_errordetails, test.warningcode AS test_warningcode 
       FROM test
       WHERE '304ab306-16fe-4d12-affd-82c79c3bea4a'::uuid = test.sn_uuid) AS anon_1

This query is taking around 6 minutes to execute from my django app (not always, randomly), but when I execute this query from my psql command prompt, it is getting completed in 0.3 second.

Could someone help me to analyze the problem?

Note: I have an index created on sn_uuid, size of the test table data is 4GB and index data size is 21GB



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source