SQL Explained Through JavaScript - Part 2

Oct 23, 2026

Note: Familiarity with JavaScript and basic SQL-tables, rows, columns, and SELECT, FROM, WHERE-will help you follow the examples.

In the first part, we looked at how SQL concepts like GROUP BY, HAVING, and LEFT JOIN can be understood through equivalent JavaScript code.

This time, all our examples will focus on a blog's comment system. We'll explore how to limit comments per user, extend that limit to IP addresses, and search for specific users' comments on specific posts. Along the way, we'll explain ON CONFLICT, CASE WHEN, and unnest through equivalent JavaScript.

Example: Limiting Comments per Hour with UPSERT and CASE WHEN

We want to track how many comments each user posts within a one-hour window, so we can reject comments once they exceed the hourly limit.

To track this, we keep a comment_limits table with one row per user. Each row stores the user's ID (user_id), comment count (comments_count), and the time their current window ends (expires_at).

Here's the SQL:

INSERT INTO comment_limits (user_id, comments_count, expires_at)
VALUES ($1, 1, now() + interval '1 hour')
ON CONFLICT (user_id) DO UPDATE
SET
  comments_count = CASE
    WHEN comment_limits.expires_at <= now() THEN 1
    ELSE comment_limits.comments_count + 1
  END,
  expires_at = CASE
    WHEN comment_limits.expires_at <= now() THEN now() + interval '1 hour'
    ELSE comment_limits.expires_at
  END
RETURNING comments_count;

Here's the equivalent JavaScript:

const HOUR = 60 * 60 * 1000;

// Let's assume this is the table data: one row per user
const table = [];

function recordComment(userId) {
  const now = Date.now();

  const row = table.find((row) => row.userId === userId);

  // SQL: INSERT ... VALUES ($1, 1, now() + interval '1 hour')
  // $1 is userId. No row yet, so create one.
  if (!row) {
    const newRow = {
      userId,
      commentsCount: 1,
      expiresAt: now + HOUR,
    };

    table.push(newRow);
    return newRow.commentsCount;
  }

  // SQL: ON CONFLICT (user_id) DO UPDATE
  // A row already exists, so update it.
  const expired = row.expiresAt <= now;

  // SQL: CASE WHEN expired THEN 1 ELSE comments_count + 1 END
  row.commentsCount = expired ? 1 : row.commentsCount + 1;

  // SQL: CASE WHEN expired THEN now() + interval '1 hour' ELSE expires_at END
  row.expiresAt = expired ? now + HOUR : row.expiresAt;

  // SQL: RETURNING comments_count
  return row.commentsCount;
}

The first comment starts a one-hour window with a count of 1. Each comment within that window adds 1. The first comment after the window ends starts a new window with a count of 1. The updated count is returned each time.

Why RETURNING comments_count?

RETURNING gives back the new comment count. That's the only value the caller needs to decide what to do next, and it comes from the same statement, so there's no second SELECT needed:

const count = recordComment(userId);

if (count > 5) {
  // too many comments this hour, reject
}

Using Two Counters

The query above has a drawback: it only counts per user. A spammer can register 100 accounts and post 5 comments from each, and no single account ever passes 5.

The fix is to keep two counters. When someone comments, we increase the counter for their user and the counter for their IP address.

Spammer behaviorUser counterIP counter
1 account, comments from 100 different IPs

Reaches the limit, blocked

100 counters with 1 comment each, not blocked
100 accounts, all from the same IP100 counters with 1 comment each, not blocked

Reaches the limit, blocked

Each counter catches the case the other one misses. So we block if either one is over the limit.

To store both kinds of counters in the same comment_limits table, we replace the user_id column with a key column. A key is a string that names one counter, like user:42 or ip:1.2.3.4. Here 42 is the user_id from the previous example. For example, after the first comment, the two counters might look like this:

keycomments_countexpires_at
user:42115:00
ip:1.2.3.4115:00

We want to limit comments by both user and IP address, so switching accounts or IPs alone won't bypass the limit.

We could also adapt the earlier single-counter query and run it twice, once for the user key and once for the IP key. Here, we'll see how to update both counters in a single query using unnest (which turns an array into rows). Besides learning something new, this saves a database call and ensures both updates succeed or fail together.

Here's the SQL:

INSERT INTO comment_limits (key, comments_count, expires_at)
SELECT key, 1, now() + interval '1 hour'
FROM unnest($1::text[]) AS key
ORDER BY key
ON CONFLICT (key) DO UPDATE
SET
  comments_count = CASE
    WHEN comment_limits.expires_at <= now() THEN 1
    ELSE comment_limits.comments_count + 1
  END,
  expires_at = CASE
    WHEN comment_limits.expires_at <= now() THEN now() + interval '1 hour'
    ELSE comment_limits.expires_at
  END
RETURNING comments_count;

Here's the equivalent JavaScript:

const HOUR = 60 * 60 * 1000;

// Table data: one row per user or IP key.
const table = [];

function recordComment(keys) {
  const now = Date.now();

  // SQL: SELECT key ... FROM unnest($1::text[]) AS key ORDER BY key
  // unnest turns the array into rows, so INSERT below can process each row individually.
  return [...keys].sort().map((key) => {
    const row = table.find((row) => row.key === key);

    // SQL: INSERT ... SELECT key, 1, now() + interval '1 hour'
    // No row for this key yet, so create one.
    if (!row) {
      const newRow = {
        key,
        commentsCount: 1,
        expiresAt: now + HOUR,
      };

      table.push(newRow);
      return newRow.commentsCount;
    }

    // SQL: ON CONFLICT (key) DO UPDATE
    // A row already exists, so update it.
    const expired = row.expiresAt <= now;

    // SQL: CASE WHEN expired THEN 1 ELSE comments_count + 1 END
    row.commentsCount = expired ? 1 : row.commentsCount + 1;

    // SQL: CASE WHEN expired THEN now() + interval '1 hour' ELSE expires_at END
    row.expiresAt = expired ? now + HOUR : row.expiresAt;

    // SQL: RETURNING comments_count (one per key)
    return row.commentsCount;
  });
}

Each comment updates two counters: one for the user and one for the IP address. Both follow the same counting and reset rules as the earlier example.

Note: ORDER BY key helps prevent a deadlock where one request locks the user counter and another locks the IP counter. Each then needs the counter locked by the other, so neither can finish. Sorting makes both requests update the counters in the same order.

Using the result

The caller checks that every counter is under the limit:

const counts = recordComment([`user:${userId}`, `ip:${ip}`]);

if (!counts.every((count) => count <= 5)) {
  // either the user or the IP commented too much, reject
}

Example: Searching for Comments with UNNEST and JOIN

Since we've touched on unnest, let's also see how it can help us search for comments. In the previous example, it turned an array into rows to insert. This time, we'll turn two arrays into pairs of values and use those pairs to find matching rows.

Imagine you're reviewing reports about comments on your blog. One report asks you to review user 42's comments on post 10. Another asks you to review user 7's comments on post 20. You want to load the comments for both reports in one query.

We have a comments table containing each comment's ID, author (user_id), blog post (post_id), and text (body). For this example, we'll use integer IDs:

id  | user_id | post_id | body
----|---------|---------|---------------------
101 | 42      | 10      | First comment
102 | 42      | 20      | Second comment
103 | 7       | 20      | Third comment
104 | 7       | 10      | Fourth comment
105 | 42      | 10      | Another comment

We want comments 101 and 105 for the first report, and 103 for the second. Comments 102 and 104 belong to the same users, but on the wrong posts for these reports.

Keeping the search pairs together

We pass two arrays to the query. Values at the same position belong to the same report:

const userIds = [42, 7];
const postIds = [10, 20];

Here's the SQL:

SELECT c.id, c.user_id, c.post_id, c.body
FROM comments AS c
JOIN unnest($1::int[], $2::int[])
  AS requested(user_id, post_id)
  ON c.user_id = requested.user_id
 AND c.post_id = requested.post_id;

$1 is userIds, and $2 is postIds. With two arrays, unnest pairs their elements by position: the first user with the first post, then the second user with the second post. It produces these rows:

user_id | post_id
--------|--------
42      | 10
7       | 20

AS requested(user_id, post_id) names this set of rows requested and names its two columns. JOIN (short for INNER JOIN) finds comments where both the user and the post match one of those rows. A pair can match several comments, as user 42 has two comments on post 10. If a pair has no matching comments, it contributes no results.

Here's the equivalent JavaScript:

const comments = [
  { id: 101, userId: 42, postId: 10, body: "First comment" },
  { id: 102, userId: 42, postId: 20, body: "Second comment" },
  { id: 103, userId: 7, postId: 20, body: "Third comment" },
  { id: 104, userId: 7, postId: 10, body: "Fourth comment" },
  { id: 105, userId: 42, postId: 10, body: "Another comment" },
];

function searchComments(userIds, postIds) {
  // SQL: unnest($1::int[], $2::int[])
  // Pair each user with the post at the same position.
  const requested = userIds.map((userId, index) => ({
    userId,
    postId: postIds[index],
  }));

  // SQL: JOIN ... ON c.user_id = requested.user_id
  //              AND c.post_id = requested.post_id
  const results = [];

  for (const pair of requested) {
    for (const comment of comments) {
      if (comment.userId === pair.userId && comment.postId === pair.postId) {
        results.push(comment);
      }
    }
  }

  return results;
}

const results = searchComments([42, 7], [10, 20]);
// Returns the comment objects with IDs 101, 105, and 103.

Both versions find comments 101, 105, and 103: user 42's comments on post 10, and user 7's comments on post 20.

Why not use IN?

It might look like we could write:

SELECT id, user_id, post_id, body
FROM comments
WHERE user_id IN (42, 7)
  AND post_id IN (10, 20);

Remember what we want: user 42's comments on post 10, and user 7's comments on post 20.

Now consider comment 102. It was written by user 42 on post 20. Should we include it? No: for user 42, we only asked for comments on post 10.

But here's how the query above checks comment 102:

user_id IN (42, 7)  → Is 42 in this list? Yes.
post_id IN (10, 20) → Is 20 in this list? Yes.

Both conditions are true, so the query includes comment 102. The first list allows either user, and the second list allows either post. Nothing in this query says that user 42 must go with post 10, or that user 7 must go with post 20.