![]() |
VOOZH | about |
SQLAlchemy is a Python library used for working with relational databases. It provides an intuitive way to interact with databases and allows us to write database-independent code. In this article, we'll explore one of the powerful features of SQLAlchemy called label(), which is used to add labels to queries and retrieve data in a more convenient way.
A label in SQLAlchemy is a means to give a result column in a query a name. When you run a query with labels, the result set will have the specified names for the columns rather than the standard column names. Any expression in a SELECT statement, such as columns, functions, and subqueries, can be given a label. In SQLAlchemy, labels are a potent tool for improving the readability of our queries and the practicality of data retrieval. Labels let us give columns in our query names, apply labels to functions, and aggregate our results in more useful ways. Labels help us write more understandable, maintainable code and facilitate database operationsWe will see how we can use label() feature of SQLAlchemy with the help of Python.
Database Table Used
For the purpose of this article, we'll be using a simple database called library.db. It has a table called students containing columns id, name, age, and department.
This is an example query using SQLAlchemy to select the "name" column in uppercase and the "age" column for rows where the age is greater than 18, using the select function and the label and func methods from SQLAlchemy.
Output:
In this example, the records with an age greater than 18 are converted to uppercase under the label "name_uppercase".
Labels can also be used with functions to make the result set more readable. For example, suppose we want to retrieve the number of students according to their department. We can use the label() function and the func.count() function to create a more informative result set.
Output: