简体   繁体   中英

Is there a better way to optimize this SQL query?

Assume my table has millions of records.

The following columns have indexes:

  • type
  • date
  • unique_id

Here is my query:

SELECT TOP (1000) T.TIME, T.TYPE, F.NAME,
B.NAME, T.MESSAGE
FROM MY_TABLE T
LEFT OUTER JOIN FOO F ON F.ID = T.FID
LEFT OUTER JOIN BAR B ON B.ID = T.BID
WHERE T.TYPE IN ('success', 'failure')
AND T.DATE BETWEEN 1592585183437 AND 1594232320525
AND T.UNIQUE_ID = "my unique ID"
ORDER BY T.DATE DESC

My question is am I causing myself any trouble with this query if I have tons of records in my table? Can this be optimized further?

My question is am I causing myself any trouble with this query if I have tons of records in my table?

Wrong question. As long as you are only asking for data you need, you NEED it. Any trouble means you STIL need it.

The query looks as good as it gets. I somehow doubt the TOP 10000 (that is a LOT of data unless you compress it somehow).

The question is more whether you have the proper indices. Without the proper indices. I would also not use strings like this for TYPE, but then the question is about the query, not possible failures in table design.

Check indices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM