1

I'm having trouble using/understanding the SQL ALL operator. I have a table FOLDER_PERMISSION with the following columns:

+----+-----------+---------+----------+
| ID | FOLDER_ID | USER_ID | CAN_READ |
+----+-----------+---------+----------+
|  1 |     34353 |   45453 |        0 |
|  2 |     46374 |  342532 |        1 |
|  3 |     46374 |   32352 |        1 |
+----+-----------+---------+----------+

I want to select the folders where all the users have permission to read, how could I do it?

0

4 Answers 4

1

Use aggregation and having:

select folder_id
from t
group by folder_id
having min(can_read) = 1;
Sign up to request clarification or add additional context in comments.

Comments

0

Gordon's answer seems better but for the sake of completeness, using ALL a query could look like:

SELECT x1.folder_id
       FROM (SELECT DISTINCT
                    fp1.folder_id
                    FROM folder_permission fp1) x1
       WHERE 1 = ALL (SELECT fp2.can_read
                             FROM folder_permission fp2
                             WHERE fp2.folder_id = x1.folder_id);

If you have a table for the folders themselves replace the derived table (aliased x1) with it.

But this only respects users present in folder_permissions. If not all users have a reference in that table you possibly won't get the folders really all users can read.

Comments

0

You can do aggregation :

SELECT fp.FOLDER_ID 
FROM folder_permission fp
GROUP BY fp.FOLDER_ID 
HAVING SUM( can_read = 0 ) = 0;

You can also express it :

SELECT fp.FOLDER_ID 
FROM folder_permission fp
GROUP BY fp.FOLDER_ID 
HAVING MIN(CAN_READ) = MAX(CAN_READ) AND MIN(CAN_READ) = 1;

Comments

0

If you wanted to return the full matching records, you could try using some exists logic:

SELECT ID, FOLDER_ID, USER_ID, CAN_READ
FROM yourTable t1
WHERE NOT EXISTS (SELECT 1 FROM yourTable t2
                  WHERE t2.FOLDER_ID = t1.FOLDER_ID AND t2.CAN_READ = 0);

screen capture of demo below

Demo

The existence of a matching record in the above exists subquery would imply that there exist one or more users for that folder who do not have read access rights.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.