The following two queries return the same information; however, the first takes 1.1 seconds to complete and the second takes 0.06 seconds.
This table has 198,810 records and "Contacts"."ReqID"
is indexed.
- Why am I seeing such a performance hit with the (seemingly) less complex query?
- Why would the UNION subquery speed up the process?
*Edit*
I have ran both queries in rapid succession and see no change in performance.
Query 1
SELECT
"Contacts"."ContactID",
"Contacts"."ReqID"
FROM
"Contacts"
WHERE
"Contacts"."ReqID" = 2426;
*EDIT*
EXPLAIN ANALYZE
Index Scan using "Contacts_ReqID_idx" on "Contacts" (cost=0.00..30.08 rows=11 width=78) (actual time=0.076..0.115 rows=14 loops=1)
Index Cond: ("ReqID" = 2426)
Total runtime: 0.159 ms
1.1 seconds to return 14 records.
Query 2
SELECT
"T1"."ContactID",
"T1"."ReqID"
FROM
(
SELECT
"Contacts"."ContactID",
"Contacts"."ReqID"
FROM
"Contacts"
WHERE
"Contacts"."ReqID" = 2426
UNION
SELECT
"Contacts"."ContactID",
"Contacts"."ReqID"
FROM
"Contacts"
WHERE
"Contacts"."ReqID" = 2426
) AS "T1"
ORDER BY
"ReqID"
*EDIT*
EXPLAIN ANALYZE
Sort (cost=61.74..61.80 rows=22 width=100) (actual time=0.313..0.329 rows=14 loops=1)
Sort Key: "Contacts"."ReqID"
Sort Method: quicksort Memory: 26kB
-> HashAggregate (cost=60.81..61.03 rows=22 width=78) (actual time=0.266..0.285 rows=14 loops=1)
-> Append (cost=0.00..60.37 rows=22 width=78) (actual time=0.063..0.201 rows=28 loops=1)
-> Index Scan using "Contacts_ReqID_idx" on "Contacts" (cost=0.00..30.08 rows=11 width=78) (actual time=0.059..0.106 rows=14 loops=1)
Index Cond: ("ReqID" = 2426)
-> Index Scan using "Contacts_ReqID_idx" on "Contacts" (cost=0.00..30.08 rows=11 width=78) (actual time=0.006..0.024 rows=14 loops=1)
Index Cond: ("ReqID" = 2426)
Total runtime: 0.410 ms
0.06 seconds to return 14 records.