1

Hello enter image description here

Here is my erd and the below my creating table codes;

-- This script was generated by the ERD tool in pgAdmin 4. -- Please log an issue at https://redmine.postgresql.org/projects/pgadmin4/issues/new if you find any bugs, including reproduction steps.

BEGIN;


CREATE TABLE IF NOT EXISTS project1."Posts"
(
    post_id serial NOT NULL,
    user_id integer NOT NULL,
    title "char" NOT NULL,
    content text NOT NULL,
    created_at timestamp with time zone NOT NULL,
    PRIMARY KEY (post_id)
);

CREATE TABLE IF NOT EXISTS project1."Comments"
(
    comment_id serial NOT NULL,
    "post_id " integer NOT NULL,
    "user_id " integer NOT NULL,
    "text " text NOT NULL,
    "created_at " timestamp with time zone NOT NULL,
    PRIMARY KEY (comment_id)
);

CREATE TABLE IF NOT EXISTS project1.users
(
    user_id serial NOT NULL,
    username "char" NOT NULL,
    password "char" NOT NULL,
    email "char" NOT NULL,
    PRIMARY KEY (user_id)
);

CREATE TABLE IF NOT EXISTS project1.products
(
    "product_id " serial NOT NULL,
    name "char" NOT NULL,
    price numeric NOT NULL,
    "category_id " integer NOT NULL,
    PRIMARY KEY ("product_id ")
);

CREATE TABLE IF NOT EXISTS project1.orders
(
    "order_id " serial NOT NULL,
    user_id integer NOT NULL,
    "order_date " date NOT NULL,
    "total_amount " numeric NOT NULL,
    PRIMARY KEY ("order_id ")
);

CREATE TABLE IF NOT EXISTS project1."order_items "
(
    item_id serial NOT NULL,
    order_id integer NOT NULL,
    product_id integer NOT NULL,
    quantity integer NOT NULL,
    PRIMARY KEY (item_id)
);

CREATE TABLE IF NOT EXISTS project1.invoices
(
    invoice_id serial NOT NULL,
    order_id integer NOT NULL,
    issued_date date NOT NULL,
    amount_due numeric NOT NULL,
    PRIMARY KEY (invoice_id)
);

CREATE TABLE IF NOT EXISTS project1.reviews
(
    review_id serial NOT NULL,
    product_id integer NOT NULL,
    user_id integer NOT NULL,
    rating integer,
    comment text NOT NULL,
    created_at timestamp with time zone NOT NULL,
    PRIMARY KEY (review_id)
);

ALTER TABLE IF EXISTS project1."Posts"
    ADD FOREIGN KEY (user_id)
    REFERENCES project1.users (user_id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1."Comments"
    ADD FOREIGN KEY ("post_id ")
    REFERENCES project1."Posts" (post_id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1."Comments"
    ADD FOREIGN KEY ("user_id ")
    REFERENCES project1.users (user_id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1.orders
    ADD FOREIGN KEY (user_id)
    REFERENCES project1.users (user_id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1."order_items "
    ADD FOREIGN KEY (order_id)
    REFERENCES project1.orders ("order_id ") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1.invoices
    ADD FOREIGN KEY (order_id)
    REFERENCES project1.orders ("order_id ") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1.reviews
    ADD FOREIGN KEY (product_id)
    REFERENCES project1.products ("product_id ") MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;


ALTER TABLE IF EXISTS project1.reviews
    ADD FOREIGN KEY (user_id)
    REFERENCES project1.users (user_id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
    NOT VALID;

END;

When I am trying to insert this data;

-- Dummy data for project1.users

INSERT INTO project1.users (username, password, email)
VALUES
  ('user1', 'pass123', '[email protected]'),
  ('user2', 'pass456', '[email protected]'),
  ('user3', 'pass789', '[email protected]'),
  ('user4', 'pass101', '[email protected]'),
  ('user5', 'pass202', '[email protected]');

-- Dummy data for project1."Posts"

INSERT INTO project1."Posts" (user_id, title, content, created_at)
VALUES
  (1, 'Post Title 1', 'Content of post 1', NOW()),
  (2, 'Post Title 2', 'Content of post 2', NOW()),
  (3, 'Post Title 3', 'Content of post 3', NOW()),
  (4, 'Post Title 4', 'Content of post 4', NOW()),
  (5, 'Post Title 5', 'Content of post 5', NOW());

-- Dummy data for project1."Comments"

INSERT INTO project1."Comments" ("post_id ", "user_id ", "text ", "created_at ")
VALUES
  (1, 2, 'Comment 1 on Post 1', NOW()),
  (2, 3, 'Comment 2 on Post 2', NOW()),
  (3, 4, 'Comment 3 on Post 3', NOW()),
  (4, 5, 'Comment 4 on Post 4', NOW()),
  (5, 1, 'Comment 5 on Post 5', NOW());

-- Dummy data for project1.products

INSERT INTO project1.products ("product_id ", "name ", "price", "category_id ")
VALUES
  (1, 'Product 1', 10.99, 1),
  (2, 'Product 2', 20.99, 2),
  (3, 'Product 3', 15.99, 1),
  (4, 'Product 4', 25.99, 2),
  (5, 'Product 5', 12.99, 1);

-- Dummy data for project1.orders

INSERT INTO project1.orders ("user_id ", "order_date ", "total_amount ")
VALUES
  (1, '2024-01-02', 50.99),
  (2, '2024-01-03', 30.99),
  (3, '2024-01-04', 45.99),
  (4, '2024-01-05', 35.99),
  (5, '2024-01-06', 22.99);

-- Dummy data for project1."order_items " Sql``` INSERT INTO project1."order_items " (order_id, product_id, quantity) VALUES (1, 1, 2), (2, 3, 1), (3, 5, 3), (4, 2, 2), (5, 4, 1);

-- Dummy data for project1.invoices
```sql
INSERT INTO project1.invoices (order_id, issued_date, amount_due)
VALUES
  (1, '2024-01-03', 50.99),
  (2, '2024-01-04', 30.99),
  (3, '2024-01-05', 45.99),
  (4, '2024-01-06', 35.99),
  (5, '2024-01-07', 22.99);

-- Dummy data for project1.reviews

INSERT INTO project1.reviews (product_id, user_id, rating, comment, created_at)
VALUES
  (1, 2, 4, 'Good product', NOW()),
  (2, 3, 5, 'Excellent product', NOW()),
  (3, 4, 3, 'Average product', NOW()),
  (4, 5, 4, 'Very good product', NOW()),
  (5, 1, 5, 'Outstanding product', NOW());

I keep getting this error;

ERROR: Key (user_id)=(1) is not present in table "users".insert or update on table "Posts" violates foreign key constraint "Posts_user_id_fkey"

ERROR: insert or update on table "Posts" violates foreign key constraint "Posts_user_id_fkey" SQL state: 23503 Detail: Key (user_id)=(1) is not present in table "users".

If anybody can help me with this I would be glad. I just want to remind that I am new to sql and thank you for your time!

1

1 Answer 1

0

You are assuming that the user_id in the userstable is going to start at the value 1. However, this is not guaranteed.

The definition for user_id is to use the data type serial NOT NULL. This data type is defined as:

    |       Name       | Storage Size |           Description           |                                          Range                                           |
    |------------------|--------------|---------------------------------|------------------------------------------------------------------------------------------|
    | smallint         | 2 bytes      | small-range integer             | -32768 to +32767                                                                         |
    | integer          | 4 bytes      | typical choice for integer      | -2147483648 to +2147483647                                                               |
    | bigint           | 8 bytes      | large-range integer             | -9223372036854775808 to +9223372036854775807                                             |
    | decimal          | variable     | user-specified precision, exact | up to 131072 digits before the decimal point; up to 16383 digits after the decimal point |
    | numeric          | variable     | user-specified precision, exact | up to 131072 digits before the decimal point; up to 16383 digits after the decimal point |
    | real             | 4 bytes      | variable-precision, inexact     | 6 decimal digits precision                                                               |
    | double precision | 8 bytes      | variable-precision, inexact     | 15 decimal digits precision                                                              |
    | smallserial      | 2 bytes      | small autoincrementing integer  | 1 to 32767                                                                               |
    | serial           | 4 bytes      | autoincrementing integer        | 1 to 2147483647                                                                          |
    | bigserial        | 8 bytes      | large autoincrementing integer  | 1 to 9223372036854775807                                                                 |

Reference: 8.1. Numeric Types (PostgreSQL | Documentation)

It is auto-incrementing, but the value might not start at 1 and might have gaps. This is mentioned in the same article I referenced:

Because smallserial, serial and bigserial are implemented using sequences, there may be "holes" or gaps in the sequence of values which appears in the column, even if no rows are ever deleted. A value allocated from the sequence is still "used up" even if a row containing that value is never successfully inserted into the table column. This may happen, for example, if the inserting transaction rolls back. See nextval() in Section 9.17 for details.

Problem

You are assuming that inserting 5 users will result in the first user having user_id = 1, the second user having user_id = 2, etc.

Solution

After you have inserted the users in the users table you will have to query the table to retrieve the actual user_id values and insert the correct values in the other insert statements that have a reference to the users table via the user_id column.

Then you shouldn't encounter this error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.