How to Concatenate Column Values of a MySQL Table Using Python?

MySQL is an open-source relational database management system widely used to store and manage data. When working with MySQL tables, you often need to combine multiple column values into a single string for reporting and analysis. Python provides the PyMySQL library to connect to MySQL databases and execute SQL queries efficiently.

This article demonstrates how to concatenate column values from a MySQL table using Python and PyMySQL. We'll cover connecting to a database, executing concatenation queries, and handling results properly.

Installing PyMySQL

First, install the PyMySQL library using pip ?

pip install PyMySQL

This command installs PyMySQL and its dependencies. You can verify the installation by importing PyMySQL in Python without errors.

Setting Up Database Connection

Create a connection to your MySQL database by providing the required credentials ?

import pymysql

# Establish database connection
connection = pymysql.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database',
    charset='utf8mb4'
)

Replace the connection parameters with your actual database credentials. The charset='utf8mb4' ensures proper handling of Unicode characters.

Method 1: Using CONCAT() Function

The MySQL CONCAT() function combines multiple column values with optional separators ?

import pymysql

try:
    # Connect to database
    connection = pymysql.connect(
        host='localhost',
        user='your_username',
        password='your_password',
        database='your_database',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    
    with connection.cursor() as cursor:
        # Concatenate first_name and last_name
        sql = "SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees"
        cursor.execute(sql)
        
        results = cursor.fetchall()
        
        # Print results
        for row in results:
            print(row['full_name'])
            
finally:
    connection.close()

Method 2: Using CONCAT_WS() Function

CONCAT_WS() (Concatenate With Separator) automatically handles NULL values and applies a consistent separator ?

import pymysql

try:
    connection = pymysql.connect(
        host='localhost',
        user='your_username', 
        password='your_password',
        database='your_database',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    
    with connection.cursor() as cursor:
        # Concatenate multiple columns with separator
        sql = """SELECT 
                    CONCAT_WS(' - ', first_name, last_name, department) 
                    AS employee_info 
                 FROM employees"""
        cursor.execute(sql)
        
        results = cursor.fetchall()
        
        for row in results:
            print(row['employee_info'])
            
finally:
    connection.close()

Method 3: Concatenating with Custom Logic

You can combine concatenation with conditional logic using CASE statements ?

import pymysql

try:
    connection = pymysql.connect(
        host='localhost',
        user='your_username',
        password='your_password', 
        database='your_database',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    
    with connection.cursor() as cursor:
        # Conditional concatenation
        sql = """SELECT 
                    CASE 
                        WHEN middle_name IS NOT NULL 
                        THEN CONCAT(first_name, ' ', middle_name, ' ', last_name)
                        ELSE CONCAT(first_name, ' ', last_name)
                    END AS full_name
                 FROM employees"""
        cursor.execute(sql)
        
        results = cursor.fetchall()
        
        for row in results:
            print(row['full_name'])
            
finally:
    connection.close()

Best Practices

Follow these practices for secure and efficient database operations ?

  • Always use try-finally blocks or context managers to ensure connections are closed
  • Use DictCursor for easier result handling
  • Handle database exceptions appropriately
  • Never hardcode credentials in production code
  • Use parameterized queries to prevent SQL injection

Comparison of Methods

Method NULL Handling Best For
CONCAT() Returns NULL if any value is NULL Simple concatenation
CONCAT_WS() Skips NULL values Multiple columns with separators
Conditional Logic Custom handling Complex concatenation rules

Conclusion

Concatenating MySQL column values in Python is straightforward using PyMySQL and SQL functions like CONCAT() and CONCAT_WS(). Always use proper connection handling and choose the concatenation method that best fits your data structure and NULL value requirements.

Updated on: 2026-03-27T09:13:01+05:30

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements