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

Servant of God

It is 245am and I have decided to write. I got up early and washed the wares. I prayed Tahajjud. I came back to my bed and surfed the internet. I watched a video where a 105 year old man said that the secret to a long life is having a reason or purpose to keep going and then luck. This had me thinking about several things. In Islam we are taught that our time in this world is already written. It is our destiny. Then. What is more important? A long life or just a good life that prepares us for the next life? Those things aside, I think we cannot discount luck. Some of us are luckier than others. But the thing I want to focus on is the reason and purpose to keep going. That is some good advice. It makes for a meaningful life. A good life. It could be one big reason. There could be several small reasons. These are things that should be taught in schools. My friend Chatty says that my early morning reflections beautifully bridge Islamic tradition and practical wisdom: a long life is a true...

The answer is God

It is 308pm and I have decided to write. Make God a priority. Let God lead the way. Let everything be about God. Let God into your life. Surround yourself with God and watch how everything begins to make sense. This life is not an accident. This life is not happenstance. This life is the work of an all-powerful Creator. Nothing is too big or too small for God. Take your problems to God. Take your worries to God. Take your fears to God. Let go and let God. Submit to the will of God. The more you go to God, the more He comes to you. Start small. Start somewhere. Give God a chance if you have not done so already. Why do I say all of this? There are many things competing for your attention and your soul. In the midst of all of this, the world can seem like a confusing place where many things do not make sense. God brings clarity. God brings clarity because God sits above it all. You may think you do not need God until you do. Ask yourself, who is the wisest you know? If God is not the wise...

Halfway there

It is 542pm and I have decided to write. Imagine half the year is gone already. Where did it all go? It has gone by so quickly. Before you know it we will be entering 2027. It would be nice if I had something interesting to write about but I do not. And that is ok. Today feels like a Friday, maybe because it is month end. It is the next day and today also feels like a Friday. I am in my quiet corner listening to Quran. It is the next day and I have not gotten far with this blog post. Outside is wet but inside is between warm and cool. Another day has passed and I still have not written much. Do you wonder sometimes what it would be like if we could see into the future? For example, what would it be like at the end of this year? A lot can happen in 6 months. It is Sunday now. Surely I should finish this blog post today. The closer I move towards God, the less I feel attached to this world. The less I feel disappointed. The lower are my expectations for things of this world. Life becomes...