IQueryable vs IEnumerable in EF Core

With IQueryable, EF Core can send the filter and limit to SQL. After ToList, the same LINQ operators run in memory.

Time depends on query planSpace 10 rows vs all rows loadedCode C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

A DbSet is an IQueryable: Where and Take build an expression that EF Core can translate to SQL. ToListAsync sends that query to the database. Once ToListAsync has loaded rows into a List, later Where calls use LINQ to Objects and run in your process.

Code

IQueryable<Employee> query = db.Employees;
query = query.Where(e => e.Salary > 100_000);
query = query.Take(10);
var page = await query.ToListAsync();

var all = await db.Employees.ToListAsync();
var localPage = all
    .Where(e => e.Salary > 100_000)
    .Take(10)
    .ToList();
static void demo(EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
    Root<Employee> e = cq.from(Employee.class);
    cq.where(cb.gt(e.get("salary"), 100_000));
    TypedQuery<Employee> query = em.createQuery(cq).setMaxResults(10);
    List<Employee> page = query.getResultList();   // one SQL query with WHERE and LIMIT

    List<Employee> all = em.createQuery("SELECT e FROM Employee e", Employee.class).getResultList();
    List<Employee> localPage = all.stream()
        .filter(x -> x.salary > 100_000)
        .limit(10)
        .collect(Collectors.toList());
}
void demo(Database& db) {
    string sql = "SELECT * FROM Employees";
    sql += " WHERE Salary > 100000";
    sql += " LIMIT 10";
    vector<Employee> page = db.query(sql);   // the database filters and limits

    vector<Employee> all = db.query("SELECT * FROM Employees");
    vector<Employee> localPage;
    for (const auto& e : all) {
        if (e.salary > 100000) localPage.push_back(e);
        if (localPage.size() == 10) break;
    }
}
from itertools import islice

query = session.query(Employee)
query = query.filter(Employee.salary > 100_000)
query = query.limit(10)
page = query.all()  # one SQL query with WHERE and LIMIT

all_rows = session.query(Employee).all()
local_page = list(islice(
    (e for e in all_rows if e.salary > 100_000),
    10))

Tips

In the .NET library

Use IQueryable while composing an EF Core query, and materialise with ToListAsync when you need the results. Avoid materialising early unless you really need all rows.