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

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 hours ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

3 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

3 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago