The alias in SQL corresponds to a “renamed” model of a desk or SELECT statement, which takes place every time you assert “SELECT * FROM table1 AS a”. The AS creates a new call for the desk. Aliases permit any table or subquery to be referenced with the aid of a unique call.
In case of a desk, this permits the identical desk to be named within the FROM clause multiple instances. It presents a determine call for the columns represented by way of the assertion, allowing them to be referenced relative to this call.
In SQLAlchemy, any Table, pick() assemble, or different selectable object may be became an alias the use of the From Clause.Alias() method, which produces an Alias construct. The alias() characteristic in sqlalchemy.Sq. Module represents an alias, as typically carried out to any table or sub-pick out inside a SQL assertion the usage of the AS keyword.
from sqlalchemy.sql import alias st = students.alias("a")
This alias can now be utilized in pick() assemble to consult students table −
s = select([st]).where(st.c.id>2)
This translates to SQL expression as follows −
SELECT a.id, a.name, a.lastname FROM students AS a WHERE a.id > 2
We can now execute this SQL query with the execute() method of connection item. The complete code is as follows −
from sqlalchemy.sql import alias, select st = students.alias("a") s = select([st]).where(st.c.id > 2) conn.execute(s).fetchall()
When above line of code is executed, it generates the subsequent output −
[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar'), (5, 'Priya', 'Rajhans')]