简体   繁体   中英

Where clause for SQL query for months and years

I've written an Sql query with a where clause narrowing the result to be with start month start year and end month end year . Please find below the part with where clause (my query is quite complex so I don't want to give all its details):

SELECT *
  FROM foo
  WHERE (year, month) between (startYear, startMonth) and (endYear, endMonth);

Note thatI find it to be very easy to understand and very expressive. How about its speed? Are there faster alternatives? If so, how would they look like?

In general, when you write SQL queries, you shouldn't really worry about speed. A mature SQL server will select a reasonable execution plan for you. So your query is probably fine. There are a few things though that you can check:

  • You can check whether there are indexes for the columns in your where clause.
  • If there are compound indexes then you can make sure to use the columns in the same order they appear in the index definition.
  • You can make sure to use search arguments in your WHERE clauses. In a nutshell it means not to make calculation on a column value before comparing to it.

If this speed is not good enough for you, then you can tune the indexes for your query. Ie add indexes that match your where clauses. Some RDBMS-s let you partition your tables by date. Sometimes you can replace one complex query with a few simple queries and temporary tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM