Perform a case-insensitive search

Question

Perform a case-insensitive search to find all facilities whose name begins with 'tennis'. Retrieve all columns.

Expected Results

facidnamemembercostguestcostinitialoutlaymonthlymaintenance
0Tennis Court 152510000200
1Tennis Court 25258000200

Your Answer

Your Results

Loading database...

Answers and Discussion

select * from cd.facilities where upper(name) like 'TENNIS%';

There's no direct operator for case-insensitive comparison in standard SQL. Fortunately, we can take a page from many other language's books, and simply force all values into upper case when we do our comparison. This renders case irrelevant, and gives us our result.

Alternatively, Postgres does provide the ILIKE operator, which performs case insensitive searches. This isn't standard SQL, but it's arguably more clear.

You should realise that running a function like UPPER over a column value prevents Postgres from making use of any indexes on the column (the same is true for ILIKE). Fortunately, Postgres has got your back: rather than simply creating indexes over columns, you can also create indexes over expressions. If you created an index over UPPER(name), this query could use it quite happily.