Grigor
Grigor

Reputation: 4049

SQL Server get number of rows

I have a table called replies and it has a column named topic_id.

What I want to do is count how many rows have the topic_id 1.

I tried

SELECT COUNT(*) 
FROM [***].[replies] 
WHERE [***].[topic_id] = '1'

But in this case I don't know if this is a valid query. If it is, how can I pull it back into a variable called $num_rows in my php code?

Note: * is actually a prefix I covered.

Upvotes: 2

Views: 1215

Answers (1)

James Johnson
James Johnson

Reputation: 46057

Something like this should work:

--declare the variable
DECLARE @num_rows INT

--get the total number of rows
SELECT @num_rows = COUNT(*) FROM replies WHERE topic_id = 1

--get a distinct count of rows (if for some reason you need it)
SELECT @num_rows = COUNT(DISTINCT reply_id) FROM replies WHERE topic_id = 1

--return the result set
SELECT @num_rows AS num_rows

If you just want to return a column called num_rows though, this would be a much more efficient approach:

SELECT COUNT(*) AS num_rows FROM replies WHERE topic_id = 1

Upvotes: 3

Related Questions