Connecting Postgres to Google Sheets makes it easy to pull data into a spreadsheet and build connected sheets. This post demonstrates several ways to import Postgres data to Google Sheets and covers the pros and cons of connecting Google Sheets to PostgreSQL.
We also show how Row Zero is a better solution for connecting Postgres to a powerful spreadsheet to work with big Postgres datasets.
- Top 3 ways to connect Google Sheets to Postgres
- Google Sheets Apps Script (10+ steps - hard, but free)
- CSV upload (8 steps - good for one-offs)
- Coefficient (Easier but expensive - $99/month for 5,000+ rows)
- Better solution: Row Zero (4 steps, millions of row)
- Pros and cons of connecting Google Sheets to Postgres
Top 3 Ways to Connect Google Sheets to Postgres
Below we outline 3 ways to connect Postgres to Google Sheets. If you're looking for an easier and more powerful solution, try Row Zero - a much more powerful spreadsheet with a built-in connector to Postgres that connects in seconds.
1. Google Sheets Apps Script
Google Sheets provides an app development functionality within the product, called Apps Script. App Script allows Google Sheets users to build custom features within the product, like menus, sidebars, and other web based apps. App script also includes a native MYSQL protocol through a Java Database Connectivity (JDBC) service. This JDBC service enables connection to databases. The Apps Script + JDBC functionality can be used to connect a Postgres database to Google Sheets. To connect Postgres to Google Sheets using Apps Script, follow the instructions below.
1. Setup the Postgres DSN
The first step in connecting Google Sheets to a Postgres database is to download and install the Postgres ODBC driver. The purpose of the PostgreSQL ODBC driver is to provide a standardized interface for applications to access Postgres databases regardless of the programming language or operating system used by the application.
Download the PostgreSQL ODBC Driver
In order to download the Postgres driver, visit https://odbc.postgresql.org, click on the link to go to the download site and then download the most recent version that matches the version of windows running on your computer (x32, x64, or x86).
Install the PostgreSQL ODBC Driver
Once you've downloaded the correct drive version, unzip or decompress the file in your downloads folder. Inside, you will find an executable file type (e.g. psqlodbc_x64.msi). Double click on the executable to install the driver and follow the steps in the installation wizard.
Configure and Add the PostgreSQL ODBC Driver in Windows
In Windows, go to the start menu and search for 'ODBC Data Sources.' Select and open the ODBC Data Source Administrator.
Navigate to the 'Drivers' tab and look for your PostgreSQL driver in the list. If you don't see it, it has not been installed correctly and you should try repeating the previous step. Assuming your driver is visible in the list, click on the 'User DSN' or 'System DSN' tabs, click 'Add,' select the PostgreSQL driver from the list, and click 'Finish.'
Next add the connection credentials for your postgreSQL database. You will need to match the settings on your database. For example, if the database allows encryption, you will need to toggle the 'SSL Mode' value to match it. Once credentials have been entered, click 'Test' to test the connection. If the Test is successful, click 'Save.' The PostgreSQL driver will now show up in either System DSN or User DSN lists.
2. Install the SQL Gateway
The second step in connecting Google Sheets to your Postgres database is to download and install a SQL Gateway, which can be configured to work with the DSN created in the previous step. A company called CData makes a SQL Gateway, which can be downloaded from their site and configured by following the instructions at CData SQL Gateway. There is an additional page where you can find further instructions about how to configure their SQL Gateway software.
3. Write and run the Appscript code
- Create a new App Script in your Google Sheet using the top menu and selecting Extensions > Apps Script
- When the app script window opens, it will look like the image below. Select and delete the sample 'function myfunction()' and begin using the code provided below. Make sure to replace the example values for your own values in the first code snippet below.
- Next, create a set of variables that identify the database address and login information to be used by the program. Replace the values in green with your own values.
//replace the variables in this block with real Postgres values as needed var address = 'your_host:your_port'; // e.g., 'localhost:5432' var user = 'your_username'; // e.g., 'postgres' var userPwd = 'your_password'; // Your database password var db = 'your_dbname'; // Your database name // JDBC connection string for PostgreSQL var dbUrl = 'jdbc:postgresql://' + address + '/' + db;
- Write a function that will appear in the Google Sheets menu bar and allow you to run in from the UI rather than with code.
// Create a function that adds a menu item to google sheets function onOpen() { var spreadsheet = SpreadsheetApp.getActive(); var menuItems = [{ name: 'Import PostgreSQL Data', functionName: 'importPostgresData' }]; spreadsheet.addMenu('PostgreSQL Data', menuItems); }
- Write a function that will identify the first empty row in a spreadsheet in which to start the import.
/* * Finds the first empty row in a spreadsheet by scanning an array of columns * @return The row number of the first empty row. */ function getFirstEmptyRowByColumnArray(spreadSheet, column) { var columnData = spreadSheet.getRange(column + ':' + column).getValues(); var emptyRowIndex = 0; while (columnData[emptyRowIndex] && columnData[emptyRowIndex][0] != '') { emptyRowIndex++; } return emptyRowIndex + 1; }
- Finally, write a function that will import and write Postgres data to your Google Sheet.
/* * Reads data in a specified Postgres table and then imports it to the specified sheet in your workbook. * (If there is no specified Google Sheet, the function will create one.) */ function importPostgresData() { var thisWorkbook = SpreadsheetApp.getActive(); var selectedSheet = Browser.inputBox( 'Enter the name of the sheet for data import:', Browser.Buttons.OK_CANCEL ); if (selectedSheet === 'cancel') return; if (!thisWorkbook.getSheetByName(selectedSheet)) thisWorkbook.insertSheet(selectedSheet); var resultSheet = thisWorkbook.getSheetByName(selectedSheet); var conn = Jdbc.getConnection(dbUrl, user, userPwd); var table = Browser.inputBox( 'Enter the name of the PostgreSQL table to import:', Browser.Buttons.OK_CANCEL ); if (table === 'cancel') return; var stmt = conn.createStatement(); var results = stmt.executeQuery('SELECT * FROM ' + table); var rsmd = results.getMetaData(); var numCols = rsmd.getColumnCount(); var firstEmptyRow = getFirstEmptyRowByColumnArray(resultSheet, 'A'); if (firstEmptyRow == 1) { var headers = new Array(numCols); for (var i = 0; i < numCols; i++) { headers[i] = rsmd.getColumnName(i + 1); } resultSheet.getRange(1, 1, 1, numCols).setValues([headers]); } var rowNum = firstEmptyRow; while (results.next()) { var row = new Array(numCols); for (var i = 0; i < numCols; i++) { row[i] = results.getString(i + 1); } resultSheet.getRange(rowNum, 1, 1, numCols).setValues([row]); rowNum++; } results.close(); stmt.close(); }
*The entire script can be found at the end of this blog post in the Appendix
- Once all the code has been written or copied from this blog, save the project with the 'Save' icon on the top menu bar. Then run the program. You will be prompted to verify and give access to your Google Account.
- After running the program, you will see a 'Postgres Data' menu option in your Google Sheet
- The first time you run the script, you may be asked to authorize access to your google account. Follow the prompts to complete this step.
- When running the extension, you will first be asked which sheet should receive the imported data. Simply type the sheet name (e.g. 'Sheet1'). If no sheet with that name exists, a new sheet will be created.
- A second question will ask which table should be imported. Type the name of the table in the text box.
- After responding to the questions, the program will import your Postgres data into the Google Sheet you selected. The program can be re-run any time the data needs to be updated with new data in the Postgres database.
2. CSV Upload
The CSV option is simpler and free but is not an actual connection between Postgres and Google Sheets and is a one-time data upload to Google Sheets that will need to be repeated every time the data in the Postgres database changes. Follow the steps below for the CSV upload from Postgres to Google Sheets. Keep in mind that if the CSV being uploaded to Google Sheets is 100,000 or more rows, the program may slow down or crash. In that case, consider using Row Zero, a much more powerful spreadsheet designed for big data.
- Open a SQL editor, like SQL Workbench on your computer.
- Create a new connection. If you haven't already connected to your database, you'll need to set up a new connection. Click File > Connect window, or click the 'Select Connection Profile' icon in the toolbar.
- Enter connection details. Fill in the details for your database connection (such as database type, host, port, database name, user, password) and click 'OK' to establish the connection.
- Open a new SQL tab. If not already open, start a new SQL tab by clicking File > New SQL Tab or the appropriate toolbar icon.
- Write your SQL query. In the new tab, write the SQL query you want to execute. For example:
Copy code SELECT * FROM your_table;
- Execute the query. Run the query by pressing F9 or clicking the 'Execute' button. After the query runs, the results will be displayed in the lower panel of the SQL Workbench window.
- Export to CSV. Right-click on the result set. Choose Export to Clipboard/File. In the export window, set the 'Export Format' to Text (CSV, Tab, ...). Configure the CSV options as desired (e.g., column delimiter, string quote character, filename, etc.). Choose the location where you want to save the CSV file and provide a filename. Click 'OK' to export the data.
- In Google Sheets click on File > Import > Upload > Browse and select the csv file on your computer.
- Repeat the process if data in the Postgres database is updated.
3. Coefficient
Coefficient is a Google Sheets add-on that makes it easy to connect your spreadsheet to a number of different applications. Coefficient offers a free plan that limits import to 5000 rows. The starter plan is $50/mo with the same 5000 row limit and the Pro plan is $99/user/mo and has no import limit, but will be limited by Google Sheets data limits (performance can degrade above 100,000 rows). To use Coefficient to connect Google Sheets to Postgres, follow the steps below.
- Install the Coefficient extension in Google Sheets. If starting from Coefficient's page, follow the instructions with the pop-up menu. If starting from your own Google Sheets workbook, use the top menu and click Extensions > Add-Ons > Get Add-ons. Search for 'Coefficient'. Select Coefficient from the search results and click 'Individual Install'.
- Follow the steps to authenticate your Google account with Coefficent and give the add-on access.
- Launch the application by going to Extensions>Coefficient>Launch.
- Once launched, follow the steps to answer questions and select Postgres as your import source
- Enter your database name, username, password, and an optional nickname. If your Postgres database is behind a firewall or private network, you will need to whitelist the Coefficient IP addresses.
- Once connected, you can use the visual query editor or write your own sql query and click import.
- The data will load into a Google sheet. The data in Google Sheets can be automatically updated every time Postgres data updates if you use a paid tier of Coefficient. Be cognisant of the query result size as Google Sheets has a 10 million cell limit and a file size limit of 100MB.
While Coefficient is a popular choice, there are several additional Google Sheets add-ins that let you connect to Postgres. Simply go to Extensions > Add-Ons > Get Add-ons and search for 'Postgres' to compare options. Note that all add-ins will still be limited by Google Sheets data size limits and may struggle above 100,000 rows.
Ultimately if you need to work with larger datasets or want a much less expensive solution, try Row Zero, which is designed for big data and has a built-in Postgres connector. Row Zero has a free plan that lets you connect to Postgres and paid plans start at $10/month. Read more about using Row Zero as a Coefficient alternative.
Why Row Zero is a better solution
Row Zero is an enterprise-grade spreadsheet designed for big data with built-in connectors to Postgres and other data sources. The free tier easily supports millions of rows and Enterprise plans can support billion row datasets. Row Zero makes it much easier to get data from a Postgres database into a spreadsheet and has more power than Google Sheets to easily handle big data sets and complex analyses. You can also write-back to Postgres from your spreadsheet. To get started, watch the video below or follow the simple instructions to connect Postgres to Row Zero.
1. Connect Row Zero to a PostgreSQL database
In Row Zero click on the 'Data' icon in the top right-hand menu and click 'Add connection'.
The connection requires 6 pieces of information defined below.
- Connection name - This field can be anything that helps identify the data source being connected. (e.g. "Production Data" or "Product Metrics")
- Host - This is the PostgreSQL address that typically takes the form of a string like 'database.mydomain.com.'
- Port - This is often 5432.
- User - This is the username for your PostgreSQL database.
- Password - The password used to log into your PostgreSQL database.
- Database - The name of the PostgreSQL database being connected to.
Once the information is entered, hit 'Test connection' to ensure the information is correct. If the connection icon turns green and says 'Connected', proceed by clicking on '+ Add Source.'
2. Write a query to import data
Now that Postgres is connected to your spreadsheet, click the "+" sign next to your Postgres connection to open a query editor where you can select the 'Schema' and write a SQL query. The easiest query to write is a 'select * from table_name' statement, which pulls in the entire table. Click 'Run' to execute the query and the Postgres data will import into a connected table in your spreadsheet.
3. Build out your Postgres connected spreadsheet
Row Zero works like Excel and Google Sheets and everything you build on top of connected data stays in sync and dynamically updates, including pivot tables, charts, formula functions, etc. Here's more info on how to build connected spreadsheets.
Pros and cons of connecting Postgres to Google Sheets
Pros
Connecting Google Sheets to Postgres offers several benefits for both individuals and teams. Here are some key advantages:
- Live Models and Dashboards: With a live connection between Postgres and Google Sheets, you can build dynamic models, charts, and dashboards that automatically update as new data is added to Postgres.
- Enhanced Data Visualization: Easily visualize Postgres data in Google Sheets with charts, pivot tables, etc.
- Familiar Interface: Google Sheets provides a user-friendly spreadsheet interface for analyzing Postgres data. Connecting Google Sheets to Postgres allows users in operations, marketing, finance, etc. to leverage large, central datasets without the need for extensive training in complex tools.
In summary, connecting Google Sheets to Postgres enhances the accessibility and efficiency of data analysis, offering real-time insights, collaboration opportunities, and a familiar interface for users.
Cons
While there are several positives, there are several drawbacks and limitations of connecting Postgres to Google Sheets including performance limitations, data size limitations, security risks, costs, and overall complexity.
Data and performance limits: Google Sheets isn't designed to work with large datasets so you may not be able to import full Postgres tables into the spreadsheet. Google Sheets has a 10 million cell limit and a file size limit of 100MB. In practice, Google Sheets can slow down or crash above 100,000 rows, especially as you add formulas, formatting, pivot tables, etc.
Security risks: Connecting Google Sheets to production data in Postgres, especially customer data, can pose an information security risk if proper access controls and restrictions are not put in place. Google Sheets workbooks are very easy to share, copy, download, and email which can lead to data leakage if not managed correctly. If data security is a priority for your organization, consider using Row Zero to connect to Postgres. Row Zero is specifically designed for enterprise security and gives organizations advanced access controls and the ability to restrict sharing, export, and copy/paste. Learn more about these enterprise security features here.
Complexity: Connecting Google Sheets to Postgres using Google Apps Script takes a lot of steps and is pretty daunting for non-technical users. Some Google Sheets add-ins make the process easier, but also add another layer to your tech stack, which has both cost and data governance implications. If you need an easy way to connect Postgres to a spreadsheet, try Row Zero, which has a built-in Postgres connector and is specifically designed to connect to data sources and work with big data.
Cost: While Google Sheets add-ins offer an easier way to connect to Postgres, they can add considerable costs. For example, Coefficient costs $99 per user per month if you want to import more than 5,000 rows.
Conclusion
There are several options for connecting PostgreSQL to Google Sheets, depending on your goals. For one-off tasks CSV upload is probably the easiest. For recurring reports and analysis, you'll want to set up a true connection to Postgres using ODBC drivers or an add-in like Coefficient. If you need a more powerful and cost-effective solution that scales with growing data, consider using Row Zero. Row Zero is dramatically more powerful and faster than Google Sheets for big datasets and it is significantly less expensive than Coefficient and other Postgres connectors. Row Zero's built-in Postgres connector makes it easy to get set up in a few steps.
If you use another cloud data warehouse or blob storage, Row Zero also connects to Snowflake, Databricks, Redshift, BigQuery, and S3.
Related Content
- Connect Google Sheets to Snowflake
- Connect Google Sheets to Redshift
- Connect Google Sheets to Databricks
- Import CSV to Postgres
- Connect Excel to Postgres
Appendix
// Replace with your PostgreSQL database details var address = 'your_host:your_port'; // e.g., 'localhost:5432' var user = 'your_username'; // e.g., 'postgres' var userPwd = 'your_password'; // Your database password var db = 'your_dbname'; // Your database name // JDBC connection string for PostgreSQL var dbUrl = 'jdbc:postgresql://' + address + '/' + db; // Create a menu function function onOpen() { var spreadsheet = SpreadsheetApp.getActive(); var menuItems = [{ name: 'Import PostgreSQL Data', functionName: 'importPostgresData' }]; spreadsheet.addMenu('PostgreSQL Data', menuItems); } // Create a function that adds a menu item to google sheets function onOpen() { var spreadsheet = SpreadsheetApp.getActive(); var menuItems = [{ name: 'Import PostgreSQL Data', functionName: 'importPostgresData' }]; spreadsheet.addMenu('PostgreSQL Data', menuItems); } /* * Finds the first empty row in a spreadsheet by scanning an array of columns * @return The row number of the first empty row. */ function getFirstEmptyRowByColumnArray(spreadSheet, column) { var columnData = spreadSheet.getRange(column + ':' + column).getValues(); var emptyRowIndex = 0; while (columnData[emptyRowIndex] && columnData[emptyRowIndex][0] != '') { emptyRowIndex++; } return emptyRowIndex + 1; } /* * Reads data in a specified Postgres table and then imports it to the specified sheet in your workbook. * (If there is no specificed Google Sheet, the function will create one.) */ function importPostgresData() { var thisWorkbook = SpreadsheetApp.getActive(); var selectedSheet = Browser.inputBox( 'Enter the name of the sheet for data import:', Browser.Buttons.OK_CANCEL ); if (selectedSheet === 'cancel') return; if (!thisWorkbook.getSheetByName(selectedSheet)) thisWorkbook.insertSheet(selectedSheet); var resultSheet = thisWorkbook.getSheetByName(selectedSheet); var conn = Jdbc.getConnection(dbUrl, user, userPwd); var table = Browser.inputBox( 'Enter the name of the PostgreSQL table to import:', Browser.Buttons.OK_CANCEL ); if (table === 'cancel') return; var stmt = conn.createStatement(); var results = stmt.executeQuery('SELECT * FROM ' + table); var rsmd = results.getMetaData(); var numCols = rsmd.getColumnCount(); var firstEmptyRow = getFirstEmptyRowByColumnArray(resultSheet, 'A'); if (firstEmptyRow == 1) { var headers = new Array(numCols); for (var i = 0; i < numCols; i++) { headers[i] = rsmd.getColumnName(i + 1); } resultSheet.getRange(1, 1, 1, numCols).setValues([headers]); } var rowNum = firstEmptyRow; while (results.next()) { var row = new Array(numCols); for (var i = 0; i < numCols; i++) { row[i] = results.getString(i + 1); } resultSheet.getRange(rowNum, 1, 1, numCols).setValues([row]); rowNum++; } results.close(); stmt.close(); }