Back to Python
2026-04-086 min read

MySQL MAX() (Python Programming)

Learn MySQL MAX() (Python Programming) step by step with clear examples and exercises.

Title: MySQL MAX() Function (Python Programming)

Why This Matters

In Python, you can use the mysql.connector module to interact with a MySQL database. The MAX() function is useful when you want to find the maximum value in a column of a table. This function is particularly important for data analysis, sorting, and filtering operations. In interviews or real-world programming scenarios, understanding how to use the MAX() function can help you solve complex problems more efficiently.

Prerequisites

Before diving into the MySQL MAX() function, ensure you have a basic understanding of:

  1. Python programming
  2. Installing and using the mysql-connector-python package
  3. Basic SQL commands and syntax (SELECT, FROM, WHERE, etc.)
  4. Understanding data types in MySQL such as INT, FLOAT, DATE, and DATETIME
  5. Knowledge of how to create tables, insert data, and execute queries in MySQL

Core Concept

To use the MySQL MAX() function in Python, you'll first need to establish a connection with your database and create a cursor object:

import mysql.connector

Create a connection to the MySQL server

connection = mysql.connector.connect(

host="localhost",

user="yourusername",

password="yourpassword",

database="yourdatabase"

)

Create a cursor object to execute SQL commands

cursor = connection.cursor()


Now, let's see how to use the `MAX()` function with different data types:

1. Integer column (e.g., id):

Execute an SQL query using the MAX() function

cursor.execute("SELECT MAX(id) FROM table_name")

Fetch the maximum value

max_value = cursor.fetchone()[0]

print(f"The maximum ID is: {max_value}")


2. Float column (e.g., price):

Execute an SQL query using the MAX() function

cursor.execute("SELECT MAX(price) FROM table_name")

Fetch the maximum value

max_value = cursor.fetchone()[0]

print(f"The maximum price is: {max_value}")


3. Date column (e.g., date):

Execute an SQL query using the MAX() function

cursor.execute("SELECT MAX(date) FROM table_name")

Fetch the maximum value (assuming date format is YYYY-MM-DD)

max_value = cursor.fetchone()[0]

print(f"The latest date is: {max_value}")


4. DATETIME column (e.g., timestamp):

Execute an SQL query using the MAX() function

cursor.execute("SELECT MAX(timestamp) FROM table_name")

Fetch the maximum value (assuming timestamp format is YYYY-MM-DD HH:MM:SS)

max_value = cursor.fetchone()[0]

print(f"The latest timestamp is: {max_value}")

Worked Example

Let's work through an example using a sample employees table:

CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
salary FLOAT,
hire_date DATE
);

INSERT INTO employees VALUES (1, 'John Doe', 28, 35000, '2020-01-01');
INSERT INTO employees VALUES (2, 'Jane Smith', 34, 40000, '2019-06-15');
INSERT INTO employees VALUES (3, 'Mike Johnson', 29, 38000, '2021-02-27');

In Python:

import mysql.connector

Establish a connection to the MySQL server

connection = mysql.connector.connect(

host="localhost",

user="yourusername",

password="yourpassword",

database="test"

)

Create a cursor object to execute SQL commands

cursor = connection.cursor()

Execute an SQL query to create the employees table (assuming you already have the data)

cursor.execute("""

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

salary FLOAT,

hire_date DATE

);

INSERT INTO employees VALUES (1, 'John Doe', 28, 35000, '2020-01-01');

INSERT INTO employees VALUES (2, 'Jane Smith', 34, 40000, '2019-06-15');

INSERT INTO employees VALUES (3, 'Mike Johnson', 29, 38000, '2021-02-27');

""")

Find the maximum salary in the employees table

cursor.execute("SELECT MAX(salary) FROM employees")

max_salary = cursor.fetchone()[0]

print(f"The maximum salary is: {max_salary}")

Find the latest hire date in the employees table

cursor.execute("SELECT MAX(hire_date) FROM employees")

latest_hire_date = cursor.fetchone()[0]

print(f"The latest hire date is: {latest_hire_date}")

Close the database connection

connection.close()


Output:

The maximum salary is: 40000.0

The latest hire date is: 2021-02-27

Common Mistakes

  1. Using the incorrect syntax for the MAX() function:

Incorrect:

cursor.execute("SELECT MAX(employees) FROM table_name")

Correct:

cursor.execute("SELECT MAX(salary) FROM employees")
  1. Not fetching the maximum value after executing the SQL query:

Incorrect:

cursor.execute("SELECT MAX(salary) FROM employees")

Correct:

cursor.execute("SELECT MAX(salary) FROM employees")
max_value = cursor.fetchone()[0]
print(f"The maximum salary is: {max_value}")
  1. Forgetting to close the database connection:

Incorrect:

import mysql.connector

Establish a connection to the MySQL server

connection = mysql.connector.connect(

host="localhost",

user="yourusername",

password="yourpassword",

database="test"

)

Create a cursor object to execute SQL commands

cursor = connection.cursor()

Execute an SQL query to create the employees table (assuming you already have the data)

cursor.execute("""

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

salary FLOAT,

hire_date DATE

);

INSERT INTO employees VALUES (1, 'John Doe', 28, 35000, '2020-01-01');

INSERT INTO employees VALUES (2, 'Jane Smith', 34, 40000, '2019-06-15');

INSERT INTO employees VALUES (3, 'Mike Johnson', 29, 38000, '2021-02-27');

""")

Find the maximum salary in the employees table

cursor.execute("SELECT MAX(salary) FROM employees")

max_salary = cursor.fetchone()[0]

print(f"The maximum salary is: {max_salary}")


Correct:

import mysql.connector

Establish a connection to the MySQL server

connection = mysql.connector.connect(

host="localhost",

user="yourusername",

password="yourpassword",

database="test"

)

Create a cursor object to execute SQL commands

cursor = connection.cursor()

Execute an SQL query to create the employees table (assuming you already have the data)

cursor.execute("""

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

salary FLOAT,

hire_date DATE

);

INSERT INTO employees VALUES (1, 'John Doe', 28, 35000, '2020-01-01');

INSERT INTO employees VALUES (2, 'Jane Smith', 34, 40000, '2019-06-15');

INSERT INTO employees VALUES (3, 'Mike Johnson', 29, 38000, '2021-02-27');

""")

Find the maximum salary in the employees table

cursor.execute("SELECT MAX(salary) FROM employees")

max_salary = cursor.fetchone()[0]

print(f"The maximum salary is: {max_salary}")

Close the database connection

connection.close()


4. Not handling ties (multiple values with the same maximum value):

If you need to find all rows with the maximum value, use the `SELECT` statement with a `WHERE` clause instead:

cursor.execute("""

SELECT * FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);

""")

max_salaries = cursor.fetchall()

print(f"The employees with the maximum salary are: {max_salaries}")

Practice Questions

  1. Write a Python script to find the maximum age in the employees table using the MySQL MAX() function.
  2. Given a sales table with columns id, product_id, and quantity_sold, write a Python script to find the product ID that has been sold the most using the MySQL MAX() function.
  3. Write a Python script to find the maximum date in a transactions table that contains columns transaction_id, date, and amount. Assume the date column is of type DATETIME.
  4. Write a Python script to find all employees who have the same maximum salary using the MySQL MAX() function.
  5. Given a users table with columns id, username, email, and registration_date, write a Python script to find the latest registration date for each unique username using the MySQL MAX() function.

FAQ

Can I use the MySQL MAX() function with multiple columns?

Yes, you can use the MAX() function with multiple columns by separating them with a comma. For example:

cursor.execute("SELECT MAX(column1), MAX(column2) FROM table_name")

How do I handle ties (multiple values with the same maximum value) using the MySQL MAX() function?

The MAX() function returns only one value, so if there are multiple values with the same maximum, it will return any one of them. If you need to find all rows with the maximum value, use the SELECT statement with a WHERE clause instead:

cursor.execute("""
SELECT * FROM table_name WHERE column = (SELECT MAX(column) FROM table_name);
""")

Can I use the MySQL MAX() function to find the minimum value in a column?

No, the MAX() function only returns the maximum value in a column. To find the minimum value, you can use the MIN() function instead.

How do I use the MySQL MAX() function with a WHERE clause to filter results?

To use the MAX() function with a WHERE clause, include the condition within parentheses after the table name:

cursor.execute("SELECT MAX(column) FROM table_name WHERE condition")

For example:

cursor.execute("SELECT MAX(salary) FROM employees WHERE department = 'IT'")
MySQL MAX() (Python Programming) | Python | XQA Learn