Случайная временная отметка

Функция с двумя временными отметками:

=> CREATE FUNCTION rnd_timestamp(t_start timestamptz, t_end timestamptz)
RETURNS timestamptz
AS $$
SELECT t_start + (t_end - t_start) * random();
$$ VOLATILE LANGUAGE sql;
CREATE FUNCTION
=> SELECT current_timestamp,
    rnd_timestamp(current_timestamp, current_timestamp + interval '1 hour')
FROM generate_series(1,10);
              now              |         rnd_timestamp         
-------------------------------+-------------------------------
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:00:54.677569+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:35:47.672671+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:15:31.388326+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:21:09.202394+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:10:11.572123+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:26:54.926134+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:51:32.249848+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:27:35.946782+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:04:02.164987+03
 2017-09-01 15:54:43.080408+03 | 2017-09-01 16:17:01.101458+03
(10 rows)

Вторую функцию (с параметром-интервалом) можно определить через первую:

=> CREATE FUNCTION rnd_timestamp(t_start timestamptz, t_delta interval)
RETURNS timestamptz
AS $$
SELECT rnd_timestamp(t_start, t_start + t_delta);
$$ VOLATILE LANGUAGE sql;
CREATE FUNCTION
=> SELECT rnd_timestamp(current_timestamp, interval '1 hour');
         rnd_timestamp         
-------------------------------
 2017-09-01 16:09:56.838673+03
(1 row)

Автомобильные номера

Создадим таблицу с номерами.

=> CREATE TABLE cars(
    id serial PRIMARY KEY,
    regnum text
);
CREATE TABLE
=> INSERT INTO cars(regnum) VALUES ('К 123 ХМ'), ('k123xm'), ('A 098BC');
INSERT 0 3

Функция нормализации:

=> CREATE FUNCTION normalize(regnum text) RETURNS text
AS $$
SELECT upper(translate(regnum, 'АВЕКМНОРСТУХ ', 'ABEKMHOPCTYX'));
$$ IMMUTABLE LANGUAGE sql;
CREATE FUNCTION
=> SELECT normalize(regnum) FROM cars;
 normalize 
-----------
 K123XM
 K123XM
 A098BC
(3 rows)

Теперь легко найти дубликаты:

=> CREATE FUNCTION num_unique() RETURNS bigint
AS $$
SELECT count(DISTINCT normalize(regnum))
FROM cars;
$$ STABLE LANGUAGE sql;
CREATE FUNCTION
=> SELECT num_unique();
 num_unique 
------------
          2
(1 row)

Корни квадратного уравнения

=> CREATE FUNCTION square_roots(a float, b float, c float, x1 OUT float, x2 OUT float)
AS $$
WITH discriminant(d) AS (
    SELECT b*b - 4*a*c
)
SELECT CASE WHEN d >= 0.0 THEN (-b + sqrt(d))/2/a END,
       CASE WHEN d >  0.0 THEN (-b - sqrt(d))/2/a END
FROM discriminant;
$$ IMMUTABLE LANGUAGE sql;
CREATE FUNCTION
=> SELECT square_roots(1,  0, -4);
 square_roots 
--------------
 (2,-2)
(1 row)

=> SELECT square_roots(1, -4,  4);
 square_roots 
--------------
 (2,)
(1 row)

=> SELECT square_roots(1,  1,  1);
 square_roots 
--------------
 (,)
(1 row)