HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

mysqldump with LIMIT and --order-by-primary

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
orderprimarywithlimitmysqldumpand

Problem

I want to use mysqldump to retrieve X first rows from a database (where "first" are ordered by primary key).

I'm trying to use mysqldump the following way:

mysqldump [connection-info] -where"1=1 LIMIT 40" --order-by-primary database table >> file.sql

(this is inside a script who runs different configurations for different tables)

Now, the problem, that command creates the following query:

SELECT /!40001 SQL_NO_CACHE / * FROMtableWHERE 1=1 LIMIT 40 ORDER BY primary_key

Is an invalid query, I need the LIMIT 40 to be placed after the ORDER BY statement.

Solution

My guess is that you cant use limit in combination with --order-by-primary

One way around this is to define the order by within the -where argument. If you know the primary key for the table:

mysqldump -u lelle -p -w"1 = 1 order by  LIMIT 40"  


Note that `` is a place holder for the columns in the primary key.

if you don't know the primary key in advance you can use the INFORMATION_SCHEMA to determine that:

select GROUP_CONCAT(column_name SEPARATOR ',') 
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
where CONSTRAINT_NAME = 'PRIMARY' 
  and CONSTRAINT_SCHEMA = ... and table_name = ...;


and then use the information in mysqldump.

Code Snippets

mysqldump -u lelle -p -w"1 = 1 order by <primary key> LIMIT 40" <database> <table>
select GROUP_CONCAT(column_name SEPARATOR ',') 
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
where CONSTRAINT_NAME = 'PRIMARY' 
  and CONSTRAINT_SCHEMA = ... and table_name = ...;

Context

StackExchange Database Administrators Q#138499, answer score: 9

Revisions (0)

No revisions yet.