Explain the use of SELECT DISTINCT statement in MySQL using Python?

MySQL tables often contain duplicate values in columns. The SELECT DISTINCT statement helps retrieve only unique values, making data analysis easier and results cleaner.

For example, if you have a customers table with multiple customers from the same countries, using SELECT DISTINCT on the country column returns only the unique country names instead of all duplicate entries.

Syntax

SELECT DISTINCT column_name FROM table_name

Steps to Use SELECT DISTINCT in Python

  • Import the MySQL connector

  • Establish database connection using connect()

  • Create a cursor object using cursor() method

  • Write the SELECT DISTINCT query

  • Execute the query using execute() method

  • Fetch and process the results

  • Close the database connection

Sample Data

Let's assume we have a "Customers" table with the following data:

+--------+---------+
| name   | country |
+--------+---------+
| John   | America |
| Peter  | England |
| Karan  | India   |
| Rohit  | India   |
| Rohan  | America |
| Arsh   | France  |
| Aryan  | England |
+--------+---------+

Example: Getting Distinct Countries

Here's how to retrieve unique country names from the Customers table:

import mysql.connector

# Establish database connection
db = mysql.connector.connect(
    host="localhost",
    user="your_username", 
    password="your_password",
    database="your_database"
)

cursor = db.cursor()

# Execute SELECT DISTINCT query
query = "SELECT DISTINCT country FROM Customers"
cursor.execute(query)

# Fetch and display results
print("Distinct countries:")
for country in cursor:
    print(country[0])

# Close connection
cursor.close()
db.close()

Output

Distinct countries:
America
England
India
France

Using Multiple Columns

You can also use SELECT DISTINCT with multiple columns to get unique combinations:

import mysql.connector

db = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password", 
    database="your_database"
)

cursor = db.cursor()

# Get distinct name-country combinations
query = "SELECT DISTINCT name, country FROM Customers"
cursor.execute(query)

print("Distinct name-country combinations:")
for row in cursor:
    print(f"{row[0]} - {row[1]}")

cursor.close()
db.close()

Conclusion

The SELECT DISTINCT statement is essential for removing duplicate values from query results. It helps analyze unique data patterns and makes database outputs cleaner and more meaningful for analysis.

---
Updated on: 2026-03-25T22:45:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements