SQLAlchemy Core - SQL Expressions

In this chapter, we will briefly focus on the SQL Expressions and their functions.

SQL expressions are constructed using corresponding methods relative to target table object. For example, the INSERT statement is created by executing insert() method as follows −

ins = students.insert()

The result of above method is an insert object that can be verified by using str() function. The below code inserts details like student id, name, lastname.

'INSERT INTO students (id, name, lastname) VALUES (:id, :name, :lastname)'

It is possible to insert value in a specific field by values() method to insert object. The code for the same is given below −

>>> ins = users.insert().values(name = 'Karan')
>>> str(ins)
'INSERT INTO users (name) VALUES (:name)'

The SQL echoed on Python console doesn’t show the actual value (‘Karan’ in this case). Instead, SQLALchemy generates a bind parameter which is visible in compiled form of the statement.

{'name': 'Karan'}

Similarly, methods like update(), delete() and select() create UPDATE, DELETE and SELECT expressions respectively. We shall learn about them in later chapters.