dotnet / dotnet/efcore

Additional optimization suggestions for CASE

Open
#33,957 2 comments 1 reaction 0 assignees View on GitHub
area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Some generalizations/similar simplifications:

1. `CASE WHEN t1 THEN x WHEN t2 THEN x ... WHEN tn THEN x ELSE x END` → `x`
This should be safe even for impure `x` 🎉
3. `CASE WHEN boolExpr THEN TRUE ELSE FALSE END` → `boolExpr`
4. `CASE WHEN NOT (boolExpr) THEN x ELSE y END` → `CASE WHEN boolExpr THEN y ELSE x END`
5. `NOT (CASE WHEN nullOrBoolExpr THEN x ELSE y END)` → `CASE WHEN nullOrBoolExpr THEN NOT(x) ELSE NOT(y) END`
⚠️ it can improve or worsen the complexity of the query
6. `NOT (CASE WHEN nullOrBoolExpr THEN TRUE ELSE FALSE END)` → `CASE WHEN nullOrBoolExpr THEN FALSE ELSE TRUE END`
This is the query in the top comment and is relevant because it is emitted within EFCore; this specialization of the previous case always improves the query.
6. `NOT (COALESCE(nullOrBoolExpr, FALSE))` -> `COALESCE(NOT(nullOrBoolExpr), TRUE)`
is the `COALESCE` version of the previous rule. It does not improve the complexity of the query, but additional simplifications might be possible on `NOT(nullOrBoolExpr)`

_Originally posted by @ranma42 in https://github.com/dotnet/efcore/issues/33857#issuecomment-2143556508_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.