making the custom SQL filtering more robust (still messy)