LoginSignup
0
0

More than 1 year has passed since last update.

MariaDB:不正日付でより大きい検索したら全件となります

Last updated at Posted at 2022-03-26

既知の内容かもしれませんが、MariaDBを使用していてつまづいた部分になります。
使用していたMariaDBのバージョンは10.3.27なのでバージョンよって動きが違うかも
しれません。

日付型の項目に不正日付でより大きい検索

日付型の項目の検索で、日付と認識されない文字でより大きい検索を行うと全件検索となる。

サンプル例

MariaDB [test]> desc test_info;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| test_id     | varchar(20) | NO   |     | NULL    |       |
| create_date | date        | NO   |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
2 rows in set (0.006 sec)

MariaDB [test]> select * from test_info;
+----------+-------------+
| test_id  | create_date |
+----------+-------------+
| A0000001 | 2020-12-01  |
| A0000002 | 2021-01-01  |
| A0000003 | 2021-09-01  |
+----------+-------------+
3 rows in set (0.000 sec)

日付でない文字、例えばAAAAでより大きい検索を実施する。

MariaDB [test]> select * from test_info where create_date > 'AAAA';
+----------+-------------+
| test_id  | create_date |
+----------+-------------+
| A0000001 | 2020-12-01  |
| A0000002 | 2021-01-01  |
| A0000003 | 2021-09-01  |
+----------+-------------+
3 rows in set, 1 warning (0.000 sec)

こんな検索はしないとは思いますますが、sqlの実行する前に検索文字について日付型チェックをしていなかったことで想定していない結果(全件出力)となってました。またwarningが出力されるので内容の確認をすると以下の内容が確認できます。

MariaDB [test]> SHOW WARNINGS ;
+---------+------+----------------------------------+
| Level   | Code | Message                          |
+---------+------+----------------------------------+
| Warning | 1292 | Incorrect datetime value: 'AAAA' |
+---------+------+----------------------------------+
1 row in set (0.001 sec)

ちなみに日付としては正しくなくても、このような場合は0件で結果が返ります。

MariaDB [test]> select * from test_info where create_date > '2022-02-31';
Empty set (0.000 sec)

日付型項目の検索する場合は、日付の型チェックが必須だと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0