qb icon indicating copy to clipboard operation
qb copied to clipboard

perf improvement opportunity for `exists`

Open davidAtInleague opened this issue 4 months ago • 0 comments

exists current implementation is

public boolean function exists( struct options = {} ) {
    return count( options = arguments.options ) > 0;
}

Which produces sql like

SELECT COALESCE(COUNT(*), 0) AS "aggregate" FROM [table] WHERE <<clauses>>

But this forces a count operation, and then does an inequality comparison in application code. In MSSQL, and I imagine all other database engines, the database cannot optimize away the count to just a "check that some row exists".

I think that exists could do better to emit:

--MSSqlserver grammar, but I believe this is all standard sql features
select case when exists (
  select * from [table] where <<clauses>>
) then 1 else 0 end as [doesItExist]

and the CF implementation would be

public boolean function exists( struct options = {} ) {
    return <<run exists statement>>.doesItExist == 1
}

Which would allow the database engine to just check if a record exists or not.

In the query I am looking at now, the count version is typically ~100ms, and the exists version is ~50ms. This change will probably fluctuate based on available indexes and complexity of the where clause, but in general I contend that the exists version is more appropriate here.

davidAtInleague avatar Oct 08 '24 14:10 davidAtInleague