I have a text file with primary keys. Each line contains one primary key. Now I want to select the rows based on the input file. I can not find the right option for psql to do this. What is the canonical way for PostgreSQL to do this job?

I know I can do

psql -c 'select * from table' db | grep -f primary_keys

But this dumps the whole database. How can I avoid it?

1 Answer 1


This assumes you are on a shell and have the tr command in the PATH:

psql -c "SELECT * FROM mytable WHERE id IN (`tr '\n' , <file`NULL)"

Every newline character is replaced with ,, and the NULL in the end takes care of the final comma.

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.