mysqlsqlpartitioningdatabase-partitioningmysql-5.1

How to select rows from partition in MySQL


I made partition my 300MB table and trying to make select query from p0 partition with this command

SELECT * FROM employees PARTITION (p0);

But I am getting following error

ERROR 1064 (42000): You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near '(p0)' at line 1

How to write select query to get data from specific partition?


Solution

  • Depending on you MySql version, PARTITION keyword does not exist until MySQL 5.6.2. You would be using MySQL 5.5 or even 5.1, but not 5.6. In case, you are using MySQL 5.1, then you can do some workaround like below

    SELECT partition, count(ID)
    FROM
    (
        SELECT ID,
          case when condition then p1
               when condition then p2
          .....
          end as partition
    
        FROM
          table
    ) s1
    GROUP BY partition
    

    Note : The above solution is just workaround to get you desire output.

    You may also try this query to count total number of rows for your partition.

    SELECT table_rows as 'count(*)' FROM information_schema.partitions WHERE table_schema = schema() and table_name ='employees' and partition_name = 'p0';
    

    Note : you may change table_schema = schema() to table_schema = 'yourschema'