Do F# Query Expressions have same performance as Native SQL?

Viewed 96

F# Query expression examples I notice look as though they grab the entire contents of a table before doing a computation. This seems less efficient than native SQL. Or should the performance be the same.

// A query expression.
let query1 =
    query {
        for customer in db.Customers do
            select customer
    }
1 Answers

F# query expressions are quite smart. I don't exactly understand how they work besides that they use quotations (similar to System.Linq.Expressions) to convert code to SQL. ORMs have measurable overhead, raw queries would be faster, but they're able to produce optimised queries

Given these models and ef-core context

[<CLIMutable>] type Address = { Id: int; City: string; Country: string }
[<CLIMutable>] type Person = { Id: int; Name: string; Age: int; Address: Address }

type PeopleContext() =
    inherit DbContext()

    [<FSharp.Core.DefaultValue>]
    val mutable _people : DbSet<Person>

    member db.People
        with get () = db._people
        and set value = db._people <- value

    override _.OnConfiguring options =
        options.UseSqlite("Data source=db.db3") |> ignore

I've created this query

query {
    for person in ctx.People do
        where (person.Age > 21)
        select person.Address.City
        take 1
} |> Seq.toArray |> printfn "%A"

That got translated to this sql

SELECT "a"."City"
FROM (
    SELECT "p"."AddressId"
    FROM "People" AS "p"
    WHERE "p"."Age" > 21
    LIMIT @__p_0
) AS "t"
Related