sub datas { $data1 = ""; $data2 = ""; my $str= shift; $DBH = &connect or die "Cannot connect to the sql server \n"; $DBH->do("USE $str;"); my $stmt="select name,data1,data2 from((select name,data1,data2 from datas order by data1 +data2 desc limit 5 )union all(select 'added' as name ,sum(data1) as data1 ,sum(data2) as data2 from (select data1,data2 from datas order by data2+data1 desc limit 18446744073709551615 offset 5 ) new)) new;"; my $sth = $DBH->prepare( $stmt ); $sth->execute() or die $sth->errstr; my $tmp = 0; while(my @row_array=$sth->fetchrow_array) { if ($tmp == 0) { $data1 .= "\[\"$row_array[0] \($row_array[2]\)\",$row_array[2]\]"; $data2 .= "\[\"$row_array[0] \($row_array[1]\)\",$row_array[1]\]"; $tmp++; } else { $data1 .= ",\[\"$row_array[0] \($row_array[2]\)\",$row_array[2]\]"; $data2 .= ",\[\"$row_array[0] \($row_array[1]\)\",$row_array[1]\]"; } } $sth->finish; $DBH->disconnect(); } #### obtained output: +--------------+--------------+--------------+ | name | data1 | data2 | +--------------+--------------+--------------+ | dsp_ncsim_hp | 11262 | 82 | | adice_short | 2865 | 274 | | ncsim_long | 741 | 116 | | adice_ncsim | 109 | 150 | | normal | 133 | 31 | | others | 5 | 184 | +--------------+--------------+--------------+ Expected: Jobs_running need to be changed.Here jobs_running column is fetching as per jobs_pending column.Jobs_pending should be sorted from maximum to minimum level as per queue_name.Here jobs_running column is not arranged from maximum to minimum level. +--------------+--------------+--------------+ | queue_name | data1 | data2 | +--------------+--------------+--------------+ | dsp_ncsim_hp | 11262 | 82 | | adice_short | 2865 | 274 | | ncsim_long | 741 | 116 | | adice_ncsim | 109 | 150 | | normal | 133 | 31 | | others | 5 | 184 | +--------------+--------------+--------------+ In the above table running is not in this order.How can i sort jobs_running and jobs_pending independently by its value. For jobs_running:- +-------------+--------------+--+ | name | data1 | +--------------+---------------+ |adice_short | 274 | | adice_ncsim | 150 | | ncsim_long | 116 | | dsp_ncsim_hp | 82 | | normal | 31 | | others | 184 | +--------------+---------------+ For jobs_pending:- +--------------+--------------+ | name | data2 | +--------------+--------------+ | dsp_ncsim_hp | 11262 | | adice_short | 2865 | | ncsim_long | 741 | | adice_ncsim | 109 | | normal | 133 | | others | 5 | +--------------+--------------+