ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

SQL ANSI: Find the Longest Consecutive Sequence of Identical Values

SQL ANSI

Goal -- WPM

Ready
Exercise Algorithm Area
1-- This query finds the longest consecutive sequence of identical values in a column.
2-- It uses window functions to identify the start of each sequence and calculate its length.
3
4WITH
5-- Step 1: Assign a group identifier to consecutive identical values.
6-- We use LAG to check the previous row's value. If it's different, a new group starts.
7GroupStarts AS (
8SELECT
9id, -- Assuming an 'id' column for ordering, or use another suitable column
10value_column, -- The column to check for consecutive sequences
11CASE
12WHEN value_column = LAG(value_column, 1, NULL) OVER (ORDER BY id) THEN 0
13ELSE 1
14END AS is_new_group
15FROM
16your_table_name -- Replace with your actual table name
17WHERE
18value_column IS NOT NULL -- Ignore NULLs for sequence calculation
19),
20-- Step 2: Calculate a running sum of 'is_new_group' to create a unique group ID for each consecutive sequence.
21GroupIDs AS (
22SELECT
23id,
24value_column,
25SUM(is_new_group) OVER (ORDER BY id) AS group_id
26FROM
27GroupStarts
28),
29-- Step 3: Calculate the length of each consecutive sequence.
30SequenceLengths AS (
31SELECT
32value_column,
33group_id,
34COUNT(*) AS sequence_length
35FROM
36GroupIDs
37GROUP BY
38value_column,
39group_id
40),
41-- Step 4: Rank sequences by length to find the longest one(s).
42RankedSequences AS (
43SELECT
44value_column,
45sequence_length,
46ROW_NUMBER() OVER (ORDER BY sequence_length DESC) AS rank_num
47FROM
48SequenceLengths
49)
50-- Final selection: Get the value and length of the longest sequence.
51-- If there are multiple sequences of the same maximum length, this will return one of them.
52SELECT
53value_column,
54sequence_length
55FROM
56RankedSequences
57WHERE
58rank_num = 1;
Algorithm description viewbox

SQL ANSI: Find the Longest Consecutive Sequence of Identical Values

Algorithm description:

This SQL query identifies the longest consecutive sequence of identical values within a specified column. It cleverly uses window functions like `LAG` and `SUM` to group consecutive identical values and then `COUNT` to determine the length of each sequence. Finally, it ranks these sequences by length to find the maximum. This is useful for analyzing time-series data, log files, or any data where runs of identical states are significant.

Algorithm explanation:

The query employs a series of Common Table Expressions (CTEs) to break down the problem. `GroupStarts` uses `LAG` to compare each row's `value_column` with the previous row's value (ordered by `id`). If they differ, `is_new_group` is marked as 1, indicating the start of a new sequence. `GroupIDs` then uses a running `SUM` of `is_new_group` to assign a unique `group_id` to all rows belonging to the same consecutive sequence. `SequenceLengths` groups by `value_column` and `group_id` to count the number of rows in each distinct sequence, thus determining its `sequence_length`. Finally, `RankedSequences` ranks these sequences by `sequence_length` in descending order. The main query selects the `value_column` and `sequence_length` from the top-ranked sequence. The time complexity is O(N log N) due to the ordering required by window functions, where N is the number of rows. Space complexity is O(N) for storing intermediate results. Edge cases handled include NULL values (ignored), empty tables (no results), and tables with a single row (the sequence length will be 1). The invariant is that `group_id` uniquely identifies contiguous blocks of identical `value_column` values.

Pseudocode:

1. Create CTE `GroupStarts`:
   - Select `id`, `value_column`.
   - For each row, compare `value_column` with the previous row's `value_column` (ordered by `id`).
   - If they are different, set `is_new_group` to 1, otherwise 0.
   - Filter out rows where `value_column` is NULL.
2. Create CTE `GroupIDs`:
   - Select `id`, `value_column` from `GroupStarts`.
   - Calculate a running `SUM` of `is_new_group` (ordered by `id`) to create `group_id`.
3. Create CTE `SequenceLengths`:
   - Group `GroupIDs` by `value_column` and `group_id`.
   - Count the number of rows in each group to get `sequence_length`.
4. Create CTE `RankedSequences`:
   - Select `value_column`, `sequence_length` from `SequenceLengths`.
   - Assign a rank based on `sequence_length` in descending order.
5. Select `value_column`, `sequence_length` from `RankedSequences` where rank is 1.