title: Robust approach for building SQL queries programmatically
body: <p>I have to resort to raw SQL where the ORM is falling short (using Django 1.7). The problem is that most of the queries end up being 80-90% similar. I cannot figure out a robust &amp; secure way to build queries without violating re-usability.</p>
  
  <p>Is string concatenation the only way out, i.e. build parameter-less query strings using <code>if-else</code> conditions, then safely include the parameters using prepared statements (to avoid SQL injection). I want to follow a simple approach for templating SQL for my project instead of re-inventing a mini ORM.</p>
  
  <p>For example, consider this query:</p>
  
  <pre><code>SELECT id, name, team, rank_score
  FROM
    ( SELECT id, name, team
      ROW_NUMBER() OVER (PARTITION BY team
                         ORDER BY count_score DESC) AS rank_score
      FROM 
        (SELECT id, name, team
         COUNT(score) AS count_score
         FROM people
         INNER JOIN scores on (scores.people_id = people.id)
         GROUP BY id, name, team
        ) AS count_table
    ) AS rank_table
  WHERE rank_score &lt; 3
  </code></pre>
  
  <p>How can I:</p>
  
  <p>a) add optional <code>WHERE</code> constraint on <code>people</code> <strong>or</strong><br>
  b) change <code>INNER JOIN</code> to <code>LEFT OUTER</code> <strong>or</strong><br>
  c) change <code>COUNT</code> to <code>SUM</code> <strong>or</strong><br>
  d) completely skip the <code>OVER / PARTITION</code> clause?</p>