w3resource

How to Create a PostgreSQL Function to Square a Number


Function to Calculate the Square of a Number

Write a PostgreSQL function that takes an integer as input and returns its square.

Solution:

-- Create a function named square_number that takes an integer as input and returns an integer
CREATE FUNCTION square_number(n INT) RETURNS INT AS $$
BEGIN
-- Return the square of the input number
RETURN n * n;
END;
-- Specify the language used in the function as PL/pgSQL
$$ LANGUAGE plpgsql;

Explanation:

  • Purpose of the Query:
    • This function computes the square of a given integer.
  • Key Components:
    • CREATE FUNCTION square_number(n INT) RETURNS INT → Defines a function that accepts an integer and returns an integer.
    • RETURN n * n; → Multiplies n by itself to compute the square.
  • Real-World Application:
    • Useful in mathematical calculations, physics simulations, and financial applications.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL function that returns the cube of a given number.
  • Write a PostgreSQL function that calculates the absolute difference between two integers.
  • Write a PostgreSQL function that squares a number only if it is even, otherwise returns -1.
  • Write a PostgreSQL function that returns the square root of a number rounded to two decimal places.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous PostgreSQL Exercise: Create a Simple Function to Return a Constant Value.
Next PostgreSQL Exercise: Function to Get Employee Full Name.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.