Bird
Raised Fist0
Node.jsframework~20 mins

PostgreSQL connection with pg in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PostgreSQL pg Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
📝 Syntax
intermediate
2:00remaining
Identify the correct way to create a PostgreSQL client using pg
Which option correctly creates a new PostgreSQL client instance using the pg library in Node.js?
Aconst pg = require('pg'); const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
Bimport { Client } from 'pg'; const client = new Client(process.env.DATABASE_URL);
Cconst { Client } = require('pg'); const client = new Client({ connectionString: process.env.DATABASE_URL });
Dimport pg from 'pg'; const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
Attempts:
2 left
💡 Hint
Remember that in Node.js with CommonJS, you use require and access Client from the pg module.
❓ component_behavior
intermediate
2:00remaining
What happens after calling client.connect()?
After creating a PostgreSQL client with pg and calling client.connect(), what is the expected behavior?
Node.js
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });
client.connect();
AThe client immediately connects to the database and is ready to run queries synchronously.
BThe client starts an asynchronous connection process; queries can be run after the connection is established.
CThe client throws an error if the connection string is invalid but does not connect otherwise.
DThe client queues queries automatically until the connection is established.
Attempts:
2 left
💡 Hint
Think about how asynchronous operations work in Node.js.
🔧 Debug
advanced
2:00remaining
Why does this pg client connection code throw an error?
Consider this code snippet. Why does it throw an error when trying to connect?
import { Client } from 'pg';
const client = new Client('postgresql://user:pass@localhost/db');
await client.connect();
Node.js
import { Client } from 'pg';
const client = new Client('postgresql://user:pass@localhost/db');
await client.connect();
AThe Client constructor expects an object with a connectionString property, not a string directly.
BThe connection string format is incorrect and causes a parsing error.
CThe await keyword cannot be used outside an async function.
DThe import statement is invalid syntax in Node.js.
Attempts:
2 left
💡 Hint
Check the expected argument type for the Client constructor.
❓ state_output
advanced
2:00remaining
What is the value of result.rows after this query?
Given the following code, what will result.rows contain after the query completes?
const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const result = await client.query('SELECT id, name FROM users WHERE id = $1', [42]);
await client.end();
Node.js
const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const result = await client.query('SELECT id, name FROM users WHERE id = $1', [42]);
await client.end();
AAn array of all users ignoring the WHERE clause
BUndefined because query returns no rows property
CAn empty array [] if no user with id 42 exists
D[{ id: 42, name: 'Alice' }]
Attempts:
2 left
💡 Hint
Think about what happens if the query finds no matching rows.
🧠 Conceptual
expert
2:00remaining
Which option correctly handles connection errors with pg client?
You want to connect to PostgreSQL using pg and handle connection errors gracefully. Which code snippet correctly does this using async/await?
A
try {
  await client.connect();
} catch (err) {
  console.error('Connection error', err);
  process.exit(1);
}
B
client.connect(err => {
  if (err) throw err;
  console.log('Connected');
});
C
await client.connect().catch(err => {
  console.error('Connection error', err);
  process.exit(1);
});
Dclient.connect().then(() => console.log('Connected')).catch(err => console.error(err));
Attempts:
2 left
💡 Hint
Focus on proper async/await error handling.

Practice

(1/5)
1. What is the main purpose of the pg library in Node.js?
easy
A. To connect and interact with PostgreSQL databases
B. To create web servers
C. To manage file uploads
D. To style web pages

Solution

  1. Step 1: Understand the role of pg

    The pg library is designed specifically to connect Node.js applications to PostgreSQL databases.
  2. Step 2: Compare with other options

    Creating web servers, managing file uploads, and styling pages are unrelated to database connections and are handled by other libraries.
  3. Final Answer:

    To connect and interact with PostgreSQL databases -> Option A
  4. Quick Check:

    pg = PostgreSQL connection [OK]
Hint: Remember pg is for PostgreSQL database connection [OK]
Common Mistakes:
  • Confusing pg with web server libraries
  • Thinking pg handles frontend styling
  • Assuming pg manages file uploads
2. Which of the following is the correct way to create a new Client instance from the pg library?
easy
A. const client = pg.connect('postgresql://user:pass@localhost/db');
B. const client = new pg.Client({ connectionString: 'postgresql://user:pass@localhost/db' });
C. const client = new Client.connect('postgresql://user:pass@localhost/db');
D. const client = pg.new Client('postgresql://user:pass@localhost/db');

Solution

  1. Step 1: Recall the correct Client creation syntax

    The pg library requires creating a new Client instance using new pg.Client() with a config object.
  2. Step 2: Check each option's syntax

    const client = new pg.Client({ connectionString: 'postgresql://user:pass@localhost/db' }); correctly uses new pg.Client({ connectionString: ... }). Options B, C, and D use invalid syntax or methods that do not exist.
  3. Final Answer:

    const client = new pg.Client({ connectionString: 'postgresql://user:pass@localhost/db' }); -> Option B
  4. Quick Check:

    Use new pg.Client with config object [OK]
Hint: Use 'new pg.Client' with config object for connection [OK]
Common Mistakes:
  • Calling pg.connect directly without new Client
  • Using incorrect method names like Client.connect
  • Missing the 'new' keyword when creating Client
3. What will the following code output if the query succeeds?
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });

async function run() {
  await client.connect();
  const res = await client.query('SELECT 1 AS number');
  console.log(res.rows[0].number);
  await client.end();
}

run();
medium
A. 1
B. [{ number: 1 }]
C. undefined
D. Error: query failed

Solution

  1. Step 1: Understand the query and result structure

    The query SELECT 1 AS number returns one row with a column named 'number' having value 1.
  2. Step 2: Check how the result is accessed

    The code logs res.rows[0].number, which accesses the first row's 'number' field, so it prints 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    res.rows[0].number = 1 [OK]
Hint: Access query result via res.rows[0].columnName [OK]
Common Mistakes:
  • Logging res.rows instead of a specific field
  • Expecting the whole array instead of one value
  • Not awaiting client.connect() before query
4. Identify the error in this code snippet that uses pg to connect to PostgreSQL:
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });

client.connect();
const res = await client.query('SELECT NOW()');
console.log(res.rows[0]);
client.end();
medium
A. client.end() should be called before query
B. client.query() should not be awaited
C. No error, code is correct
D. Missing await before client.connect()

Solution

  1. Step 1: Check async usage for connect()

    The client.connect() method returns a promise and must be awaited to ensure connection before querying.
  2. Step 2: Verify other async calls

    The await before client.query() is correct. Calling client.end() after query is also correct.
  3. Final Answer:

    Missing await before client.connect() -> Option D
  4. Quick Check:

    Always await client.connect() before queries [OK]
Hint: Always await client.connect() before querying [OK]
Common Mistakes:
  • Not awaiting client.connect() causing race conditions
  • Awaiting client.query() is correct, so skipping it is wrong
  • Calling client.end() too early before query finishes
5. You want to write a Node.js function using pg that connects to PostgreSQL, runs a query, and always closes the connection even if an error occurs. Which pattern is best?
hard
A. Call connect, query, and end sequentially without error handling
B. Only call client.end() if query succeeds, skip on error
C. Use try-catch-finally: connect in try, query in try, close in finally
D. Use callbacks instead of async/await for better error handling

Solution

  1. Step 1: Understand error-safe connection handling

    To ensure the connection closes even if an error happens, use a try-catch-finally block where client.end() is called in the finally block.
  2. Step 2: Evaluate options for best practice

    Use try-catch-finally: connect in try, query in try, close in finally correctly uses try-catch-finally. Call connect, query, and end sequentially without error handling lacks error handling. Only call client.end() if query succeeds, skip on error risks leaving connection open on errors. Use callbacks instead of async/await for better error handling is outdated compared to async/await.
  3. Final Answer:

    Use try-catch-finally: connect in try, query in try, close in finally -> Option C
  4. Quick Check:

    try-catch-finally ensures connection closes [OK]
Hint: Use try-catch-finally to always close connection [OK]
Common Mistakes:
  • Not closing connection on errors
  • Ignoring async/await for error handling
  • Closing connection only on success
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard