What is a self join? Explain it with an example?

Answer Posted / lalithg

CREATE TABLE candytest
(kidId char(2),
candycolor varchar(10)
)
GO

INSERT INTO candytest SELECT 'K1', 'Yellow'
INSERT INTO candytest SELECT 'K1', 'Red'
INSERT INTO candytest SELECT 'K2', 'Red'
INSERT INTO candytest SELECT 'K2', 'Blue'
INSERT INTO candytest SELECT 'K3', 'White'
INSERT INTO candytest SELECT 'K3', 'Red'
INSERT INTO candytest SELECT 'K3', 'Yellow'
Go
--Now to find those kidid's which has both yellow and red
colored candies, we can write query as:

SELECT c1.kidid
FROM candytest AS c1 JOIN candytest AS c2
ON c1.candycolor = 'Red' AND c2.candycolor = 'Yellow'
AND c1.kidid = c2.kidid

Is This Answer Correct ?    85 Yes 69 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is database design and development?

609


Explain what a database is?

615


Explain about xml databases?

626


Why does this query return 0?

626


In which database can extended stored procedures be added?

534






If a column is an image value type, how you can compare column values? How can you use this column in join clause?

598


Explain about a primary key?

574


Explain about the storage and physical database design?

535


Explain about network model?

591


What are data modelling techniques?

531


How to replace not in with not exist?

1470


Write short notes on manual refreshes.

2296


There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

1998


What is the maximum length of an extended property?

562


To convert IDMS to DB2, how to deal with IDMS occurs and redefined clause?

3442