Question

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.

  1. Why am I seeing such a performance hit with the (seemingly) less complex query?
  2. 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.

Was it helpful?

Solution

It turns out that Navicat (the software I use to access and administrate my database) is running some extra code that allows in place editing of the data when running a simple SELECT * FROM [Table] statement. Below is the email I received from a support representative.


Dear [Navicat User],

Thanks for your email. Please note that in order to get column information and allow update data afterwards, Navicat will run extra SQL when the query is a simple SELECT query. Using UNION, Navicat not allows user update any data in the query result.

...

Sincerely,
Mayho Ho
Navicat Support Center

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top