Search code examples
sqlpostgresqlsql-functionpgadmin-4

Random Double Function - POSTGRESQL


I'm trying to write a function that takes a minimum and a maximum input and returns a double.

Inputs:

high (integer)
low (integer)

Output:

val (double)

My SQL code is:

CREATE OR REPLACE FUNCTION random_between(low INT ,high INT) 
   RETURNS DOUBLE AS

BEGIN
   RETURN floor(random()* (high-low + 1) + low);
END;

The error:

ERROR: syntax error at or near "BEGIN"


Solution

  • You could write this as pure SQL function, like so:

    create or replace function random_between(low int ,high int) 
    returns double precision as $$
        select floor(random()* (high-low + 1) + low);
    $$ language sql;
    

    Problems with your code:

    • the body of the function needs to be surrounded with single quotes (or something equivalent, such as $$)

    • there is no double datatype in Postgres; maybe you meant double precision; note, however, that this is an inexact datatype: this might, or might not be what you want, but make sure that you understand the implications

    • you need to specify the language of the function