Postgresql: How to write insert query using where clause

Solution 1:

You just need to make sure both users exist in the Users table (execute two queries against the Users table) and then insert a record into the Teams table.
It's better to use an explicit transaction to get both users and insert a record into Teams.

To get either you have a user in DB you can use count:

const whereClause = userId ?  {
            where: {
                id: userId,
            }
} : {}
const userCount = await db.User.count({
            where: {
                id: userId
            }
})
const userExists = count === 1;

The same way you can check leadId