use CGI; my $q = new CGI; my %args = $q->Vars; $fields = join(",", sort { $args{$a} <=> $args{$b} } keys %args ) # Sort with values of hash and Join. It won't put ',' at the end $SQL = "SELECT $fields FROM YOUR_TABLE_NAME";