Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a SELECT statement within a WHERE clause

SELECT * FROM ScoresTable WHERE Score = 
  (SELECT MAX(Score) FROM ScoresTable AS st WHERE st.Date = ScoresTable.Date)

Is there a name to describe using a SELECT statement within a WHERE clause? Is this good/bad practice?

Would this be a better alternative?

SELECT ScoresTable.* 
FROM ScoresTable INNER JOIN 
  (SELECT Date, MAX(Score) AS MaxScore 
  FROM ScoresTable GROUP BY Date) SubQuery 
  ON ScoresTable.Date = SubQuery.Date 
  AND ScoresTable.Score = SubQuery.MaxScore

It is far less elegant, but appears to run more quickly than my previous version. I dislike it because it is not displayed very clearly in the GUI (and it needs to be understood by SQL beginners). I could split it into two separate queries, but then things begin to get cluttered...

N.B. I need more than just Date and Score (e.g. name)

like image 225
jofitz Avatar asked Jun 21 '11 11:06

jofitz


People also ask

Can you use a SELECT statement in a WHERE clause?

The WHERE clause can be used with SQL statements like INSERT, UPDATE, SELECT, and DELETE to filter records and perform various operations on the data.

Is subquery not allowed in WHERE clause?

Subqueries must appear on the right hand side of an expression. Nested subqueries are not supported. Only one subquery expression is allowed for a single query. Subquery predicates must appear as top level conjuncts.

Can we use 2 conditions in WHERE clause?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.

Can we use on and WHERE in same query?

Yes. ON should be used to define the join condition and WHERE should be used to filter the data.


1 Answers

It's called correlated subquery. It has it's uses.

like image 71
Mladen Prajdic Avatar answered Sep 30 '22 20:09

Mladen Prajdic