0
0
MysqlHow-ToBeginner · 3 min read

How to Query Specific Partition in MySQL: Syntax and Examples

In MySQL, you can query a specific partition of a partitioned table by using the PARTITION(partition_name) clause in your SELECT statement. This limits the query to only the specified partition, improving performance when you know which partition holds the data.
📐

Syntax

The basic syntax to query a specific partition in MySQL is:

  • SELECT * FROM table_name PARTITION (partition_name);

Here, table_name is your partitioned table, and partition_name is the name of the partition you want to query.

This tells MySQL to scan only the specified partition instead of the whole table.

sql
SELECT * FROM table_name PARTITION (partition_name);
💻

Example

This example shows how to query a specific partition named p2023 from a partitioned table sales:

First, assume the sales table is partitioned by year with partitions like p2022, p2023.

sql
SELECT * FROM sales PARTITION (p2023);
Output
id | product | amount | sale_year ---|---------|--------|---------- 101 | WidgetA | 150 | 2023 102 | WidgetB | 200 | 2023
⚠️

Common Pitfalls

Common mistakes when querying partitions include:

  • Using partition names that do not exist, which causes an error.
  • Trying to use PARTITION clause on non-partitioned tables.
  • Expecting the PARTITION clause to filter data like a WHERE clause; it only limits which partitions are scanned.

Example of wrong usage and correction:

sql
/* Wrong: partition name typo */
SELECT * FROM sales PARTITION (p2024);

/* Correct: use existing partition name */
SELECT * FROM sales PARTITION (p2023);
📊

Quick Reference

ClauseDescription
PARTITION(partition_name)Limits query to the specified partition only
SELECT * FROM table_nameQueries entire table without partition filtering
WHERE conditionFilters rows inside the scanned partitions

Key Takeaways

Use the PARTITION(partition_name) clause in SELECT to query a specific partition.
Partition names must exist and match exactly to avoid errors.
PARTITION clause limits scanned partitions but does not filter rows like WHERE.
Only partitioned tables support the PARTITION clause in queries.
Querying specific partitions can improve performance by reducing scanned data.