Level Up Your PostgreSQL Game: Running SQL Queries in VSCode

Level Up Your PostgreSQL Game: Running SQL Queries in VSCode

If you’re like me, you probably love keeping everything in one place, especially when you’re writing and running SQL queries. Instead of hopping between tools like pgAdmin or DBeaver or ValentinaDB, wouldn’t it be awesome to manage your PostgreSQL database directly from VSCode? Well, the good news is you can do just that using an extension called SQLTools.

Here’s a step-by-step guide to get you connected and running queries effortlessly.

Step 1: Install SQLTools in VSCode

First things first, let’s install the SQLTools extension. Open VSCode, go to the Extensions view (Cmd + Shift + X), and search for SQLTools. Click Install and you’re halfway there!

Step 2: Get the SQLTools PostgreSQL Driver

Once SQLTools is installed, you’ll need to grab the SQLTools PostgreSQL/CockroachDB Driver (yes, it supports both databases!). Head back to the Extensions view and search for this driver, then install it. This driver will allow SQLTools to connect to your PostgreSQL database.

Step 3: Set Up Your PostgreSQL Connection

Now let’s set up your connection. In VSCode, look for the SQLTools icon on the left sidebar and click it. You’ll see an option to add a new connection. Select PostgreSQL as your driver and fill in the necessary details:

  • Name: Any friendly name you want (like MyPostgresDB).
  • Server: Usually localhost if it’s running on your machine.
  • Port: Default is 5432.
  • Database: Your database name (e.g., mydatabase).
  • Username: Your PostgreSQL username (e.g., postgres).
  • Password: Your password.

Hit Test Connection to make sure everything works. Once it’s successful, click Save.

Step 4: Running SQL Queries

Now, you can open a .sql file in VSCode, write some queries, and run them! But wait… instead of using the mouse every time you want to execute a query, why not use keyboard shortcuts?

By default, SQLTools runs queries using Cmd + Enter on Mac . But if you want to customize the shortcut to something else, like Shift + Enter, here’s how you do it:

  1. Open the Keyboard Shortcuts: Press Cmd + K followed by Cmd + S.
  2. Search for Run Active Query: This is the command for executing queries.
  3. Change Keybinding: Right-click on the SQLTools: Run Active Query and select Change Keybinding. Press your desired shortcut (like Shift + Enter) and hit Enter to save.

That’s it! Now, whenever you write a query, just hit your custom keybinding to run it instantly. No need to fiddle with the mouse.

Quick Example

Let’s say you’ve got a simple query like this:

SELECT usename FROM pg_user WHERE usename LIKE '%p';

With your keyboard shortcut set, just place the cursor on the query and press Cmd + Enter (or whatever shortcut you chose), and your results will pop up right there in VSCode.

Give it a try, and happy querying!

vamsi manyam Avatar