Odoo : SQL Query Tips

In this article we will show some useful tips that will help you work with SQL Queries in python/Odoo.

How to execute queries in Odoo 10 ?

you should use the self.env.cr to run a sql query

cr = self.env.cr
cr.execute("SELECT a, b, c FROM [your_table] WHERE [condition]")
cr.fetchall()

It’s highly recommended to use the double quotes ” ” instead of single quotes ‘ ‘

What’s the query can returns ?

cr.dictfetchall() : will give you all the matching records in the form of the list of dictionary containing key, value [{'': ''}, {'': ''}, ...].
cr.dictfetchone : works same as cr.dictfetchall() except it returns only a single record {'': ''}.
cr.fetchall() : will give you all the matching records in the form of the list of tuple [(''), (''), ...].
cr.fetchone() : works same way as cr.fetchall() except it returns only single record ('').

SQL Queries with variables

You can execute Queries with variables using %s like:

cr.execute("SELECT a, b, c FROM [your_table] AS a WHERE a.id = %s AND a.field = %s", (first_value, second_value))

Hope it was useful for you
Good luck !!