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

Giving

It is 237pm and I have decided to write. I drank a strong cup of coffee. It is hot outside but cool inside in the AC. I have no topic but I feel like writing. I love giving charity. Who knows it, feels it. The world would be a much better place if we all shared with one another. If we helped one another. If we only take as much as we need and leave the rest for others. If we prioritised needs over wants. We are going to leave it all behind when we die. We cannot carry anything into the grave except our deeds. One of the easiest ways to give money to charities is through SMS codes. The telecoms should have a system in place where charitable causes can sign up for an SMS code to accept donations. Long ago I remember seeing the donation tins at the supermarket. We should have more of those. I think more people would give more if they were presented with more opportunities to give. The nlcb booths could be outlets for making donations. Linx machines could be points for making donations. AT...

A mirror for the soul

It is 207pm and I have decided to write. I had this thought. Is the Quran a mirror for the soul? How does the Quran help me see my soul? What is a soul? I am reading about the soul and it is all abstract as if we really do not know what the soul is. The soul is what remains after the body dies. I get that. The immaterial part of our existence. Is it responsible for the conscience? Is it linked to emotions? Are my thoughts from my soul? My friend says that the Quran speaks of the soul in this way. "And they ask you about the soul. Say, 'The soul is of the affair of my Lord. And mankind have not been given of knowledge except a little.'" (Quran 17:85). "And [by] the soul and He who proportioned it. And inspired it [with discernment of] its wickedness and its righteousness." (Quran 91:7–8). In Islam we talk about the ruh, nafs and self. The ruh is the spirit whose true nature is known fully only to Allah, the nafs is the self involved in desires, struggles, and...

Technology in Trinbago

It is 205am and I have decided to write. I was doing some research and trying to update myself on what is happening in the tech space in Trinidad and Tobago. Nothing stood out in particular. I went looking at what other Caribbean countries were doing that we could adopt. I think there are opportunities in that. Then I decided to focus my energy on coming up with a list of things I think could be done with tech in Trinbago. 1. Feeding a startup culture. Ease of doing business. Make it easy to start and run a business. Support for businesses that earn foreign exchange. 2. Launch the work from home policy. 3. Have a similar policy for online schooling and home schooling. 4. Tech literacy focusing on cybersecurity and keeping safe online. 5. What would it take to get Paypal and CashApp supported here? 6. Support and encouragement for tech bloggers and tech youtubers. 7. More hackatons and a yearly developer survey. 8. Facilitating contact and communication between local techies and big tec...