Open In App

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

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Python: MySQL Create Table

In this article, we show how to concatenate column values of a MySQL table using Python. We use various data types in SQL Server to define data in a particular column appropriately. We might have requirements to concatenate data from multiple columns into a string

Concatenating Columns means that one is merging column data and showing it into a single column. This can also be done in MySQL using the CONCAT() function, but we are using a Python Program to concatenate multiple columns. MySQL Connector-Python module is an API in python for communicating with a MySQL database.

We are going to use this database:

How to Concatenate Column Values of a MySQL Table:

Syntax: SELECT Concat(Column Name 1, Column Name 2) AS fulldetail FROM Table_Name

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

This example shows the Concatenation of a column. Steps are as follows:

  • Use connect() function to establish a connection with the database server. Pass the host, user (root or your username), password (if present), and database parameters to connect() method.
  • Then to create a cursor object, use the cursor() function.
  • Execute the upper disused syntax for the Person table.

Syntax: 
cursor.execute("SELECT Concat(Column Name 1, Column Name 2) AS fulldetail FROM Table_Name")

Code:

Python3
# Establish connection to MySQL database
import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="root123",
  database = "geeks"
  )
mycursor = mydb.cursor()

mycursor.execute("SELECT Concat(FirstName, LastName) AS fulldetail FROM Persons;")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Output:

('PathakAnuk',)
('kantKrish',)

Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy