I have a bunch of Users, each of whom has many Posts. Schema:
Users: id
Posts: user_id, rating
How do I find all Users who have at least one post with a rating above, say, 10?
I'm not sure if I should use a subQuery for this, or if there's an easier way.
Thanks!
Return valueThe LEAST() function returns the smallest value from the list of arguments sent as a parameter. If any argument is NULL , then this function will return NULL . If the arguments are a mixture of integers and strings, then this function will compare them as numbers.
The SQL EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.
ASC | DESC The ASC sorts the result from the lowest value to the highest value while the DESC sorts the result set from the highest value to the lowest one. If you don't explicitly specify ASC or DESC , SQL Server uses ASC as the default sort order. Also, SQL Server treats NULL as the lowest value.
To find all users with at least one post with a rating above 10, use:
SELECT u.*
FROM USERS u
WHERE EXISTS(SELECT NULL
FROM POSTS p
WHERE p.user_id = u.id
AND p.rating > 10)
EXISTS doesn't care about the SELECT statement within it - you could replace NULL with 1/0, which should result in a math error for dividing by zero... But it won't, because EXISTS is only concerned with the filteration in the WHERE clause.
The correlation (the WHERE p.user_id = u.id) is why this is called a correlated subquery, and will only return rows from the USERS table where the id values match, in addition to the rating comparison.
EXISTS is also faster, depending on the situation, because it returns true as soon as the criteria is met - duplicates don't matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With