Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more: , +
Hello Everyone.
I have big confuse in two query. I want to count total records in a table which primary key is in another table. i user two types of query but both query giving me different result. so please help me

SQL
select COUNT(*) from first_tbl where isApprExam =1 and Code in (select schlcode from journals_tbl)

select COUNT(*) from regmaster inner join journals_tbl j on regmaster.Code=j.schlcode where regmaster.isApprExam =1


Please tell me why they giving different answer and which is right query.
Posted

If a row in the first table can be joined to several rows in the second table your query will count every occurrence.
In the case of the IN clause every corresponding row will be counted only once.

So if you want the number of rows in first_tbl/regmaster that has a corresponding row in journals_tbl you should use IN or EXISTS
 
Share this answer
 
Solution 2 answers your question quite nicely.

But here are additional SQL count examples which may make it clearer:
SQL
--taking regmaster and first_tbl to be the same table

select COUNT(distinct regmaster.Code) 
from regmaster 
inner join journals_tbl j 
	on regmaster.Code = j.schlcode 
where regmaster.isApprExam = 1
;
--should give the same count as
select COUNT(*) from first_tbl where isApprExam =1 and Code in (select schlcode from journals_tbl)



select COUNT(*) 
from journals_tbl 
where Code in (select schlcode from regmaster where isApprExam = 1)
;
--should give the same count as
select COUNT(*) from regmaster inner join journals_tbl j on regmaster.Code=j.schlcode where regmaster.isApprExam =1

Hopefully I got those right, and if so hope it helps you out in understanding.
 
Share this answer
 
SQL
Hi,

Don't use cont(*) its decrease the performance.

select COUNT(1) from regmaster inner join journals_tbl j on regmaster.Code=j.schlcode where regmaster.isApprExam =1
 
Share this answer
 
Comments
Divyam Sharma 3-Nov-15 7:41am    
ok.. but tell me which query is right and why?
Jörgen Andersson 3-Nov-15 15:46pm    
That's simply wrong.
Count(*) is specifically defined in SQL92 to return the cardinality of the query.
And counting the rows where 1 is not null is less efficient than just counting the rows.
That said, the optimizer would realize that it's the same thing and give you the same plan.
Richard Deeming 4-Nov-15 11:54am    
Count(1) and Count(*) are identical. See this StackOverflow answer[^] for a good explanation.

Answer reported as "Inaccurate/misleading".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900