- Import CSV File Into PostgreSQL Table
- Import a CSV file into a table using COPY statement
- Import CSV file into a table using pgAdmin
- How to Import CSVs to PostgreSQL Using PgAdmin
- What Is a CSV file?
- Why Import CSV Files into a Database?
- PostgreSQL and pgAdmin
- How to Import CSVs to PostgreSQL
- 1. Create a Table in pgAdmin
- 2. Import the CSV file
- Well, Importing a CSV file to a Postgres Database Was Easy!
- Импорт и экспорт данных в PostgreSQL, гайд для начинающих
- 1. Импорт базы данных в формате в PostgreSQL
- 2. Импорт данных из csv-файла
- 3. Экспорт данных в .csv-файл
- 4. Экспорт данных выборки в .csv-файл
Import CSV File Into PostgreSQL Table
Summary: in this tutorial, we will show you various ways to import a CSV file into a PostgreSQL table.
First, create a new table named persons with the following columns:
- id : the person id
- first_name : first name
- last_name: last name
- dob date of birth
- email : the email address
Second, prepare a CSV data file with the following format:
The path of the CSV file is as follows: C:\sampledb\persons.csv
Import a CSV file into a table using COPY statement
To import this CSV file into the persons table, you use COPY statement as follows:
PostgreSQL gives back the following message:
It means that two rows have been copied. Let’s check the persons table.
It works as expected.
Let’s dive into the COPY statement in more detail.
First, you specify the table with column names after the COPY keyword. The order of the columns must be the same as the ones in the CSV file. In case the CSV file contains all columns of the table, you don’t need to specify them explicitly, for example:
Second, you put the CSV file path after the FROM keyword. Because CSV file format is used, you need to specify DELIMITER as well as CSV clauses.
Third, specify the HEADER keyword to indicate that the CSV file contains a header. When the COPY command imports data, it ignores the header of the file.
Notice that the file must be read directly by the PostgreSQL server, not by the client application. Therefore, it must be accessible by the PostgreSQL server machine. Also, you need to have superuser access in order to execute the COPY statement successfully.
Import CSV file into a table using pgAdmin
In case you need to import a CSV file from your computer into a table on the PostgreSQL database server, you can use the pgAdmin.
The following statement truncates the persons table so that you can re-import the data.
First, right-click the persons table and select the Import/Export… menu item:
Second, (1) switch to import, (2) browse to the import file, (3) select the format as CSV, (4) select the delimiter as comma ( , ):
Third, click the columns tab, uncheck the id column, and click the OK button:
Finally, wait for the import process to complete. The following shows the dialog that inform you the progress of the import:
In this tutorial, you have learned how to import data from a CSV file into a table on the PostgreSQL database server using the COPY statement and pgAdmin tool.
How to Import CSVs to PostgreSQL Using PgAdmin
Do you work with data and use CSV files? Here is a practical guide on how to import such files into a PostgreSQL database using pgAdmin, one of the best PostgreSQL editors on the market.
Let’s get right into importing CSVs into a Postgres database. We’ll start by explaining what a CSV file is, then we’ll introduce you to pgAdmin and show you how to do the import process. Don’t worry – it’s easy!
What Is a CSV file?
CSV is short for comma-separated values. It is a format for storing data in text files. This standard is supported by many applications and programs, including Microsoft Office, LibreOffice, and Google Sheets.
Why Import CSV Files into a Database?
When are CSV files used? Transferring data from one program or platform to another is a main use. Imagine that you need to export data from a database to a spreadsheet or vice versa. CSVs are the surest way to save your data; they are read by almost all office suites and database management systems (DBMSs). In addition, CSVs are text files and thus are quite small; transferring even large data sets is not a problem. That’s a huge advantage to using CSVs.
Have a look at the differences between storing data in a table and storing it in a CSV. Here is a table called characters . I wonder if you recognize the data I put there.
ID | first_name | last_name | family |
---|---|---|---|
1 | John | Snow | Targaryen |
2 | Arya | Stark | Stark |
3 | Tyrion | Lannister | Lannister |
Here’s the same information in CSV format:
This is a very tiny data set, but you can imagine what it would be like with many columns and thousands of rows. I think you understand the uses and advantages of CSVs, so let’s move on to the tool we’ll use to import them: pgAdmin.
PostgreSQL and pgAdmin
Some time ago, my friend Ignacio showed you how to install and set up PostgreSQL on Windows 10. If you’ve read that article, you know that Postgres is easy to set up and one of the most popular DBMSs in the world.
There are tons of different SQL editors on the market that support PostgreSQL. I got used to pgAdmin and honestly I don’t see any point in changing to anything else. It’s a great tool that has never let me down.
What is pgAdmin? It is a graphical PostgreSQL database management program. Its latest version is pgAdmin 4. It may be used on Linux, Unix, macOS, or Windows, and because it is open-source, it’s free. This will be an important argument for many people. Full functionality and no fees make pgAdmin perfect for me. And maybe for you, too.
PgAdmin allows you to administer databases and their replicas, create all database objects, issue queries, and analyze the query plan (presented in classic or graphic form). You can also use the classic console to write in it. Plus, there are many extensions that allow you to freely adapt the program to your needs.
Alternatives to pgAdmin include DBeaver, Navicat, HeidiSQL, and OmniDB. If you would like me to devote an article to the various SQL editors out there – including those for PostgreSQL databases – let me know in the comments.
I assume that you already have Postgres and pgAdmin installed on your computer and that you have them set appropriately. Now we can get down to business and import some data.
How to Import CSVs to PostgreSQL
Let’s go back to our characters.csv file and try to import it into our database via pgAdmin. There are two methods, and I will show you what to do step by step.
1. Create a Table in pgAdmin
Using the internal Query Tool in pgAdmin, you can first create a table with an SQL query:
Make sure the columns have the same names and values as those in the CSV file.
Instead of writing a SQL Query, you can also right-click on Tables in the tree on the left. A short menu will appear. Select Create and then Table. .
A new window will pop up asking you to enter a name for the new table. In our case, it will be characters .
In the same window, click on the Columns tab and add the appropriate columns by clicking the + button. Remember that column names must match those in the CSV file. You’ll also need to specify the data type that each column will contain.
If you don’t know what data types to enter, I recommend taking the LearnSQL.com Data Types in SQL course. It’s better to learn the basics and avoid making mistakes. We know what data we want to include in each column, so everything should look like this:
Notice that you can set the column to be non-NULL and specify a primary key here as well. By clicking SQL, you can view the SQL query used to create the table. For now, we won’t worry about the other (more advanced) features here.
When you are done, click Save. You just created a table! If you don’t see it in the tree, right-click on Tables and select Refresh. It should appear.
2. Import the CSV file
Again, you can use the Query Tool and type an SQL query. Use the COPY statement for this:
In the first line, enter the name of your table. In the second line (after the FROM clause), enter the path to your file. In my case, it is the C drive and the a folder. Important: you need to specify the DELIMITER , which is the character used to separate the values in the CSV file. It’s usually a comma, but it can be a semi-colon, a space, or something else.
Finally, use the HEADER keyword to skip the header (i.e the row containing the column names) when copying data from the CSV.
In our case, the result is a COPY 3 message. This means that pgAdmin copied three rows into our table. Let’s enter a simple query to check that everything worked:
Of course, as in the case when creating a table as well as importing data from a CSV file, we can skip the query and use the program itself. To do this, simply right-click on your table in the tree on the left and select the Import/Export… menu item.
A window will appear with the slider set to Import. Then select the source file and set the format to CSV. Set the Header to Yes if your file has a header. The only thing left is to select the delimiter (usually a comma). Your window should look like this:
When you click OK, the data will be imported. And your table is ready! Now you can write SQL queries and analyze data, combine data from other tables, etc. Welcome to the other side of the mirror, Alice! You successfully followed the White Rabbit.
Well, Importing a CSV file to a Postgres Database Was Easy!
That’s how simple it is to import data from a CSV file into a PostgreSQL database with pgAdmin. There are two ways you can do this – by using the program itself, and by using SQL in the Query Tool and the COPY statement. I use pgAdmin because it’s a great tool for working with PostgreSQL. What IDE are you using? Tell us in the comments.
If you are a complete beginner to PostgreSQL, I encourage you to take our SQL Basics in PostgreSQL course or SQL from A to Z in PostgreSQL (the main track for this dialect). These are brilliant, interactive SQL courses that will teach you everything you need to work effectively with databases. Don’t fall behind; the world is betting on PostgreSQL, including lots of big companies. Why not give it a try?
Импорт и экспорт данных в PostgreSQL, гайд для начинающих
В процессе обучения аналитике данных у человека неизбежно возникает вопрос о миграции данных из одной среды в другую. Поскольку одним из необходимых навыков для аналитика данных является знание SQL, а одной из наиболее популярных СУБД является PostgreSQL, предлагаю рассмотреть импорт и экспорт данных на примере этой СУБД.
В своё время, столкнувшись с импортом и экспортом данных, обнаружилось, что какой-то более-менее структурированной инфы мало: этот момент обходят на всяких там курсах по аналитике, подразумевая, что это очень простые моменты, которым не следует уделять внимание.
В данной статье приведены примеры импорта в PostgreSQL непосредственно самой базы данных в формате sql, а также импорта и экспорта данных в наиболее простом и распространенном формате .csv, в котором в настоящее время хранятся множество существующих датасетов. Формат .json хоть и является также очень распространенным, рассмотрен не будет, поскольку, по моему скромному мнению, с ним все-таки лучше работать на Python, чем в SQL.
1. Импорт базы данных в формате в PostgreSQL
Скачиваем (получаем из внутреннего корпоративного источника) файл с базой данных в выбранную папку. В данном случае путь:
Имя файла: demo-big-20170815
Далее понадобиться командная строка windows или SQL shell (psql). Для примера воспользуемся cmd. Переходим в каталог, где находится скачанная БД, командой cd C:\Users\User-N\Desktop\БД :
Далее выполняем команду для загрузки БД из sql-файла:
«C:\Program Files\PostgreSQL\10\bin\psql» -U postgres -f demo-big-20170815.sql
Где сначала указывается путь, по которому установлен PostgreSQL на компьютере, -U – имя пользователя, -f — название файла БД.
Отметим, что в зависимости от размера базы данных загрузка может занимать до нескольких десятков минут. Конец загрузки будет отмечен следующим видом:
Заходим в pgAdmin и наблюдаем там импортированную БД:
2. Импорт данных из csv-файла
Предполагается, что у вас уже есть необходимый .csv-файл, и первое, что нужно сделать, это перейти pgAdmin и создать там новую базу данных. Ну или воспользоваться уже существующей, в зависимости от текущих нужд. В данном случае была создана БД airtickets.
В выбранной БД создается таблица с полями, типы которых должны соответствовать «колонкам» в выбранном .csv-файле.
Далее воспользуемся SQL shell (psql) для подключения к нужной БД и для подачи команд на импорт данных. При открытии SQL shell (psql) она стандартно спросит про имя сервера, имя подключаемой БД, порт и пользователя. Ввести нужно только имя БД и пароль пользователя, всё остальное проходим нажатием ентра. Создается подключение к нужной БД – airtickets.
Ну и вводим команды на импорт данных из файла:
\COPY tickets FROM ‘C:\Users\User-N\Desktop\CSV\ticket_dataset_MOW.csv’ DELIMITER ‘,’ CSV HEADER;
Где tickets – название созданной в БД таблицы, из – путь, где хранится .csv-файл, DELIMITER ‘,’ – разделитель, используемый в импортируемом .csv-файле, сам формат файла и HEADER , указывающий на заголовки «колонок».
Один интересный момент. Написание команды COPY строчными (маленькими) буквами привело к тому, что psql ругнулся, выдал ошибку и предложил написать команду прописными буквами.
Заходим в pgAdmin и удостоверяемся, что данные были загружены.
3. Экспорт данных в .csv-файл
Предположим, нам надо сохранить таблицу airports_data из уже упоминаемой выше БД demo.
Для этого подключимся к БД demo через SQL shell (psql) и наберем команду, указав уже знакомые параметры разделителя, типа файла и заголовка:
\COPY airports_data TO ‘C:\Users\User-N\Desktop\CSV\airports.csv’ DELIMITER ‘,’ CSV HEADER;
Существует и другой способ экспорта через pgAdmin: правой кнопкой мыши по нужной таблице – экспорт – указание параметров экспорта в открывшемся окне.
4. Экспорт данных выборки в .csv-файл
Иногда возникает необходимость сохранить в .csv-файл не полностью всю таблицу, а лишь некоторые данные, соответствующие некоторому условию. Например, нам нужно из БД demo таблицы flights выбрать поля flight_id, flight_no, departure_airport, arrival_airport, где departure_airport = ‘SVO’. Данный запрос можно вставить сразу в команду psql: