HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

SQL Minimum Row count

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
sqlcountrowminimum

Problem

I have a stored procedure that allows users to pass in parameters.

SELECT * 
FROM Table1
WHERE columnA =@paramA, ColumnB=@paramB....


I need to hide the results if there are less than 10 rows, but return them if there are more than 10. Is there a clean way to do this? Any help would be great.

Solution

You can use count(*) over() to make sure your result set has that many rows.

You didn't say what to do if the rows = 10, only > or = based on what you want.

DB FIDDLE

select *
into mytable
from (select 'X' as c1) x
cross apply (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10))as y(Y)

select * from mytable

--change the 10 to 11 to see it not return
select * from
(
select *, COUNT(*) OVER() CT
from mytable
where c1 = 'X'
) sub
where CT > 10

Code Snippets

select *
into mytable
from (select 'X' as c1) x
cross apply (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10))as y(Y)

select * from mytable

--change the 10 to 11 to see it not return
select * from
(
select *, COUNT(*) OVER() CT
from mytable
where c1 = 'X'
) sub
where CT > 10

Context

StackExchange Database Administrators Q#245001, answer score: 8

Revisions (0)

No revisions yet.