Select FieldA, " if data exists in table two return true else false "
from Table1
Left join Table2 on Table1.Id=Table2.Id
This is how I currently do the requirement above:
Select FieldA, (case when Table2.Table2Id is not null then 1 else 0 End)
from Table1
Left join Table2 on Table1.Id=Table2.Id
Is there any replacement for the "Case" statement, to something like ifExists(Table2.Id) ?
You can use EXISTS, i guess you want the strings True/False, otherwise cast 1/0 to bit:
SELECT Id,
DataExists = CASE WHEN EXISTS
(
SELECT 1 FROM Table2 WHERE Table2.Id = Table1.Id
) THEN 'True' ELSE 'False' END
FROM dbo.Table1
For the sake of completeness:
SELECT Id,
DataExists = CAST((CASE WHEN EXISTS
(
SELECT 1 FROM Table2 WHERE Table2.Id = Table1.Id
) THEN 1 ELSE 0 END) AS BIT)
FROM dbo.Table1
May be you can use isNull as well.
Select FieldA, isnull((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName
from Table1
Related
For instance,
Select field1
From table1
when table1.field1 = 'S'
then (select field1,2,3,4,5,6,.....
form table1,2,3,4,5,6,....(with joins))
when table1.field1 = 'O'
then (select field1,2,3,4,5,6,.....
from table1,2,3,4,5,6,.....(with join))
I think I got what you need. One possible solution is to create a view with hardcoded where clauses on it. This is the idea:
CREATE VIEW ConditionalSelect AS
SELECT ...fields...
FROM ...tables...
JOIN ...joins...
WHERE table1.field1 = 'S'
AND ....
UNION
SELECT ...fields...
FROM ...tables...
JOIN ...joins...
WHERE table1.field1 = 'O'
AND ....
Then you can do this:
SELECT *
FROM ConditionalSelect
WHERE field1 = 'S'
NOTE: Both SELECT MUST have the same columns, columns types and column names, either the VIEW won't compile.
You could just do something like this:
DECLARE #Field1 VARCHAR(10) =
(
SELECT Field1
FROM table1
);
IF(#Field1 = 'S')
BEGIN
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t2.col1 = t1.col1
END
ELSE IF (#Field1 = 'O')
BEGIN
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t2.col1 = t1.col1
END
Saves you from creating a view
I'm trying to do something wonky, but I cant think of any other way to do it:
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = field1)) as does_exist
FROM my_table
This obviously fails because field1 doesn't exist at the time the result set is created. Does anyone know how to accomplish this?
You can use left join:
select distinct on (t1.field1) t1.field1, t2.id is not null as does_exist
from my_table t1
left join another_table t2 on t2.id = t1.field1
however your query should work as well:
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = my_table.field1)) as does_exist
FROM my_table
SELECT
my_table.field1 as field1,
case another_table.ID
when null then 0
else 1
end does_exist
FROM my_table
left outer join another_table on another_table.ID = my_table.field1
Here 1 is Exists, and 0 not exists
Using SQL Server 2008
Objective: Select a series of columns from table1 to insert into table2
Issue: In table2 there is one additional column that needs to be inserted that can be derived from a join between table1 and table 3
Current Code
SELECT
table1.name,
table1.email,
table1.phone,
CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END AS Active,
CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END AS RoleId,
(SELECT
table3.UserID AS ParentID
FROM
table3
INNER JOIN
table1 ON
table3.ID = table1.table3_ID)
FROM
table1
WHERE
table1.group_id = 3 AND
table1.status = 'active'
Currently this code does not work and returns "Subquery returned more than 1 value" error.
I am aware this may not be the correct way to use a nested select, what would be the correct way to do this?
Additional data can be provided if necessary.
Thank you in advance.
The problem is that you want a correlated subquery. That means that you need to remove table1 from the subquery:
SELECT table1.name, table1.email, table1.phone,
(CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END) AS Active,
(CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END) AS RoleId,
(SELECT table3.UserID
FROM table3
WHERE table3.ID = table1.table3_ID
) as ParentID
FROM table1
WHERE table1.group_id = 3 AND table1.status = 'active';
If there is more than one possible match in table3, then you will need something like select top 1 table3.UserId or select max(table3.UserId).
You could probably solve the more than 1 value error by adding a TOP 1 to the 'select .. from table ' part of the select. But it may be easier to just inner join them.
SELECT
table1.name,
table1.email,
table1.phone,
CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END AS Active,
CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END AS RoleId,
table3.UserID
FROM table1
INNER JOIN table3 ON
table3.ID = table1.table3_ID
WHERE
table1.group_id = 3 AND
table1.status = 'active'
If you really (really really really) want to use subquery instead of join your code is quite well. You should change your subquery's join as below.
SELECT
table1.name,
table1.email,
table1.phone,
CASE WHEN table1.status = 'active' THEN 1 ELSE 0 END AS Active,
CASE WHEN table1.group_id = 3 THEN 5 ELSE table1.group_id END AS RoleId,
(SELECT
table3.UserID
FROM
table3
WHERE
table3.ID = table1.table3_ID) AS ParentID
FROM
table1
WHERE
table1.group_id = 3 AND
table1.status = 'active'
Apart from this I put an alias ParentID outside the subquery.
Please consider below code with table aliases. It's good practice to use it because the code is more readable.
SELECT
t1.name,
t1.email,
t1.phone,
CASE WHEN t1.status = 'active' THEN 1 ELSE 0 END AS Active,
CASE WHEN t1.group_id = 3 THEN 5 ELSE t1.group_id END AS RoleId,
(SELECT
table3.UserID
FROM
table3 t3
WHERE
t3.ID = t1.table3_ID) AS ParentID
FROM
table1 t1
WHERE
t1.group_id = 3 AND
t1.status = 'active'
This is the structure of my existing SQL query :
SELECT * FROM (
SELECT *, 'A' AS Status FROM Table1
WHERE Field1 NOT IN
(
SELECT Field1 FROM Table2 WHERE Field 1 = 'val' AND ...
)
UNION
SELECT *, 'B' AS Status FROM Table1
WHERE Field1 IN
(
SELECT Field1 FROM Table2 WHERE Field 1 = 'val' AND ...
)
) AS Result
Here I'm selecting two sets of data from a table and assigning two different values (A & B) for the Status column and Union both sets in to one as Result.
Problem with this method is, it needs to duplicate the inner select query SELECT Field1 FROM Table2 WHERE Field 1 = 'val' AND ... (my original sql query is bit complex than the shown above)
How can I rewrite this as a single Select query? Is it possible or not?
You could simply move the WHERE condition to a CASE expression, like this:
SELECT
*,
CASE
WHEN Field1 IN (
SELECT Field1 FROM Table2 WHERE Field1 = 'val' AND ...
)
THEN 'B'
ELSE 'A'
END AS Status
FROM Table1
;
You could also use a LEFT JOIN method like others suggested, but if Table2 produces duplicates for the specified filter, you might get duplicates in the output as well. To avoid that, you would probably need to use a derived table that only returns distinct values, something like this:
SELECT
t1.*,
CASE
WHEN t2.Field1 IS NULL THEN 'A'
ELSE 'B'
END AS Status
FROM Table1 t1
LEFT JOIN (
SELECT DISTINCT Field1 FROM Table2 WHERE Field1 = 'val' AND ...
) t2
ON t1.Field1 = t2.Field2
;
you can simply use LEFT JOIN on this,
SELECT a.*,
CASE WHEN b.field1 IS NULL
THEN 'A'
ELSE 'B'
END AS Status
FROM table1 a
LEFT JOIN table2 b
ON a.field1 = b.field1 AND
b.field1 = 'VAL'
Please check the below query, which works if there is only one condition of Field1=’val’ on Table2. If there are multiple where conditions, then go for LEFT JOIN.
SELECT
*,
(CASE WHEN Field1='val' THEN 'B' ELSE 'A' END) AS Status
FROM
Table1
U can achieve this by using LEFT JOIN and CASE as follows
SELECT a.*,
(CASE b.Field1
WHEN 'Val'
THEN 'B' ELSE 'A' END) as status
FROM Table1 a LEFT JOIN Table2 b ON a.field1 =b.field1
If multiple conditions are there for status try the following one
SELECT a.*,
(CASE
WHEN (SELECT COUNT(Field1)
FROM Table2
WHERE field1 =a.field1 AND Field 1 ='val' AND ...) >0
THEN 'B' ELSE 'A' END) as status
FROM Table1 a LEFT JOIN Table2 b ON a.field1 =b.field1
How to select Boolean value from sub query with IF EXISTS statement (SQL Server)?
It should be something like :
SELECT
TABLE1.Id,
NewFiled = (IF EXISTS(SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
SELECT 'TRUE'
ELSE
SELECT 'FALSE')
FROM TABLE1
Use CASE:
SELECT
TABLE1.Id,
CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
If TABLE2.ID is Unique or a Primary Key, you could also use this:
SELECT
TABLE1.Id,
CASE WHEN TABLE2.ID IS NOT NULL
THEN 'TRUE'
ELSE 'FALSE'
END AS NewFiled
FROM TABLE1
LEFT JOIN Table2
ON TABLE2.ID = TABLE1.ID
You can also use ISNULL and a select statement to get this result
SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
Use a CASE statement and do it like this:
SELECT
T1.Id [Id]
,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2]
FROM
TABLE1 [T1]
LEFT OUTER JOIN
TABLE2 [T2]
ON
T2.Id = T1.Id
You can use EXISTS to check if a column value exists in a different table.
SELECT
TABLE1.id,
EXISTS (SELECT 1 FROM TABLE2 WHERE TABLE2.id = TABLE1.id) AS columnName
FROM TABLE1
Example:
CREATE TABLE TABLE1 (
id INTEGER PRIMARY KEY,
some_column TEXT NOT NULL
);
CREATE TABLE TABLE2 (
id INTEGER PRIMARY KEY,
some_column TEXT NOT NULL
);
INSERT INTO TABLE1 VALUES
(111, 'lorem ipsum'),
(222, 'and'),
(333, 'some'),
(444, 'random'),
(123, 'strings');
INSERT INTO TABLE2 VALUES
(111, 'lorem ipsum'),
(444, 'random'),
(123, 'strings');
SELECT
TABLE1.id,
EXISTS (SELECT 1 FROM TABLE2 WHERE TABLE2.id = TABLE1.id) AS columnName
FROM TABLE1
Output:
id
someColumn
111
1
123
1
222
0
333
0
444
1