PostgreSQL SIGN() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL SIGN()
function to determine the sign of a number.
Introduction to the PostgreSQL SIGN() function
The SIGN()
function allows you to determine the sign of a number.
Here’s the syntax of the SIGN()
function:
The SIGN()
function accepts a numeric value (numeric_value
) and returns -1 if the value is negative, 0 if the value is zero, and 1 if the value is positive. Additionally, it returns NULL
if the value is NULL
.
The SIGN()
function can be handy when you’re working with financial data, performing mathematical calculations, or handling data validation activities.
PostgreSQL SIGN() function examples
Let’s explore some examples of using the SIGN()
function.
1) Basic SIGN() function example
The following example uses the SIGN()
function to get the sign of various numbers:
Output:
The SIGN()
returns -1 for -10, 0 for 0, 1 for 10, and NULL
for NULL
.
2) Using the SIGN() function with table data
First, create a table called sales
to store the sales amount by year:
Second, insert rows into the sales
table:
Third, compare the sales of a year with the previous year and use the SIGN()
function to output the sales trend:
Output:
How it works.
- Use the
LAG()
window function to retrieve thesales_amount
from the previous year utilizing theORDER
BY
year clause to specify the order of rows. - Use the
CASE
expression to evaluate each row’s sales data and assign a corresponding value to thesales_trend
column.
If you want to reuse the result of the LAG() function, you can use a common table expression:
Summary
- Use the
SIGN()
function to determine the sign of a number.