top of page

Mastering Database Connections: How to Connect R to PostgreSQL

connecting R to postgreSQL database

Introduction

Connecting data allows users to establish links between R and external data systems, enabling efficient data retrieval and manipulation for reporting purposes.

To connect R to a PostgreSQL database, follow these steps to set up your environment and establish a connection using the RPostgres or RPostgreSQL packages. This guide assumes you have PostgreSQL installed and running, along with R and RStudio.

Step-by-step connection guide

Install the necessary packages required to connect to PostgreSQL.

installing the required packages

Load the packages into your R session.

loading the packages in R session

Establishing a connection to your PostgreSQL database using the following code.

establishing connection between R and postgreSQL database

(Note, above are the details of my PostgreSQL database locally hosted)

Next, verify if your connection is successful by listing the tables in your database using the following code.

verifying if the connection is successful

Executing the above code, will list all the tables in my database as shown below.

verifying connection by listing the tables in the database

With connection verified, you can now execute SQL commands directly from R. For example, I can retrieve data from the table ‘orders’ using the following code.

using SQL commands to retrieve data from R

Executing this will retrieve data from the table orders as shown below.

example of dataset retrieved from the postgreSQL database

Once you’re done with your database operations, close your connection as follows.

closing your database connection in R

Conclusion

Connecting R to a PostgreSQL database allows you to leverage powerful data manipulation capabilities directly within your statistical analysis workflows. By following these steps, you can easily set up your environment and start interacting with your PostgreSQL databases from R.

If you like the work we do and would like to work with us, drop us an email on our contacts page and we’ll reach out!

Thank you for reading!

Blog.png
bottom of page