in

System.Data.SQLite

An open source ADO.NET provider for the SQLite database engine

sub-optimal SQL generated for Skip(n)

Last post 10-17-2008 12:46 PM by peter77. 0 replies.
Page 1 of 1 (1 items)
Sort Posts: Previous Next
  • 10-17-2008 12:46 PM

    sub-optimal SQL generated for Skip(n)

    The Skip(n) method is not optimally transformed into SQL. Consider the following LINQ expression:

    (from e in _context.EMPLOYEE orderby e.NAME select e.NAME).Skip(9999).Take(99);

    This generates the following SQL:

    SELECT
    [Var_8_1].[NAME] AS [NAME]
    WHERE  NOT (EXISTS (SELECT [Var_8_3].[NAME] AS [NAME]
     FROM ( SELECT
      [Extent1].[NAME] AS [NAME]
      FROM [EMPLOYEE] AS [Extent1]
      ORDER BY [Extent1].[NAME] ASC LIMIT 9999
     )  AS [Var_8_3]
     WHERE ([Var_8_1].[NAME] = [Var_8_3].[NAME]) OR (([Var_8_1].[NAME] IS NULL) AND ([Var_8_3].[NAME] IS NULL))))
    ORDER BY [Var_8_1].[NAME] ASC LIMIT 99

    This is very slow if the employee table has a large number of recods, even if the NAME column is indexed. A much more optimal (and shorter) SQL would be:

    SELECT name FROM employee ORDER BY name ASC LIMIT 99 OFFSET 9999

    Of course this only works if the LINQ expression has a Take(m) clause specified besides Skin(n). If Take(m) is not specified you could work around by inserting a fake "LIMIT" clause, eg.:

    SELECT name FROM employee ORDER BY  name ASC LIMIT (SELECT count(*) FROM employee) OFFSET 9999

    or just a huge number in the LIMIT clause:

    SELECT name FROM employee ORDER BY  name ASC LIMIT 1000000000000000 OFFSET 9999

Page 1 of 1 (1 items)
Powered by Community Server (Commercial Edition), by Telligent Systems