my %ids; $origsql = qq{ SELECT route_number, stop_reference, depart_time FROM routes WHERE distance < 200...........}; #all SQL code not included here $sth = $dbh->prepare( $origsql ); $sth->execute(); $sth->bind_columns( undef, \$orig_service_id, \$orig_stop, $depart_orig); while ($sth->fetch()) { push(@orig_service_ids, $orig_service_id); } for my $id (@orig_service_ids) { $ids{$id} = 1; } # ... $destsql = qq{ SELECT route_number, stop_reference, depart_time FROM routes WHERE distance < 200...........}; #all SQL code not included here $sth = $dbh->prepare( $destsql ); $sth->execute(); $sth->bind_columns( undef, \$dest_service_id, \$dest_stop, $depart_dest); while ($sth->fetch()) { push(@dest_service_ids, $dest_service_id); } for my $id (@dest_service_ids) { if (exists $ids{$id}) { print "ID $id exists in both origin and destination set\n"; } }