【问题标题】:When is comparing strings case-sensitive and when case-insensitive in SQL?什么时候比较字符串区分大小写,什么时候在 SQL 中不区分大小写?
【发布时间】:2020-11-19 21:03:26
【问题描述】:

PostgreSQLMySQLMariaDBOracleSQL ServerSQLite 等流行数据库中,何时比较字符串是否区分大小写?

我的意思是使用诸如'ab' = 'AB' 之类的运算符进行比较,或者使用诸如POSITION('b' IN 'ABC')INSTR('ABC', 'b')REPLACE('ABC', 'b', 'x')TRANSLATE('ABC', 'b', 'x')TRIM('XabcX', 'x') 之类的字符串函数中执行的字符串比较。

我认为我可以知道答案,但我不知道它是否正确。

另外,SQL标准是否定义了字符串比较的区分大小写?

很遗憾,我只找到了一个关于case-sensitivity of SQL syntax的问题,并没有在字符串比较中找到。

编辑:我询问的是 RDBMS 的默认设置,没有额外设置数据库、表或列的排序规则。

我只询问 ASCII 字母 A-Z 和 a-z。

【问题讨论】:

  • SQL 始终区分大小写
  • 对于 SQL Server,它取决于排序规则。大多数人最终会使用不区分大小写、区分重音的 IME
  • 我依赖于数据库,以及各种因素,例如数据库、表和列的排序规则。就目前而言,您的问题非常广泛,如果不提供更多详细信息,就无法准确回答。
  • @GMB:我在RDBMS的默认设置中添加了我感兴趣的信息,没有设置数据库、表、或列的排序规则。默认情况下在这种情况下是否总是区分大小写?
  • @GMB:我也只对 ASCII 字母 A-Z 和 a-z 感兴趣,而且只对 PostgreSQL、MySQL、MariaDB、Oracle、SQL Server 和 SQLite 数据库感兴趣。如果问题还有其他问题,请告诉我。

标签: sql case-sensitive case-insensitive


【解决方案1】:

Oracle DB 函数/操作符区分大小写,包括regexp_like 方法在内的一些例外情况可以切换到区分大小写模式;

--case sensitive demo
select q.txt 
from (select 'myPhrase' txt from dual) q
where regexp_like(q.txt, 'myphrase');  --empty result set

select q.txt 
from (select 'myPhrase' txt from dual) q
where q.txt like 'myphrase'; --empty result set

select q.txt 
from (select 'myPhrase' txt from dual) q
where q.txt like 'myPhrase'; --exact match; returns value

select q.txt 
from (select 'myPhrase' txt from dual) q
where regexp_like(q.txt, 'myphrase', 'i'); --case insensitive switch 'i'; returns value

select q.txt 
from (select 'myPhrase' txt from dual) q
where lower(q.txt) like 'myphrase'; --enforced match; returns value;

这里是 Collation rules for different SQL OperationsData Type Comparison Rules 的文档参考

一旦伪排序规则被确定为要使用的排序规则,就会检查 NLS_SORT 和 NLS_COMP 会话参数以提供要应用的实际命名排序规则 通常这两个设置为 BINARY

SELECT
    t.parameter,
    t.value
FROM
    nls_database_parameters t
WHERE
    t.parameter IN (
        'NLS_COMP', 'NLS_SORT'
    );

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多