# Top Pattern Matches

> A needle in a haystack, but how many haystacks?

Canonical URL: <https://datadriven.io/problems/top_pattern_matches>

Domain: SQL · Difficulty: medium · Seniority: L4

## Problem

Our server logs contain messages with embedded reference numbers. Find the 10 servers whose log messages most frequently match a pattern of a 3-digit prefix, a dash, then 4 or more digits. Return each server's name and its match count, from the most matches down to the fewest, and when two servers tie, listing the alphabetically earlier name first.

## Tables

### server_logs

- log_id INTEGER
- server_name TEXT
- message TEXT
- log_timestamp TEXT
- log_level TEXT
- response_time_ms INTEGER

Sample rows (10 of 200):

| log_id | server_name | log_level | message | response_time_ms | log_timestamp |
| --- | --- | --- | --- | --- | --- |
| 137 | web-prod-02 | WARN | Connection timeout after 30s | 23 | 2026-02-02 01:07:13 |
| 174 | api-prod-01 | ERROR | Database query slow: 2.5s | NULL | 2026-03-03 02:14:26 |
| 211 | api-prod-02 | DEBUG | Cache miss for key user_123 | 49 | 2026-04-04 03:21:39 |
| 248 | db-primary | CRITICAL | Memory usage at 85% | 0 | 2026-05-05 04:28:52 |
| 285 | db-replica-01 | INFO | SSL certificate expires in 7 days | NULL | 2026-06-06 05:35:05 |
| 322 | cache-01 | WARN | Rate limit exceeded for IP 192.168.1.x | 88 | 2026-07-07 06:42:18 |
| 359 | worker-01 | ERROR | Disk space low: 10% remaining | 101 | 2026-08-08 07:49:31 |
| 396 | cdn-edge-us | DEBUG | New deployment v2.3.1 started | NULL | 2026-09-09 08:56:44 |
| 433 | cdn-edge-eu | CRITICAL | Health check passed | 127 | 2026-01-10 09:03:57 |
| 470 | monitor-01 | INFO | Failed to connect to upstream | 140 | 2026-02-11 10:10:10 |

## Expected output

First 5 of 10 rows:

| server_name | match_count |
| --- | --- |
| cache-01 | 6 |
| db-primary | 6 |
| api-prod-02 | 4 |
| cdn-edge-eu | 4 |
| api-prod-01 | 2 |

## Worked solution and explanation

### What this is really asking

`message LIKE '%___-____%'` is the entire trick. Underscore is single-character wildcard, so three underscores, dash, four underscores matches '3 digits, dash, 4+ digits' on 60M rows without regex.

---

### Break down the requirements

#### Step 1: Match shape with LIKE

`%___-____%` reads as: anything, 3 chars, dash, 4 chars, anything. The trailing `%` lets the digit run exceed 4.

#### Step 2: Aggregate per server

`GROUP BY server_name`, `COUNT(*)`. WHERE filters before grouping, so the count is messages-with-a-match, not total matches.

#### Step 3: Top 10

`ORDER BY match_count DESC LIMIT 10`. Production code would add `server_name` as a deterministic tie-break.

---

### The solution

**TOP 10 SERVERS BY LIKE-PATTERN HITS**

```sql
SELECT server_name, COUNT(*) AS match_count
FROM server_logs
WHERE message LIKE '%___-____%'
GROUP BY server_name
ORDER BY match_count DESC, server_name
LIMIT 10
```

> **Cost Analysis**
>
> Leading `%` kills any btree index on `message`; full scan over 60M rows. The `log_timestamp` partition doesn't help without a time filter. On Postgres, a trigram index fixes it.

> **Interviewers Watch For**
>
> Whether you know `_` is single-char (not 'zero or one'). Also: count messages or matches? `COUNT(*)` counts messages; one with two refs still counts once.

> **Common Pitfall**
>
> `LIKE '___-____'` without surrounding `%` only matches messages that ARE the pattern, not ones that CONTAIN it. Drops match count to near zero on real log text.

> **The False Start**
>
> First instinct is `REGEXP '[0-9]{3}-[0-9]{4,}'`. Right shape, and it actually enforces digits. The expected query trades strictness for LIKE's portability and speed. Flag the tradeoff aloud and ship the LIKE.

---

### COMMON FOLLOW-UP QUESTIONS

## Common follow-up questions

- How do you enforce that matched chars are actually digits? _(Switch to `REGEXP_LIKE(message, '[0-9]{3}-[0-9]{4,}')` or Postgres `~`. Slower, but no false positives on `abc-defg`.)_
- What if you wanted total occurrences, not messages? _(Use `REGEXP_COUNT(message, '[0-9]{3}-[0-9]{4,}')` and `SUM()` per server. `COUNT(*)` undercounts multi-match messages.)_
- How do you exploit the `log_timestamp` partition? _(Add `WHERE log_timestamp >= ...` so the planner prunes partitions. Without it, all partitions scan regardless of LIKE.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/top_pattern_matches)
- [SQL Interview Questions](https://datadriven.io/sql-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). DataDriven is the data engineering interview community. Live code execution in SQL, Python, and Spark sandboxes. Every feature is open to every member.