Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Oracle SQL function using Select Count returns duplicate answer for every row

Trying to do a simple User function where I get the number of people whos age is > 100.

this is my current table

select * from peoples

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

**NAME**      **AGE**
----------------------
Joe Bloggs  12
Paul Smith  15
Jonah James 534
Mika Rive   31
Hannah Bananas  56
Harry Heelz 4
Brian Bolton    232
Jack Ripper 123

I’m currently trying to implement user function where the output is a single row with the total number of people with an age greater than 100.

Here is the function I have attempted to make

create or replace function agetest return number is
v_count number;

begin
    select count(age) into v_count
    from persons
    where  age > 100;
    
        return v_count;
end;
 

When I execute the SQL query directly I get the correct answer

select count(age) from persons where age > 100;

COUNT(AGE)
1 3

but when I run the function

select agetest from persons;

I get the output of:

AGETEST
1 3
2 3
3 3
4 3
5 3
6 3
7 3
8 3

Just looking for guidance on why the output is showing the same result for each row.

My ideal output for the function would just be:

AGETEST
1 3

>Solution :

Try executing the function against DUAL:

SELECT agetest FROM dual;

In Oracle, the DUAL table is a sort of dummy table which has only one record in it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading