How do you write a case insensitive query for both MySQL and Postgres?

后端 未结 11 1978
南方客
南方客 2020-11-29 23:39

I\'m running a MySQL database locally for development, but deploying to Heroku which uses Postgres. Heroku handles almost everything, but my case-insensitive Like statements

相关标签:
11条回答
  • 2020-11-29 23:59

    use COLLATE.

    http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

    0 讨论(0)
  • 2020-11-30 00:02

    In postgres, you can do this:

    SELECT whatever FROM mytable WHERE something ILIKE 'match this';
    

    I'm not sure if there is an equivalent for MySQL but you can always do this which is a bit ugly but should work in both MySQL and postgres:

    SELECT whatever FROM mytable WHERE UPPER(something) = UPPER('match this');
    
    0 讨论(0)
  • 2020-11-30 00:03
    select * from foo where upper(bar) = upper(?);
    

    If you set the parameter to upper case in the caller, you can avoid the second function call.

    0 讨论(0)
  • 2020-11-30 00:03

    If you're using PostgreSQL 8.4 you can use the citext module to create case insensitive text fields.

    0 讨论(0)
  • 2020-11-30 00:05

    The moral of this story is: Don't use a different software stack for development and production. Never.

    You'll just end up with bugs which you can't reproduce in dev; your testing will be worthless. Just don't do it.

    Using a different database engine is out of the question - there will be FAR more cases where it behaves differently than just LIKE (also, have you checked the collations in use by the databases? Are they identical in EVERY CASE? If not, you can forget ORDER BY on varchar columns working the same)

    0 讨论(0)
  • 2020-11-30 00:05

    There are several answers, none of which are very satisfactory.

    • LOWER(bar) = LOWER(?) will work on MySQL and Postgres, but is likely to perform terribly on MySQL: MySQL won't use its indexes because of the LOWER function. On Postgres you can add a functional index (on LOWER(bar)) but MySQL doesn't support this.
    • MySQL will (unless you have set a case-sensitive collation) do case-insensitive matching automatically, and use its indexes. (bar = ?).
    • From your code outside the database, maintain bar and bar_lower fields, where bar_lower contains the result of lower(bar). (This may be possible using database triggers, also). (See a discussion of this solution on Drupal). This is clumsy but does at least run the same way on pretty much every database.
    0 讨论(0)
提交回复
热议问题