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


Inside SQL tables, columns usually contain duplicate values. We may sometimes need to get only the distinct or different values present in a column in our table since the duplicate values makes it difficult for us to analyze the results returned by the query.

Example:

Suppose, we have a table named Customers which conatins details about our customers, their names,age and country etc. We need to know to which different countries do our customers belong. We may have 10 customers from India, 15 from America and so on. If we simply select the country column, this will return us the whole column with lots of duplicate values .This won’t serve our purpose as it will be difficult for us to analyze the results. We just want to know the distince countries.

In this scenario, the “SELECT DISTINCT” statement of MySQL is used.

Syntax

SELECT DISTINT column_name FROM table_name

Major steps to select distint value from a table in database using MySQL in python

  • import mysql connector

  • establish connection with the connector using connect()

  • create the cursor object using cursor() method

  • create a query using the appropriate mysql statements

  • execute the SQL query using execute() method

  • close the connection

Suppose , we have the following table named “Customers”.

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

Example

We need to select the distinct country names from this table.

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="SELECT DISTINCT country FROM Customers "
cursor.execute(query)
for names in cursor:
   print(names)
db.close()

The above code returns the distinct country names.

Output

America
England
India
France

Updated on: 10-Jun-2021

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements