CooBoo
CooBoo

Reputation: 3

If word in column A starts with letters in column B then in SQL

My database Elements have som inputs.

COLUMN A
Name:
Helium
Lithium

COLUMN B
Symbol:
He
Li

If Name starts with symbols in column B, then 'Yes' should be printing in a new column C.
Else 'No'

Not sure how to write in SQL

Upvotes: 0

Views: 424

Answers (3)

Sick Ranchez
Sick Ranchez

Reputation: 228

select ColumnA, ColumnB, (Case When SUBSTRING (ColumnA, 1, 2) = ColumnB Then 'Yes' Else 'No' End) as ColumnC from Elements

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1271111

You can use exists:

select a.*,
       (case when exists (select 1 from b where a.col like b.col || '%')
             then 'Yes' else 'No'
        end) as flag
from a;

Note: || is the standard operator for string concatenation. Your database may not support the operator, but it would have a similar function or operator.

Upvotes: 0

GMB
GMB

Reputation: 222682

Assuming that these two columns belong to the same table and that the values are stored on the same row, you can use like and a case expression:

select e.*, 
    case when columna like concat(columnb, '%') then 'Yes' else 'No' end as columnc
from elements e

The actual function to concatenate strings varies across databases. concat() is quite widely supported; the standard operator is ||, so columnb || '%'.

Upvotes: 0

Related Questions