I am new to StackOverflow and have got stuck with a query to print prime numbers from 2 to 1000. I have used the below query need input if this is the most efficient way to code it.
WITH NUM AS (
SELECT LEVEL N
FROM DUAL CONNECT BY LEVEL <= 1000
)
SELECT LISTAGG(B.N,'-') WITHIN GROUP(ORDER BY B.N) AS PRIMES
FROM (
SELECT N,
CASE WHEN EXISTS (
SELECT NULL
FROM NUM N_INNER
WHERE N_INNER .N > 1
AND N_INNER.N < NUM.N
AND MOD(NUM.N, N_INNER.N)=0
) THEN
'NO PRIME'
ELSE
'PRIME'
END IS_PRIME
FROM NUM
) B
WHERE B.IS_PRIME='PRIME'
AND B.N!=1;
I know this question has been asked multiple times and I am requesting better solution if any. More over need input on how this works with MySQL/MS SQL/PostgreSQL.
Any help will make my understanding better.
Simple query in PostgreSQL:
Enjoy! :)
Tested on sqlite3
Tested on Vertica 8
MariaDB (with sequence plugin)
Similar to kordirkos algorithm:
Using LEFT JOIN:
MySQL
There are no sequence generating helpers in MySQL. So the sequence tables have to be created first:
Now similar queries can be used:
sqlfiddle
The below code works to find prime numbers in SQL
Tested on SampleDB of local server
I have created the stored procedure which has a parameter @number to find the prime numbers up to that given number
In order to get the prime numbers we can execute the below stored procedure
If you are new to stored procedures and want to find the prime numbers in SQL we can use the below code
Tested on master DB
This code can give the prime numbers between 1 to 100. If we want to find more prime numbers edit the @i and @j arguments in the while loop and execute
Oracle and without inner select in getting part: