SELECT DISTINCT(Column_name) FROM table
In our sample database my_db.db, we have student table. Each row ( student ) have one class. We will display the unique classes by using DISTINCT query.
q="SELECT DISTINCT(class) FROM student"
try:
my_cursor=my_conn.execute(q)
for row in my_cursor:
print(row[0])
except sqlite3.Error as my_error:
print("error: ",my_error)
Output
Four
Three
Five
Six
Seven
Nine
Eight
We can add ORDER BY to this to display in alphabetical order. ( the change in query is shown here )
q="SELECT DISTINCT(class) FROM student ORDER BY class"
q="SELECT COUNT(DISTINCT(class)) FROM student"
Output
7
Using SQLAlchemy and with WHERE condition
from sqlalchemy.exc import SQLAlchemyError
q="SELECT DISTINCT(class) FROM student WHERE mark>=80"
try:
r_set=my_conn.execute(q)
data=r_set.fetchall()
for row in data:
print(row[0])
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
else:
print("No of records displayed : ",len(data))
Output
Three
Five
Six
Seven
Four
No of records displayed : 5
q="SELECT DISTINCT class,gender FROM student"
try:
my_cursor=my_conn.execute(q)
for row in my_cursor:
print(row[0],row[1])
except sqlite3.Error as my_error:
print("error: ",my_error)
Output
Four female
Three male
Four male
Five male
Six male
Six female
Seven female
Nine male
Nine female
Eight male
Seven male
Three female
q="SELECT DISTINCT class FROM student WHERE class NOT NULL"
try:
my_cursor=my_conn.execute(q)
for row in my_cursor:
print(row[0])
except sqlite3.Error as my_error:
print("error: ",my_error)
View and Download sqlite-distinct.ipynb file
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.