my @order; my $sth_1 = $dbh->prepare( "SELECT id FROM TABLE WHERE previous IS NULL" ) or die $DBI->errstr; my $sth_2 = $dbh->prepare( "SELECT id FROM TABLE WHERE previous IS ?" ) or die $DBI->errstr; $sth_1->execute() or die $DBI->errstr; if ( $sth_1->rows() > 0 ) { my ($id) = $sth_1->fetchrow_array(); push @order, $id; $sth_2->execute( $id ) or die $DBI->errstr; while ( $sth_2->rows() > 0 ) { my ( $id ) = $sth_2->fetchrow_array(); push @order, $id; $sth_2->execute( $id ) or die $DBI->errstr; } }