⊗pyPmDBQC 120 of 128 menu

Adding Strings When Selecting SQL in Python

When retrieving records from a database, you can add rows together using the CONCAT function. The rows are usually table fields.

Example

In this example, when selecting from the database, a new field concat is created, in which 3 fields are simultaneously merged - age, name and salary:

query = "SELECT *, CONCAT(age, name, salary) as concat FROM users"

The result of the executed code:

{'id': 1, 'name': 'user1', 'age': 23, 'salary': 400, 'concat': '23user1400'} {'id': 2, 'name': 'user2', 'age': 25, 'salary': 500, 'concat': '25user2500'} {'id': 3, 'name': 'user3', 'age': 23, 'salary': 500, 'concat': '23user3500'} {'id': 4, 'name': 'user4', 'age': 30, 'salary': 900, 'concat': '30user4900'} {'id': 5, 'name': 'user5', 'age': 27, 'salary': 500, 'concat': '27user5500'} {'id': 6, 'name': 'user6', 'age': 28, 'salary': 900, 'concat': '28user6900'}

Example

Let's add 3 exclamation marks after name:

query = "SELECT *, CONCAT(name, '!!!') as name FROM users"

The result of the executed code:

{'id': 1, 'name': 'user1!!!', 'age': 23, 'salary': 400} {'id': 2, 'name': 'user2!!!', 'age': 25, 'salary': 500} {'id': 3, 'name': 'user3!!!', 'age': 23, 'salary': 500} {'id': 4, 'name': 'user4!!!', 'age': 30, 'salary': 900} {'id': 5, 'name': 'user5!!!', 'age': 27, 'salary': 500} {'id': 6, 'name': 'user6!!!', 'age': 28, 'salary': 900}

Practical tasks

Display the age of users by adding the word 'user_age' to the value.

enru