4

What is the easiest way to query from .csv file ?

Ex: I have a list of 1000 email addresses in emails.csv file.

I want to query all users with emails that are in emails.csv file ex:

SELECT * 
FROM users 
WHERE email IN (emails.csv)

Is there a way to do like this something or I need to create a script. If some script is needed, can you please provide some example.

2
  • you need to create a table and copy it from csv Commented Jan 31, 2018 at 14:25
  • 1
    If the file is located on the databases server, you could use a it through the file_fdw extension Commented Jan 31, 2018 at 14:40

1 Answer 1

5

you need to create a table and copy it from csv, smth like:

t=# create table csv(i int,email text);
CREATE TABLE
t=# copy csv(email) from stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> q
>> w
>> \.
COPY 2
t=# select * from csv;
 i | email
---+-------
   | q
   | w
(2 rows)

but In your case you copy from file, not STDIN, eg

copy csv(email) from '/path/to/file';
Sign up to request clarification or add additional context in comments.

3 Comments

hmm I don't think the company wants to add a table for this purpose. Thanks anyway for the suggestion
@Fi3n1k: well, queries can only work with tables. There is no way you can use those CSV values unless you create some kind of table. You could put it into a temporary table if you want
Depending on your case, you could use the CREATE TEMPORARY TABLE command to create a table that will only be accessible to the current transaction and will cease to exist when the transaction is over. There are plenty of tricks that can be used on top of that one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.