can't you just write an SQL query to get the list of pairs meeting your criteria from the database? in doesn't seem impossible from your specification.
Alternatively you could write a query to get a subset of promissing pairs, and then check if those meet your criteria with a Perl script.