1

I want to get sum of number of records in two tables in a variable. Following is the code:

declare v_sum int default 0;
declare v_count2 int default 0;

select count(*) into v_sum
from table1;

select count(*) into v_count2 
from table2;

set v_sum = v_sum + v_count2;

Is there any way to directly select and add the table2 count in v_sum without creating v_count2 variable.

3 Answers 3

1

You don't need two variables. One way is to combine both sets and then do COUNT:

SELECT COUNT(*)
INTO v_sum
FROM (SELECT 1 AS c
 FROM table1
 UNION ALL
 SELECT 1
 FROM table2) AS sub

EDIT:

SELECT SUM(c)
INTO v_sum
FROM (SELECT COUNT(*) AS c
     FROM table1
     UNION ALL
     SELECT COUNT(*)
     FROM table2) AS sub
Sign up to request clarification or add additional context in comments.

2 Comments

Should I use this if tables contains millions of records? or write separate queries would be better?
@ctor Compare both solution.
1

You can use the query directly, e.g.:

SET v_sum = v_sum + (SELECT COUNT(*) FROM table2);

Comments

0

One way to avoid variable could be:

select v_sum + count(*) into v_sum
from table2;

Comments

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.