Showing posts with label loop. Show all posts
Showing posts with label loop. Show all posts

MariaDB Sequence Storage Engine

Posted on Tuesday, April 14, 2020 by Nicki

Learnt today that MariaDB has this great feature called a Sequence Storage Engine.

Ever needed to repeat something couple of times but don't want to write a loop? Just write a query that joins to a sequence table, for example:

set @date = date(now());
select 
date(date_add(@date, interval seq day)) as date, 
dayname(date_add(@date, interval seq day)) as dayname, 
week(date_add(@date, interval seq day)) as weeknum, 
mod(dayofweek(date_add(@date, interval seq day))+5, 7) dayofweek, 
case when mod(dayofweek(date_add(@date, interval seq day))+5, 7) < 5 then 1 else 0 end workday
from seq_0_to_21

It produces the following listing(forgive the formatting):

+------------+-----------+---------+-----------+---------+
| date | dayname | weeknum | dayofweek | workday |
+------------+-----------+---------+-----------+---------+
| 2020-04-14 | Tuesday | 15 | 1 | 1 |
| 2020-04-15 | Wednesday | 15 | 2 | 1 |
| 2020-04-16 | Thursday | 15 | 3 | 1 |
| 2020-04-17 | Friday | 15 | 4 | 1 |
| 2020-04-18 | Saturday | 15 | 5 | 0 |
| 2020-04-19 | Sunday | 16 | 6 | 0 |
| 2020-04-20 | Monday | 16 | 0 | 1 |
| 2020-04-21 | Tuesday | 16 | 1 | 1 |
| 2020-04-22 | Wednesday | 16 | 2 | 1 |
| 2020-04-23 | Thursday | 16 | 3 | 1 |
| 2020-04-24 | Friday | 16 | 4 | 1 |
| 2020-04-25 | Saturday | 16 | 5 | 0 |
| 2020-04-26 | Sunday | 17 | 6 | 0 |
| 2020-04-27 | Monday | 17 | 0 | 1 |
| 2020-04-28 | Tuesday | 17 | 1 | 1 |
| 2020-04-29 | Wednesday | 17 | 2 | 1 |
| 2020-04-30 | Thursday | 17 | 3 | 1 |
| 2020-05-01 | Friday | 17 | 4 | 1 |
| 2020-05-02 | Saturday | 17 | 5 | 0 |
| 2020-05-03 | Sunday | 18 | 6 | 0 |
| 2020-05-04 | Monday | 18 | 0 | 1 |
| 2020-05-05 | Tuesday | 18 | 1 | 1 |
+------------+-----------+---------+-----------+---------+
22 rows in set (0.01 sec)

The sequence table name is dynamic, so to get a sequence from 1 to 5 use the table name seq_1_to_5. It has a column called seq that contains the sequence number

Link:  https://mariadb.com/kb/en/sequence-storage-engine/