Suppose I have a (code-generated) query that is looking for keywords in a number of different fields. For example, any one of the terms University
, South
or Africa
might be in the name field, or the address field, or some other field. I want to find all records where any of these fields match any of these keywords:
SELECT *
FROM
Institutions
WHERE
Institutions.name LIKE '%University%' OR
Institutions.address LIKE '%University%' OR
Institutions.name LIKE '%South%' OR
Institutions.address LIKE '%South%' OR
Institutions.name LIKE '%Africa%' OR
Institutions.address LIKE '%Africa%'
However, this is going to pull up everything. I would like to sort by the records that match the most possible conditions.
I think this would work but looks pretty clunky:
SELECT *
FROM
Institutions
WHERE
Institutions.name LIKE '%University%' OR
Institutions.address LIKE '%University%' OR
Institutions.name LIKE '%South%' OR
Institutions.address LIKE '%South%' OR
Institutions.name LIKE '%Africa%' OR
Institutions.address LIKE '%Africa%'
ORDER BY
(
CASE WHEN Institutions.name LIKE '%University%' THEN 1 ELSE 0 END +
CASE WHEN Institutions.address LIKE '%University%' THEN 1 ELSE 0 END +
CASE WHEN Institutions.name LIKE '%South%' THEN 1 ELSE 0 END +
CASE WHEN Institutions.address LIKE '%South%' THEN 1 ELSE 0 END +
CASE WHEN Institutions.name LIKE '%Africa%' THEN 1 ELSE 0 END +
CASE WHEN Institutions.address LIKE '%Africa%' THEN 1 ELSE 0 END
) DESC
Is there something cleaner? I'm fine with SQL Server-specific solutions but pure SQL solutions would be great.