WITH
    permitted as (
        SELECT
            folder_id
        FROM
            permissions
        WHERE
            user_id = $1
    )
SELECT
    folder_id
FROM
    folders
WHERE
    folder_id IN (
        SELECT
            folder_id
        FROM
            permitted
    )
    AND parent_folder_id NOT IN (
        SELECT
            folder_id
        FROM
            permitted
    )