Chrome Extension

Column name as alias name SQLAlchemy

We can show column names of a table with its alias name using the .label() method in SQLAlchemy.
employees = self.session.query(
      "emp_name") #we are using emp_name alias for column name
                EmployeeModel.department == 'finance'
Code faster with devsheet chrome extension and increase productivity as a programmer
search code from your favorite search engine instantly.
Install Now

We can select a column with its alias name using the .label() method in SQLAlchemy. Sometimes we got the requirements to show a function result or column name with a different name, you can use the .label() method there.

Below is an example of getting the sum of column values named score and we are showing it with its alias name total_score.

| Id | name     | score  |
| 1  | Math     | 10     |
| 2  | Physics  | 30     |
| 3  | Math     | 20     |
| 4  | Math     | 50     |

The SQLAlchemy query will be as below

result = db.session.query(
Was this helpful?
Open Code Manager We are hiring