EN VI

Sql - Can I use INSERT statement with select to make a condition?

2024-03-13 14:00:04
Sql - Can I use INSERT statement with select to make a condition?

I want to create an insert but I want to check if the last insert of a table is null. When its null I dont want to insert it.

I have a table named users_ill.

id | user_id | health_at | created_at

Here is my insert statement:

INSERT INTO users_ill (user_id) VALUES ($1);', [user_id]);

But now I want to check also if the health_at is null or not. How can I check this with insert ?

I can also write another query but I think this would be not necessarry when its work with insert and select together.

Solution:

Assuming that the most recent record would be the one with the greatest created_at value, you could use an INSERT INTO ... SELECT as follows:

INSERT INTO users_ill (user_id)
SELECT $1
WHERE NOT EXISTS (
    SELECT 1
    FROM (
        SELECT health_at
        FROM users_ill
        ORDER BY created_at DESC
        LIMIT 1
    ) t
    WHERE health_at IS NULL
)

The inner LIMIT subquery finds the most recent record in the users_ill table. The exists logic then asserts that the health_at value from that most recent record is not null. The insert then would only proceed under the conditions you expect.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login