You can use MAX()
to find the current highest value, then add 1 to that value. Use COALESCE()
to handle the case of certyearmonth values that are not yet present in the table, and you can solve both of your examples with the same query:
mysql> select coalesce(max(certmonthnumber),0)+1 as next_val
-> from certificates
-> where certyearmonth = '201310';
+----------+
| next_val |
+----------+
| 4 |
+----------+
1 row in set (0.00 sec)
mysql>
mysql> select coalesce(max(certmonthnumber),0)+1 as next_val
-> from certificates
-> where certyearmonth = '201410';
+----------+
| next_val |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)