I got two queries:
'UPDATE foo SET bar = baz WHERE a = b AND c = d'
and
'UPDATE foo SET bar = baz WHERE c = d AND a = b'
both are semantically equal (they do the same), but a simple compare would state that they are different as the first has a = b AND c = d whereas the second uses c = d AND a = b.
How can I check whether both queries are semantically equal?
This is an obviously easy example that can be solved by simple alphabetic sorting of the syntax tree at the WHERE node. I am interested in a generic approach that can also solve more complex queries - even with subqueries.
A further restriction is that I do not have access to the database and can only use the strings of the queries. Thus RUNNING the queries is out of question as it would NOT reflect on the equality of the queries.
An example for the bold text above:
FooTable:
A | B | C
1 | xx | xx
2 | yy | zz
FooTable': (FooTable' is FooTable on a different database)
A | B | C
1 | xx | xx
2 | ee | zz
3 | ss | xx
Example why running the queries will NOT yield valid results:
1) Queries on the same database:
UPDATE FooTable SET B = 'rr' WHERE C = 'xx'
AND
UPDATE FooTable SET B = 'rr' WHERE C = 'xx' OR B = 'ss'
Both queries will RESULT in exactly the same but are trivially not equal.
2) Queries when including different databases (same schema but different data):
SELECT A,B,C FROM FooTable where C = 'xx'
AND
SELECT A,B,C FROM FooTable' where C = 'xx'
Those two queries are trivially semantically equal but will NOT yield the same results.
IN:select * from core.[Group] where Id IN(select groupId from core.GroupPermission)should be equal to this one usingEXISTS:select * from core.[Group] where exists (select null from core.GroupPermission where core.GroupPermission.GroupId = core.[Group].Id)?t. Consider a synonym,s, that is applied tot(or, if your database system doesn't support synonyms, a viewvwhich selects all columns fromtand applies no filters). There is no way to determine just by inspecting two queries, where one referencestand the other referencess(orv) that they are identical.