Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case statement to determine if I should union

I currently want to do some sort of conditional union. Given the following example:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Say I wanted to only union the second statement if the count of 'users' was >=2 , otherwise do not union the two.

In summary I want to append a table with a row if the table only has 2 or more values.

like image 343
BlueBird Avatar asked May 19 '15 13:05

BlueBird


People also ask

What is a union statement?

The UNION operator is used to combine the result-set of two or more SELECT statements. Every SELECT statement within UNION must have the same number of columns. The columns must also have similar data types. The columns in every SELECT statement must also be in the same order.

Under what conditions can a union clause be used?

The Union Clause is used to combine two separate select statements and produce the result set as a union of both the select statements. NOTE: The fields to be used in both the select statements must be in same order, same number and same data type.

Can we use union in CASE statement in SQL?

The CASE statement can potentially enhance performance by minimizing the number of times the data is read. ORDER BY NAME; This simple SQL statement uses UNION to put together the results of three queries against the SYSTABLES table.

Can we use CASE statement in where clause?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.


2 Answers

You could use an ugly hack something like this, but I think Tim's answer is better:

SELECT  age, name
FROM    users
UNION ALL

SELECT  25, 'Betty'
WHERE (SELECT COUNT(*) FROM users) > 1;
like image 179
Zohar Peled Avatar answered Sep 22 '22 13:09

Zohar Peled


If it's in a stored-procedure you could use If...Else:

IF (SELECT COUNT(*) FROM users) < 2
 BEGIN
  SELECT  age, name
  FROM    users
  END
ELSE
  SELECT  age, name
  FROM    users
  UNION ALL
  SELECT  25 AS age, 'Betty' AS name

Otherwise you could try something like this:

SELECT  age, name
  FROM    users
  UNION ALL
  SELECT  TOP 1 25 AS age, 'Betty' AS name
  FROM users
  WHERE (SELECT COUNT(*) FROM users) >= 2

Note that i've used UNION ALL since it doesn't seem that you want to eliminate duplicates.

Played around here: http://sqlfiddle.com/#!6/a7540/2323/0

Edit: Instead of my second approach i prefer Zohar's. So if you can use If....Else prefer that otherwise WHERE (SELECT COUNT(*) FROM users) > 1 without a table.

like image 31
Tim Schmelter Avatar answered Sep 20 '22 13:09

Tim Schmelter