CREATE SEQUENCE hibernate_sequence START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE FUNCTION next_id(OUT result bigint) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE our_epoch bigint := 1356998400000; -- 1st Jan 2013 00.00.00 hrs GMT milliseconds seq_id bigint; now_millis bigint; shard_id int := 1; BEGIN SELECT nextval('public.hibernate_sequence') % 1024 INTO seq_id; SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis; result := (now_millis - our_epoch) << 15; result := result | (shard_id << 10); result := result | (seq_id); END; $$; CREATE TABLE smaster ( orderid bigint DEFAULT next_id() NOT NULL, custname character varying(200) NOT NULL ); ALTER TABLE ONLY smaster ADD CONSTRAINT smaster_pkey PRIMARY KEY (orderid); CREATE TABLE sdetail ( orderdetailid bigint DEFAULT next_id() NOT NULL, orderid bigint NOT NULL, item character varying(200) NOT NULL, qty integer NOT NULL, rate double precision NOT NULL ); ALTER TABLE ONLY sdetail ADD CONSTRAINT sdetail_pkey PRIMARY KEY (orderdetailid); ALTER TABLE ONLY sdetail ADD CONSTRAINT sfk_orderid FOREIGN KEY (orderid) REFERENCES smaster(orderid);