Utkarsh Utkarsh - 2 months ago 11
SQL Question

How to check primary key condition in a SQL query?

The problem statement is :

Let W(A,B) be a relation schema. The domain of A is

INTEGER
and the domain of B is
VARCHAR(5)
.

Write a SQL query with returns the A-values of tuples in W if A is a
primary key of W. Otherwise, i.e., if A is not a primary key, then the
query should return the A-values of tuples in W for which the primary
key property is violated.

How can I check primary key condition in a SQL query?

Answer

I figured out the answer to this problem which is as follows:

SELECT W."A" FROM "W" W WHERE NOT EXISTS
(SELECT W1."A" FROM "W" W1,"W" W2 WHERE
W1."A" = W2."A" AND W1."B" <> W2."B")
UNION
SELECT DISTINCT W."A" FROM "W" W WHERE EXISTS
(SELECT * FROM "W" W1,"W" W2 WHERE W."A" = W1."A" AND
W1."A" = W2."A" AND W1."B" <> W2."B")