w3resource

Create a PostgreSQL Function that returns a Fixed String


Create a Simple Function to Return a Constant Value

Write a PostgreSQL function that returns the string "Hello, PostgreSQL!" when called.

Solution:

-- Create a function named greet_message
CREATE FUNCTION greet_message() RETURNS TEXT AS $$
BEGIN
-- Return the constant string 'Hello, PostgreSQL!'
RETURN 'Hello, PostgreSQL!';
END;
-- Specify the language used in the function as PL/pgSQL
$$ LANGUAGE plpgsql;

Explanation:

  • Purpose of the Query:
    • This function demonstrates how to define a PL/pgSQL function that returns a fixed value.
    • It is useful for testing function creation and execution.
  • Key Components:
    • CREATE FUNCTION greet_message() → Defines a function named greet_message.
    • RETURNS TEXT → Specifies that the function returns a TEXT value.
    • RETURN 'Hello, PostgreSQL!'; → The function always returns this string.
  • Real-World Application:
    • This could be used for system messages or notifications in a database application.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL function that returns the number 100 every time it is called.
  • Write a PostgreSQL function that always returns the current database name.
  • Write a PostgreSQL function that returns a hardcoded JSON object containing a name and age.
  • Write a PostgreSQL function that returns the sum of two hardcoded numbers (e.g., 15 and 25) without taking any input.


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

Previous PostgreSQL Exercise: Writing PL/pgSQL functions Home.
Next PostgreSQL Exercise: Function to Calculate the Square of a Number.

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.