w3resource

Writing a PostgreSQL Function to check Even or Odd Numbers


Function to Check if a Number is Even or Odd

Write a PostgreSQL function that checks if a number is even or odd and returns a corresponding message.

Solution:

-- Create a function named check_even_odd that takes an integer as input and returns a text value
CREATE FUNCTION check_even_odd(n INT) RETURNS TEXT AS $$
BEGIN
    -- Check if the number is even by using the modulo operator
    IF n % 2 = 0 THEN
        -- Return 'Even' if the number is even
        RETURN 'Even';
    ELSE
        -- Return 'Odd' if the number is odd
        RETURN 'Odd';
    END IF;
END;
-- Specify the language used in the function as PL/pgSQL
$$ LANGUAGE plpgsql;

Explanation:

  • Purpose of the Query:
    • Determines whether a given number is even or odd.
  • Key Components:
    • IF n % 2 = 0 THEN RETURN 'Even'; ELSE RETURN 'Odd'; → Checks divisibility by 2
  • Real-World Application:
    • Useful in game development, analytics, and statistical applications.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL function that checks if a number is prime.
  • Write a PostgreSQL function that returns "Positive" or "Negative" based on the input number.
  • Write a PostgreSQL function that checks if a number is a multiple of both 3 and 5.
  • Write a PostgreSQL function that determines if a number is odd and greater than 100.


Go to:


PREV : Function to Get Employee Full Name.
NEXT : Function to Calculate Factorial of a Number.

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

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.