Executing a series of SQL queries in a WHERE clause

What is the extraction order in Query, for example:

SELECT * FROM [users] WHERE [userid] = 50001 AND [username] = 'new user' 

My question is what will be agreed upon for the first - [userid] or [username].

and it will affect runtime.

Any suggestion to improve this request will be announced.

+4
source share
3 answers

The answer depends on the indexes that you make available to the SQL engine. If userid indexed, but username not, perhaps the engine will start with userid ; if username indexed but userid not, then the engine will probably start with a name; if both fields are indexed, the engine will search for this index and search for rows by internal identifiers. Please note that all this is highly dependent on the DBMS used. Some engines refused to search the index as a whole in favor of a full table scan when the number of rows is small.

+6
source

The database will determine how the conditions are met.

Usually (but not always) he will use the index where possible.

You can see how it is necessary to optimize conditions in where or joins need to be optimized: - SQLStatementExecution - Example discussion1 - Example discussion2 - Example discussion3

Generally speaking, the order of criteria in a WHERE clause is evaluated and optimized by the query optimizer before creating an execution plan. It's good. However, I would recommend that you review the request execution plan for each request before putting it into operation.

+2
source

SQL database engines will usually be optimized based on clustering (the physical order of data records) and any available indexes. MySQL and MS SQL Server (at least many others too) are smart enough to know which order to execute filters to optimize the query.

For your purposes, it does not matter, and the results will be the same, with the same performance in any order.

+1
source

Source: https://habr.com/ru/post/1388699/


All Articles