如何正确处理查询约束中的日期

dev*_*ium 1 sql database oracle constraints

我目前正在使用以下查询来完成2010年6月完成的所有检查:

select inspections.name
from inspections
where
  to_char(inspections.insp_date, 'YYYY') = 2010 and
  to_char(inspections.insp_date, 'MM') = 06;
Run Code Online (Sandbox Code Playgroud)

但这感觉有点尴尬.难道不会有更好的方法吗?看看http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html似乎并非如此.我正在使用Oracle,如果它有所作为.

谢谢

Vin*_*rat 11

我喜欢在可能的情况下使用范围比较,因为优化器可以将其用于索引扫描:

select inspections.name
  from inspections
 where inspections.date >= DATE '2010-06-01'
   and inspections.date < DATE '2010-07-01'
Run Code Online (Sandbox Code Playgroud)

  • @devoured elysium:我认为这是主观的,而使用索引的能力不是:) (6认同)
  • 我认为更清楚的是原始的qery和编写SQL时,如果有一个非常好的方法,将永远不会使用索引将使用索引,这是一个糟糕的主意.任何编写SQL的人都需要了解什么是sargable,什么不是.清晰度(程序员主观)并不能胜过数据库查询中的性能. (6认同)