Skip to content

Instantly share code, notes, and snippets.

@theking2
Created January 1, 2024 19:39
Show Gist options
  • Save theking2/fe206ad6377cfed97b92b6a2ae336051 to your computer and use it in GitHub Desktop.
Save theking2/fe206ad6377cfed97b92b6a2ae336051 to your computer and use it in GitHub Desktop.
Calculate storage of DECIMAL(m,d)
Storage of `DECIMAL(_m_,_d_)` can be calculated with this function:
```sql
DELIMITER $$
CREATE FUNCTION `fn_DECIMAL_SIZE`(`M` INT, `D` INT) RETURNS int(11)
DETERMINISTIC
BEGIN
set @m = m;
set @d = d;
set @i = @m-@d;
set @size = 4 * floor( @i/9 );
set @size = @size + ceil( (@i % 9) / 2 );
set @size = @size + 4 * floor( @d/9 );
set @size = @size + ceil( (@d % 9) / 2 );
return @size;
END$$
DELIMITER ;
```
[source](https://dev.mysql.com/doc/refman/8.0/en/precision-math-decimal-characteristics.html)
to create a list of some values use:
```sql
select m, d, fn_DECIMAL_SIZE(m,d)
from (
(select seq as m from seq_1_to_20) _m
join
(select seq as d from seq_0_to_6) _d
)
where m>d;
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment