2

i want to use a COUNT result as IF CONDITION on ORACLE, like this pseudocode on oracle:

select count(d.number_people) as counted_people
from dual d
if counted_people = 1 then
dbms_output.put_line('Have just one people on this column.'
end if;

This syntax is wrong, I know, how do I do it the right way?

3
  • DUAL is a special one-row one-colum table, and it does not have number_people column, It's not clear what number of people do you want to count from this table using SELECT count(number_people) FROM dual ? Commented Dec 18, 2018 at 19:58
  • Its a example , the ploblem is how to use a count as if statement Commented Dec 18, 2018 at 20:00
  • 2
    Possible duplicate of if (select count(column) from table) > 0 then Commented Dec 18, 2018 at 20:07

2 Answers 2

1

Use SELECT ... INTO variable ...

Demo: https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=610d02797857539be5fcd4afdbd7d9e6

DECLARE 
  cnt number;
BEGIN
  select count(*) INTO cnt from dual;
  IF cnt = 1 THEN
     DBMS_OUTPUT.PUT_LINE('Exaclty one record');
  ELSE
     DBMS_OUTPUT.PUT_LINE('0 or more than 1  record');
  END IF;
END;
/
Sign up to request clarification or add additional context in comments.

Comments

1

COUNT is an aggregation result. You can count all rows in a table, all rows that match certain criteria, etc. As an aggregation result, you can use it in the SELECT clause, in the HAVING clause, and in the ORDER BY clause. (You cannot use it in the WHERE clause, because the WHERE clause deals with the data in the table rows. You need a HAVING clause instead, which deals with aggregation results.)

SELECT clause / ORDER BY clause example

select
  supplier_id,
  case when count(*) < 20 then 'less then 20 orders'
       when count(*) < 40 then 'less beteen 20 and 40 orders'
       else '40 or more orders'
  end as number_of_orders
from orders
where order_date >= date '2018-01-01'
group by supplier_id
order by count(*) desc;

HAVING clause example

select sex, count(*)
from members
group by sex
having count(*) > 20;

4 Comments

I have been doing Oracle since v4 (1985), and this is the first time I have seen this group by clause.
My comment was supposed to be a joke because of the particular column you are grouping by.
@Roger Cornejo: Ah, sorry. Yeah, I must admit when typing my query I wondered for a moment if the BY in GROUP BY was optional ;-)
:-)) hilarious :-))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.