Skip to main content

Recursion example with SQL


I asked my friend Chatty, can you use recursion in SQL? For example I have a table (ID, value) ordered by increasing ID. Can you guide me through using recursion to select all the rows of consecutive repeated values using and creating an SQLite database. Provide the small sample data.

Is there a better way to do this?

A More Modern Alternative (Window Functions)
In real-world SQL, this problem is usually solved more efficiently using window functions like:

LAG()
ROW_NUMBER()
SUM() OVER

But recursion is excellent for learning traversal logic and hierarchical thinking.

Recursion example using sqlite on termux

DROP TABLE IF EXISTS sample;

CREATE TABLE sample (
    id INTEGER PRIMARY KEY,
    value TEXT
);

INSERT INTO sample (id, value) VALUES
(1, 'A'),
(2, 'A'),
(3, 'A'),
(4, 'B'),
(5, 'B'),
(6, 'C'),
(7, 'A'),
(8, 'A'),
(9, 'D'),
(10, 'D'),
(11, 'D'),
(12, 'D');

WITH RECURSIVE grouped AS (

    SELECT
        id,
        value,
        1 AS group_num
    FROM sample
    WHERE id = (SELECT MIN(id) FROM sample)

    UNION ALL

    SELECT
        s.id,
        s.value,

        CASE
            WHEN s.value = g.value
            THEN g.group_num
            ELSE g.group_num + 1
        END

    FROM sample s
    JOIN grouped g
        ON s.id = g.id + 1
)

SELECT
    value,
    MIN(id) AS start_id,
    MAX(id) AS end_id,
    COUNT(*) AS consecutive_count
FROM grouped
GROUP BY group_num, value
HAVING COUNT(*) > 1;

Comments

Popular posts from this blog

Hobby project - Store and view exchange rates

The next step in my project was to test out being able store and display the rates in a database. I decided to use nodejs and supabase for this. Everything worked beautifully. Only hickup was the following error due to my package.json not being correct. SyntaxError: Cannot use import statement outside a module Added this to package.json   "type": "module" This works beautifully. Right now I am just testing fragments of what could be part of a bigger system to see what is possible and what works and how easy to code on a mobile. There is no fully functioning integrated end to end system just yet. This is also what I tested. A serverless append-only database using GitHub + Actions + Pages. That’s basically a lightweight backend system. This was the ChatGPT prompt I used. Guide me through each step. This is what I want. A manually run github actions that adds to docs/data.json with the current date and time. docs/index.html displays all the entries in data.json. Make s...

What is important

Every now and again, I get reminded of the why. Why I have handed my life over to God. It is 3:08 p.m. and I have decided to write. Honestly, I feel like I could end this blog post right here. What more is there to say? God above all else. God is our compass on this journey called life. Everything else can become a distraction. Maybe not everything, but certainly many things. You get the point. What is important? What do we prioritise? What do we make time for? The answers look different for everyone. Our lives are different. We are tested differently. We are all products of our circumstances, and those circumstances vary from person to person. Yet God is the common thread across humanity and throughout time. God always was and always will be. One day, we will answer to God. We will give account to God. We cannot live without food, water, and oxygen, but all of those things come from God. So how can we live without God? How timely. I just received a notification from the Quranly app: S...

Today

It is 213pm and I have decided to write. God is good. Obviously. God is beautiful. God made me smile. God is what we think of God. We are what we think. Better to think good things. What are some good thoughts? The rain brings joy to the plants. Time dances. The birds sing beautifully. I am happy. A cup of love to warm the soul. Peace and quiet on a Friday afternoon. The light rests gently on everything. Think of all the good things. Think of one good thing. What is the most beautiful thought? God is here and I am here and that is enough. I can do all things through God. The most beautiful thought is one of contentment. I appreciate the now. I appreciate the moment. I am grateful to be where I am. It is no coincidence that God and gratitude both begin with the letter g. If I combine God and gratitude I get Goditude. I also notice that the word guide is contained in the word gratitude. Let gratitude be our guide. If I remove guide from Goditude, I am left with dot. Goditude is a dot wit...