General rules for simplifying SQL statements

前端 未结 8 1530
心在旅途
心在旅途 2020-12-22 17:15

I\'m looking for some \"inference rules\" (similar to set operation rules or logic rules) which I can use to reduce a SQL query in complexity or size. Does there exist some

8条回答
  •  攒了一身酷
    2020-12-22 17:34

    My approach is to learn relational theory in general and relational algebra in particular. Then learn to spot the constructs used in SQL to implement operators from the relational algebra (e.g. universal quantification a.k.a. division) and calculus (e.g. existential quantification). The gotcha is that SQL has features not found in the relational model e.g. nulls, which are probably best refactored away anyhow. Recommended reading: SQL and Relational Theory: How to Write Accurate SQL Code By C. J. Date.

    In this vein, I'm not convinced "the fact that most SUBSELECTs can be rewritten as a JOIN" represents a simplification.

    Take this query for example:

    SELECT c 
      FROM T1 
     WHERE c NOT IN ( SELECT c FROM T2 );
    

    Rewrite using JOIN

    SELECT DISTINCT T1.c 
      FROM T1 NATURAL LEFT OUTER JOIN T2 
     WHERE T2.c IS NULL;
    

    The join is more verbose!

    Alternatively, recognize the construct is implementing an antijoin on the projection of c e.g. pseudo algrbra

    T1 { c } antijoin T2 { c }
    

    Simplification using relational operators:

    SELECT c FROM T1 EXCEPT SELECT c FROM T2;
    

提交回复
热议问题