ELSE SELECT nothing/blank
You can assign a variable:
IF EXISTS(SELECT 1 FROM Account WHERE Account.username=@Username)
BEGIN
SELECT Status
FROM Account
WHERE Account.username = @Username;
END;
ELSE
BEGIN
DECLARE @X int;
SELECT @X = 0;
END;
sql:using not in and select nothing
Don't use NOT IN
with a subquery. As Jarlh says in a comment, when any value is NULL
, then no rows are returned at all.
Instead, get used to NOT EXISTS
:
select t.id, 'Leaf' as type
from tree t
where not exists (select 1 from tree t2 where t2.p_id = t.id);
This behaves as you would expect.
Although you could fix the problem using WHERE t2.p_id IS NOT NULL
in the subquery, you might as well use NOT EXISTS
. At some future point, you'll find yourself debugging another NOT IN
where you left out the WHERE
clause.
SQL select dummy data
You would have to use UNION
with two select statements:
SELECT 'dummy1' AS [Dummies]
UNION
SELECT 'dummy2'
This will produce a single column.
Dummies
-------
dummy1
dummy2
SQL - If Select returns nothing then do another Select
You can do this in one statement, assuming the columns are the same:
SELECT *
FROM table
WHERE criteria = criteria
UNION ALL
SELECT *
FROM table
WHERE criteria2 = criteria2 AND
NOT EXISTS (SELECT 1 FROM table WHERE criteria = criteria);
Select dummy values if where clause returns zero rows
The problem is, that if the WHERE clause eliminates all rows, you end up with an empty set.
One way around it, is to use an aggregate function to force one row in the result.
Then, with COALESCE (or ISNULL), you can assign your default values.
This solution is only feasible if:
- your basic query always returns exactly 0 or 1 row
- your columns do not contain NULL
- the selected columns can be aggregated (e.g. it will not work for text columns)
- your default values have the same data type as the columns
For example:
select COALESCE(MAX(step_id),123456) AS step_id,
COALESCE(MAX(step_name),'There are no step_id matching the WHERE clause') AS step_name
from msdb.dbo.sysjobhistory
where step_id = 9999
Select Null statement, Is it possible?
Is this what you need
SELECT null FROM table where password= 'abc'
Related Topics
Get Month and Year from a Datetime in SQL Server 2005
Difference Between Different Types of SQL
Maintaining Referential Integrity - Good or Bad
Postgresql Recursive Self Join
Best Way to Get the Next Id Number Without "Identity"
Inserting Image into Blob Oracle 10G
Easiest Way to Copy a MySQL Database
Case in Statement with Multiple Values
How Much Does Wrapping Inserts in a Transaction Help Performance on SQL Server
Difference Between Drop Table and Truncate Table
How Different Is Postgresql to MySQL
Bulk Insert, SQL Server 2000, Unix Linebreaks
Isdate Function in SQL Evaluates Invalid Dates as Valid
How to Gracefully Include Formatted SQL Strings in an R Script