Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy clause before Where clause - performance? [duplicate]

Tags:

c#

linq

I'm trying to understand if there are any performance hit in using an OrderBy clause before Where clause like so:

List<string> names = new List<string> { //... };

var ns = names.OrderBy(n => n).Where(n => n.Length == 5);

Or will the compiler rearrange instructions so the Where clause gets executed before OrderBy clause?

like image 939
Saravana Avatar asked May 25 '13 04:05

Saravana


People also ask

Does the order of a WHERE clause matter?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.

Can we use order by before WHERE clause in SQL?

The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query.

Does WHERE clause improve performance?

A where clause will generally increase the performance of the database. Generally, it is more expensive to return data and filter in the application. The database can optimize the query, using indexes and partitions. The database may be running in parallel, executing the query in parallel.

Does order by go before or after WHERE?

ORDER BY is always put at the very end of the query. Clauses like FROM , WHERE , GROUP BY , HAVING , etc. should be put before the ORDER BY keyword. To sort the output in ascending order, you may put the keyword ASC after the column name.


1 Answers

That really depends on the LINQ provider (the class that implements IQueryable<T>).

On Entity Framework and LINQ to SQL (and other database related LINQ providers), the query is converted to SQL statements, and then will run on the database engine. For example, this query:

var ns = names.OrderBy(n => n).Where(n => n.Length == 5);

when iterated over, will be converted to:

SELECT * FROM names WHERE LEN(name) == 5 ORDER BY name

no matter where you put the OrderBy clause.

So in this case, there is no performance hit. But when using LINQ to Objects (as in your example), the two variations have a lot of difference in performance. This answer form Jon Skeet covers this case pretty well.

like image 110
Mohammad Dehghan Avatar answered Oct 06 '22 12:10

Mohammad Dehghan