Prime Numbers as a SQL Query

This isn't a Sieve of Eratosthenes algorithm, but it's too good not to share it.

select r 
from (
  select rownum+1 r from dual connect by rownum < 10000
  or 0 not in(
    select mod(r,rownum+1) from dual
    connect by rownum<sqrt(r)

This is an Oracle query that will generate all of the primes up to 10,000. The query is not even close to fast, but I think it's kind of funny. It's just your typical everyday brute force method of calculating prime numbers.

3 Comments so far

  1. Kabroo @ December 5th, 2010

    Very cool ! Thanks for sharing. BTW, how would you do it in MS SQL?

  2. Debbie Reynolds @ March 2nd, 2012

    Hello, I think your website might be having browser compatibility issues. When I look at your blog in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, awesome blog!

  3. maitrayee choubey @ February 26th, 2016

    can you please explain the same

Leave a reply