title: How to write a raw SQL query in Django QuerySet?
body: <p>I want to use following SQL query in Django but I was unable to use that after trying directly with raw SQL. The SQL works directly while executing on PostgreSQL query window but on Django did not work. </p>
  
  <p>The SQL is to find immediate lower value before a number 22522. I would like to use that in QuerySet format or in raw SQL. Added SQL query below-</p>
  
  <pre><code>SELECT id, name, zip 
  FROM region 
  WHERE zip &gt;= (SELECT max(zip) FROM region WHERE zip &lt; 22522) 
  AND zip &lt;= (SELECT min(zip) FROM region WHERE zip&gt;22522) 
  ORDER BY zip ASC LIMIT 1
  </code></pre>
  
  <p>Here is the code which I tried to use in raw query format. I saw, any other simple SQL query inside the <code>c.execute()</code> print result data correctly.</p>
  
  <pre><code>from django.db import connection
  
  with connection.cursor() as c:
      c.execute("SELECT id, name, zip FROM region WHERE zip&gt;=(SELECT max(zip) 
      FROM region WHERE zip&lt;22522) AND zip&lt;=(SELECT min(zip) FROM region 
      WHERE zip&gt;22522) ORDER BY zip ASC LIMIT 1")
  
      for row in c.fetchall():
          print(row[1])
  </code></pre>