'psql function written in separate file

i'm learning psql in Postgres. My basic question is when i create a function like this one :

CREATE OR REPLACE FUNCTION totalRecords ()
RETURNS integer AS $total$
declare
    total integer;
BEGIN
  SELECT count(*) into total FROM COMPANY;
  RETURN total;
END;
$total$ LANGUAGE plpgsql;

i must write all of the code in the prompt command line. How can i save this code in a script and call it from the command line ? the extentsion of the scirpt must be a .sql ? how can i call this script.



Solution 1:[1]

Save your script to a file. Then execute like this:

psql -p portnumber -d database -U user -f mysqlscrpt.sql 

The extension of the script does not matter.

Solution 2:[2]

@jkdba's answer is sufficient but, alternatively, if you are already logged in the psql console, you can use:

\i <sqlscript>.sql

The \i being for input. \o is output, and it would write to the file instead of bringing it in. I mention this because this is what made me remember the command :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jkdba
Solution 2 xixa