Skip to content

Day 52: Using comparison operators

Utilizing Comparison Operators in SQL: Filtering Data Based on Specific Conditions

Comparison operators in SQL are essential tools that help us filter data in our databases. These operators, which include greater than (>), less than (<), equal to (=), greater than or equal to (>=), not equal to (<> or !=), allow us to specify conditions in our queries.

For instance, if you want to filter out books that have a rating greater than 4, you can use the greater than (>) operator. In this context, we start with the SELECT command to select the title and rating columns from the books table. We then specify that we want rows where the rating is greater than 4.

Filtering Data with SQL

Here's how you can select books with a rating greater than 4 using SQL and Python:

import sqlite3

# Connect to the bookstore.db database
conn = sqlite3.connect("bookstore.db")

# Create a cursor to execute SQL commands
cursor = conn.cursor()

# SELECT all books with a rating greater than 4
cursor.execute("""
SELECT title, rating FROM books
WHERE rating > 4
""")

# Retrieve all rows returned by the SELECT statement
rows = cursor.fetchall()

# Iterate over the rows and print each row
for row in rows:
    print(row)

# Close the database connection
conn.close()

In this Python script, we connect to the bookstore.db database and create a cursor to execute SQL commands. We then use the greater than (>) operator to select books with a rating greater than 4. The results are fetched and printed, and finally, we close the database connection.

By using comparison operators, we can efficiently filter data in our SQL queries, enhancing our data analysis capabilities and improving the readability of our code.

Learn More

Want to learn more about SQL for Machine Learning? Check out the full course HERE.


Need help mastering Machine Learning?

Don't just follow along — join me! Get exclusive access to me, your instructor, who can help answer any of your questions. Additionally, get access to a private learning group where you can learn together and support each other on your AI journey.