Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer equality when comparing values #34164

Open
ranma42 opened this issue Jul 5, 2024 · 0 comments · May be fixed by #34166
Open

Prefer equality when comparing values #34164

ranma42 opened this issue Jul 5, 2024 · 0 comments · May be fixed by #34166

Comments

@ranma42
Copy link
Contributor

ranma42 commented Jul 5, 2024

Most databases can take advantage of indexes (and in some cases even auto-generate them) when queries perform equality comparisons (instead of inequality).

In some places EFCore already tries to lean towards equality

// use equality where possible
// !(a == true) -> a == false
// !(a == false) -> a == true
SqlBinaryExpression { OperatorType: ExpressionType.Equal, Right: SqlConstantExpression { Value: bool } } binary
=> Equal(binary.Left, Not(binary.Right)),
// !(true == a) -> false == a
// !(false == a) -> true == a
SqlBinaryExpression { OperatorType: ExpressionType.Equal, Left: SqlConstantExpression { Value: bool } } binary
=> Equal(Not(binary.Left), binary.Right),

In other places it disregards this and in fact can even replace equality comparisons with inequalities

// a == b <=> !a == !b -> a == b
// !a == b <=> a == !b -> a != b
// a != b <=> !a != !b -> a != b
// !a != b <=> a != !b -> a == b
nullable = false;
return sqlBinaryExpression.OperatorType == ExpressionType.Equal ^ leftNegated == rightNegated
? _sqlExpressionFactory.NotEqual(left, right)
: _sqlExpressionFactory.Equal(left, right);
// a == !b and !a == b in SQL evaluate the same as a != b
body = _sqlExpressionFactory.NotEqual(left, right);

It would be better to avoid converting equalities into inequalities and, when possible, convert inequalities into equalities.

@ranma42 ranma42 linked a pull request Jul 5, 2024 that will close this issue
@roji roji added this to the Backlog milestone Jul 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants