Renaming a Field in Python

There are situations when you need to rename the original fields of records when outputting them. In such cases, the SQL command AS is used. It sets a new name for fields or tables when selecting from a database, while no changes occur in the database itself.

Example

Let's select the names of all users from our table users and give this field a different name:

pythonquery = "SELECT name as user_name FROM users"

The result of the executed code:

python{'user_name': 'user1'}
{'user_name': 'user2'}
{'user_name': 'user3'}
{'user_name': 'user4'}
{'user_name': 'user5'}
{'user_name': 'user6'}
{'user_name': 'user'}

Example

You can rename only one field from the selection:

pythonquery = "SELECT id, age as user_age FROM users"

The result of the executed code:

python{'id': 1, 'user_age': 23}
{'id': 2, 'user_age': 25}
{'id': 3, 'user_age': 23}
{'id': 4, 'user_age': 30}
{'id': 5, 'user_age': 27}
{'id': 6, 'user_age': 28}
{'id': 8, 'user_age': 30}

Example

To rename a table, you need to use the AS command to the right of its name:

pythonquery = "SELECT id, age as user_age FROM users as users_table"

Practical tasks

Задание 1

Rename the user salary field when outputting to the console.

Задание 2

Display the name, age and salary of users, while renaming their names and ages.