Use data-modifying CTEs:
WITH ins1 AS (
INSERT INTO sample(firstname, lastname)
VALUES ('fai55', 'shaggk')
-- ON CONFLICT DO NOTHING -- optional addition in Postgres 9.5+
RETURNING id AS user_id
)
, ins2 AS (
INSERT INTO sample1 (user_id, adddetails)
SELECT user_id, 'ss' FROM ins1
-- RETURNING user_id -- only if used in turn
)
INSERT INTO sample2 (user_id, value) -- same here
SELECT user_id, 'ss' FROM ins1;
Each INSERT depends on the one before. SELECT instead of VALUES makes sure nothing is inserted in subsidiary tables if no row is returned from a previous INSERT. (Related: the ON CONFLICT clause in Postgres 9.5+)
It's also a bit shorter and faster this way.
Typically, it's more convenient to provide complete data rows in one place:
WITH data(firstname, lastname, adddetails, value) AS (
VALUES -- provide data here
(text 'fai55', text 'shaggk', text 'ss', text 'ss2') -- see below
-- more? -- works for multiple input rows
)
, ins1 AS (
INSERT INTO sample (firstname, lastname)
SELECT firstname, lastname FROM data -- DISTINCT? see below
ON CONFLICT DO NOTHING -- requires UNIQUE constraint
RETURNING firstname, lastname, id AS sample_id
)
, ins2 AS (
INSERT INTO sample1 (sample_id, adddetails)
SELECT sample_id, adddetails
FROM data
JOIN ins1 USING (firstname, lastname)
RETURNING sample_id, user_id
)
INSERT INTO sample2 (user_id, value)
SELECT user_id, value
FROM data
JOIN ins1 USING (firstname, lastname)
JOIN ins2 USING (sample_id);
You may need explicit type casts in a stand-alone VALUES expression. As opposed to a VALUES expression attached to an INSERT, where data types are derived from the target table.
If multiple rows can come with identical (firstname, lastname), you may need to fold duplicates for the first INSERT:
...
INSERT INTO sample (firstname, lastname)
SELECT DISTINCT firstname, lastname FROM data
...
You could use a (temporary) table as data source instead of the CTE data.
Related, with more details: