Proving SQL query equivalency

后端 未结 9 2447
一整个雨季
一整个雨季 2020-12-15 05:33

How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.


As I had a specific query in

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 06:01

    CAREFUL! Functional "equivalence" is often based on the data, and you may "prove" equivalence of 2 queries by comparing results for many cases and still be wrong once the data changes in a certain way.

    For example:

    SQL> create table test_tabA
    (
    col1 number
    )
    
    Table created.
    
    SQL> create table test_tabB
    (
    col1 number
    )
    
    Table created.
    
    SQL> -- insert 1 row
    
    SQL> insert into test_tabA values (1)
    
    1 row created.
    
    SQL> commit
    
    Commit complete.
    
    SQL> -- Not exists query:
    
    SQL> select * from test_tabA a
    where not exists
    (select 'x' from test_tabB b
    where b.col1 = a.col1)
    
          COL1
    
    ----------
    
             1
    
    1 row selected.
    
    SQL> -- Not IN query:
    
    SQL> select * from test_tabA a
    where col1 not in
    (select col1
    from test_tabB b)
    
          COL1
    
    ----------
    
             1
    
    1 row selected.
    
    
    -- THEY MUST BE THE SAME!!! (or maybe not...)
    
    
    SQL> -- insert a NULL to test_tabB
    
    SQL> insert into test_tabB values (null)
    
    1 row created.
    
    SQL> commit
    
    Commit complete.
    
    SQL> -- Not exists query:
    
    SQL> select * from test_tabA a
    where not exists
    (select 'x' from test_tabB b
    where b.col1 = a.col1)
    
    
          COL1
    
    ----------
    
             1
    
    1 row selected.
    
    SQL> -- Not IN query:
    
    SQL> select * from test_tabA a
    where col1 not in
    (select col1
    from test_tabB b)
    
    **no rows selected.**
    

提交回复
热议问题