22

I have a 450GB database... with millions of records.

Here is an example query:

SELECT TOP 1 * FROM c WHERE c.type='water';

To speed up our queries, I thought about just taking the first one but we have noticed that the query still takes quite a while, despite the very first record in the database matching our constraints.

So, my question is, how does the SELECT TOP 1 really work? Does it:

A) Select ALL records and then return just the first (top) one where type='water'

B) Return the first record which is encountered where type='water'

pookie
  • 3,796
  • 6
  • 49
  • 105

3 Answers3

22

Try this line, noting the offset limit:

SELECT * FROM c WHERE c.type='water' OFFSET 0 LIMIT 1

For more information about the offset limit:
https://learn.microsoft.com/en-us/azure/cosmos-db/sql-query-offset-limit

Arjun Bhalodiya
  • 293
  • 2
  • 14
1

Assuming you aren't sorting your results (which you query isn't) then TOP 1 will return the first result as soon as it finds one. This should then end the query.

Jacobm001
  • 4,431
  • 4
  • 30
  • 51
  • Great, thanks, it makes sense that it takes the first record and then stops searching, but I was not convinced it was doing that. Thanks for your help. – pookie Jul 18 '17 at 16:17
  • Apparently, CosmosDB indexes everything by default. Since I've not touched any indexing policies, c.type _is_ indexed and therefore your second paragraph is not correct. I've unmarked it as the solution so if you can, please update your answer so that it can be considered again. Thanks! – pookie Jul 20 '17 at 10:00
1

Cosmos db Explorer doesn't work with the TOP Command, It's an existing issue. It works fine in SDK Call.

Check some Top command usage below

https://learn.microsoft.com/en-us/azure/cosmos-db/sql-query-subquery

Arpan Saini
  • 4,623
  • 1
  • 42
  • 50