Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if column value exists in another column in SQL

Tags:

I need a SQL query that compares two values and returns an ID.

I have this table:

ID  Calling_ID  Called_ID 1   27          10 2   15          20 3   80          90 4   90          88 5   60          30 6   88          40 7   15          60 8   30          40 9   27          95 10  40          30 

How do I check if each value in the Calling_ID column exists in the Called_ID column and then return the ID? The above data would return 88, 30, 40.

like image 311
Hussein.M Avatar asked Feb 15 '14 16:02

Hussein.M


People also ask

How do you check if a substring is present in a column in SQL?

MySQL LOCATE() Function The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search.

How do you check if a column exists in SQL?

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE table_name = 'SampleTable' AND column_name = 'Name' ) SELECT 'Column exists in table' AS [Status] ; ELSE SELECT 'Column does not exist in table' AS [Status]; You can see, the column Name exists in table.

How do I check if two columns are equal in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.


Video Answer


1 Answers

This should work:

SELECT ID FROM [TableName] WHERE Calling_ID IN ( SELECT Called_ID FROM [TableName] ) 
like image 162
Abhishek Chaudhary Avatar answered Oct 15 '22 14:10

Abhishek Chaudhary