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.
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.
SELECT DISTINT column_name FROM table_name
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 | +----------+---------+
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.
America England India France