Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

select query help

select query help

select query help


Hi all

I'm trying to do a simple select in postgresql, something like this

if not exists (select 1 from table where a = 'blah')
insert into table values ('a','b','c')

What i'm trying to do is to see whether a value already exists in a table, if it doens't i want to insert the value

But when i do this in query analyser if gives me an error on the if

Can anyone help me with this


RE: select query help

You need to do this as a stored procedure.

RE: select query help

If you're using a language that allows you to handle the error you could just do the insert. If you get a duplicat key error you could handle it in whatever way is appropriate for tha application.

We usually do a select first (with the new key) and then check the number of fields returned. If 0, then we do the insert.


RE: select query help

you have to write it as a function with plpgsql language for example

but the thing you tried is in a wrong direction, because if two oparations appear at the same time, they both will put that data

better, do it with unique constraint, and just insert the constraint will forbid two duplicate rows

the other way is with some kind of locking of the row with SELECT ... FOR UPDATE for example

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close