Hello, I’m trying to build a rating system. I have a query with three sub queries. I would like to check for NULL conditions within those sub queries. However I’m not sure what is the best way to do it. This is how I did it:(case when (select Rating from RatingUser where RatingUser.userID = 2 and RatingCharacteristics.CharID = RatingUser.CharID and SystemID = 2) is not null then (select Rating from RatingUser where RatingUser.userID = 2 and RatingCharacteristics.CharID = RatingUser.CharID and SystemID = 2) else 0 end) as Score,
It doesn't looks not that well optimized to me. And also I’m not sure if in this scenario SQL will execute the select statement twice?Below is my entire select statement withought checking for NULL conditions. SELECT Ratings.SystemID, Ratings.CharID, RatingCharacteristics.CharName, (SELECT Rating FROM RatingUser WHERE RatingUser.userID = 2 and RatingCharacteristics.CharID = RatingUser.CharID and SystemID = 2) RateUser,(SELECT COUNT(*) FROM RatingUser WHERE RatingUser.CharID = RatingCharacteristics.CharID) RatedBy,CONVERT(NUMERIC(7,2), (SELECT SUM(Rating) AS INT FROM RatingUser JOIN RatingSystem ON RatingSystem.SystemID = RatingUser.SystemID JOIN RatingCharacteristics rcs ON rcs.CharID = RatingUser.CharID WHERE RatingUser.SystemID = RatingSystem.SystemID AND RatingUser.CharID = RatingCharacteristics.CharID) / CAST( (SELECT COUNT(*) AS FLOAT FROM RatingUser WHERE RatingUser.CharID = RatingCharacteristics.CharID ) AS FLOAT)) Score FROM RatingsLEFT JOIN RatingSystem ON RatingSystem.SystemID = Ratings.SystemIDJOIN RatingCharacteristics ON Ratings.CharID = RatingCharacteristics.CharIDWHERE RatingSystem.SystemID = 1
About my database design, I have four tables:Ratings with columns SystemID and CharIDRatingUser – stores the results for every userRatingCharacteristics and RatingSystem – every System may have different characteristics for rate. And also I feel like my query is not that well optimized. If you have other ideas I will be happy to see it.Thanks in advance for you help.Rocco