Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL use EXISTS as Column

I'm wondering whether I can use EXISTS (or something similar) in column like this:

SELECT Column1,
       Column2,
       EXISTS (SELECT 1 FROM Table2 T2 WHERE T2.Column = T1.Column) AS IsFlag
FROM Table1

I know I can do something similar with Count()

SELECT Column1,
       Column2,
       (SELECT Count(*) FROM Table2 T2 WHERE T2.Column = T1.Column) AS IsFlag
FROM Table1

But that might not be very efficient when Table2 is large

like image 238
Andrej K Avatar asked Oct 09 '12 19:10

Andrej K


People also ask

How do you use exists instead of in in SQL Server?

If you have a small list of static values (and the values are not present in some table), the IN operator is preferred. If you need to check for existence of values in another table, the EXISTS operator is preferred as it clearly demonstrates the intent of the query.

Can we use exists in subquery?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do you use exists and not exists in SQL?

If EXISTS (subquery) returns at least 1 row, the result is TRUE. If EXISTS (subquery) returns no rows, the result is FALSE. If NOT EXISTS (subquery) returns at least 1 row, the result is FALSE. If NOT EXISTS (subquery) returns no rows, the result is TRUE.

How do you check if a column exists in SQL?

Checking Existence of the Column: For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.


2 Answers

Try this

SELECT Column1,
       Column2,
       CASE WHEN EXISTS (SELECT 1 FROM Table2 T2 
       WHERE T2.Column = T1.Column) then 1 ELSE 0 END AS IsFlag
FROM Table1
like image 84
SQLMenace Avatar answered Oct 07 '22 06:10

SQLMenace


CASE 
    WHEN 
        EXISTS (SELECT 1 FROM Table2 T2 WHERE T2.Column = T1.Column) 
    THEN 1 
    ELSE 0 
END AS IsFlag
like image 31
Louis Ricci Avatar answered Oct 07 '22 06:10

Louis Ricci