Categories: python

WHERE Clause – MySQL

In a MySQL database, the where clause is used to filter the data according to the specified conditions. Using the where clause, you can retrieve, remove, or update a specific set of data in a MySQL database.

MySQL WHERE Clause in Python:

The WHERE clause has already been employed in one of our earlier tutorials:

  • MySQL data update using Python
  • MySQL data can be deleted using Python.

Use the WHERE clause in the SELECT statement to select data from a table based on a specific condition.

  • Rows from the result set are typically filtered using the WHERE clause.
  • Data from the MySQL Table can be retrieved, updated, and deleted with its assistance.

Syntax:

Following is the syntax of the WHERE clause −

SELECT column1, column2, columnN
FROM table_name
WHERE [condition]

Example: Consider the following database named college and have a table name as a student.
Schema of the database:

import mysql.connector

#Establishing connection
conn = mysql.connector.connect(
user='your_username',
host='localhost',       password='your_password',
database='College')

# Creating a cursor object using
# the cursor() method
mycursor = conn.cursor();

# SQL Query
sql = "select * from Student where Roll_no >= 21;"

# Executing query
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
 print(x)

# Closing the connection
conn.close()

The where clause retrieves the records with roll number value greater than 21.

Note: also read about Drop Table Query – MySQL

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

11 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago