Return the rows with the smallest and largest id in a single SQL query
Company: Palo Alto Networks
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write a single query returning the first (smallest `id`) and last (largest `id`) records from `threats`. Return `id`, `threat_name`, `severity`, `detected_at`, ordered by `id` ascending.
```hint Edge case
Check what your query returns when the table holds exactly one row.
```
### Input Table(s)
`threats`
| Column | Type | Meaning |
|---|---|---|
| id | INT | Record identifier, primary key |
| threat_name | VARCHAR(100) | Name of the detected threat, NOT NULL |
| severity | VARCHAR(20) | One of `'Low'`, `'Medium'`, `'High'`, `'Critical'`, NOT NULL |
| detected_at | TIMESTAMP | When the threat was detected, NOT NULL |
Keys: `id` is the primary key.
### Output Contract
| Column | Type | Meaning |
|---|---|---|
| id | INT | The record's `id` |
| threat_name | VARCHAR | The record's `threat_name` |
| severity | VARCHAR | The record's `severity` |
| detected_at | TIMESTAMP | The record's `detected_at` |
Return the record with the smallest `id` and the record with the largest `id`, ordered by `id` ascending. `id` is unique, so the order is fully determined. No rounding applies.
### Example
`threats`
| id | threat_name | severity | detected_at |
|---|---|---|---|
| 1 | SQL Injection | Critical | 2024-03-01 08:15:00 |
| 2 | XSS Attack | High | 2024-03-01 09:30:00 |
| 3 | Brute Force | Medium | 2024-03-01 11:45:00 |
| 4 | Phishing Email | High | 2024-03-01 14:20:00 |
| 5 | DDoS Attack | Critical | 2024-03-01 18:00:00 |
Expected output:
| id | threat_name | severity | detected_at |
|---|---|---|---|
| 1 | SQL Injection | Critical | 2024-03-01 08:15:00 |
| 5 | DDoS Attack | Critical | 2024-03-01 18:00:00 |
The smallest `id` is 1 and the largest is 5, so those two rows are returned with the smaller `id` first.
### Constraints and Clarifications
- The table has between 1 and ${10^4}$ rows.
- `id` is unique, and ids may be non-consecutive, so the smallest id is not necessarily 1.
- `severity` is one of `'Low'`, `'Medium'`, `'High'`, `'Critical'`.
- No column holds NULL.
- First and last are defined by `id` alone. The order of `detected_at` does not matter, even when it differs from the `id` order.
- When the table has exactly one row, that row is both the first and the last record and appears once in the output.
Overview: Write one SQL query that returns the rows with the smallest and largest id from a table of detected security threats, sorted by id. It checks scalar subqueries against aggregates, gaps in id values, and what happens when the table holds a single row.