Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query at least one of something

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!

like image 988
atp Avatar asked Jul 07 '10 17:07

atp


People also ask

What is at least in SQL?

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.

Which SQL keyword checks whether a query returns at least one row?

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.

How do I SELECT a minimum in SQL?

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.

How do you order from least to greatest in SQL?

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.


1 Answers

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.

like image 109
OMG Ponies Avatar answered Sep 16 '22 22:09

OMG Ponies