SQL SCALE function
Returns the count of digits after the decimal point of a numeric value, including trailing zeros: scale(1.2300) is 4.
- カテゴリ
- Math
- Returns
integer- In this category
- 16 of 82
構文
SCALE(numeric)
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | Not built in | No equivalent; SQL_VARIANT_PROPERTY(x, 'Scale') reports the declared scale of the expression's type |
| PostgreSQL | はい | scale(numeric) since 9.6; min_scale and trim_scale arrived in 13 |
| MySQL | Not built in | No equivalent; you can approximate with LENGTH of the fractional part of a CAST to text |
| SQLite | Not built in | No equivalent; values are stored as REAL and carry no fixed scale |
| Oracle | Not built in | No direct function; TO_CHAR and string parsing can count the digits |
例
PostgreSQL
SELECT SCALE(1.2300::numeric) AS s; -- 4
PostgreSQL
SELECT amount, SCALE(amount::numeric) AS digits_after_point FROM payments;
知っておくと便利なこと
- scale counts stored digits, so scale(1.2300) is 4 while scale(1.23) is 2. PostgreSQL numeric keeps trailing zeros, so the two values are equal but report different scales.
- It is defined only for numeric: scale(1.5::float8) fails with function scale(double precision) does not exist. Cast first, and expect the digit count of the float's shortest text form.
- In a NUMERIC(10,2) column every value is coerced to scale 2, so 1.5 is stored as 1.50 and scale() returns 2. Values only differ in scale in unconstrained numeric columns and expressions.
Questions about SCALE
What does scale(1.2300) return?
4. scale() counts the stored digits after the point, trailing zeros included, because numeric keeps them. scale(1.23) would return 2.
Is scale() the same as the column's declared scale?
For a NUMERIC(10,2) column, yes: PostgreSQL pads every value to the declared scale, so 1.5 is stored as 1.50 and scale() returns 2. In an unconstrained numeric column each value keeps its own scale.
What is the equivalent outside PostgreSQL?
There is none built in. Cast to text and count the fractional characters, or carry the scale as data. SQL Server can report the declared scale of an expression's type with SQL_VARIANT_PROPERTY(x, 'Scale'), or of a column through sys.columns.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.