I need to check a condition. i.e:
if (condition)> 0 then update table else do not update end if
Do I need to store the result into a variable using select into?
e.g:
declare valucount integer begin select count(column) into valuecount from table end if valuecount > o then update table else do not update
SELECT [DISTINCT] COUNT([DISTINCT] IF(<condition>, <expression>, NULL)) AS alias_name FROM your_table_name; The syntax shows that: COUNT() function includes IF() function, which has a condition specified. If the <condition> is true, then the count will be calculated based on <expression> passed.
The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows. The above syntax is the general SQL 2003 ANSI standard syntax.
According to this theory, COUNT(*) takes all columns to count rows and COUNT(1) counts using the first column: Primary Key. Thanks to that, COUNT(1) is able to use index to count rows and it's much faster.
The difference is simple: COUNT(*) counts the number of rows produced by the query, whereas COUNT(1) counts the number of 1 values. Note that when you include a literal such as a number or a string in a query, this literal is "appended" or attached to every row that is produced by the FROM clause.
You cannot directly use a SQL statement in a PL/SQL expression:
SQL> begin 2 if (select count(*) from dual) >= 1 then 3 null; 4 end if; 5 end; 6 / if (select count(*) from dual) >= 1 then * ERROR at line 2: ORA-06550: line 2, column 6: PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ... ...
You must use a variable instead:
SQL> set serveroutput on SQL> SQL> declare 2 v_count number; 3 begin 4 select count(*) into v_count from dual; 5 6 if v_count >= 1 then 7 dbms_output.put_line('Pass'); 8 end if; 9 end; 10 / Pass PL/SQL procedure successfully completed.
Of course, you may be able to do the whole thing in SQL:
update my_table set x = y where (select count(*) from other_table) >= 1;
It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF
statement; you won't see a SELECT
statement in any of the branches.
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
No, just use the value directly:
begin if (select count(*) from table) > 0 then update table end if; end;
Note there is no need for an "else".
You can simply do it all within the update statement (ie no if
construct):
update table set ... where ... and exists (select 'x' from table where ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With