Is there a way to get a column indicating the number of NULL fields in a row? This would be within a SELECT statement.
For Example:
Field1 Field2 Num_Null
-----------------------
NULL "A" 1
UPDATE: I want this query so I can sort based on how many Affiliates sales there are of a given Book. So having 3 affiliates would be sorted higher than having 2, regardless of which ones. There are about seven affiliates in my database, and that’s subject to grow. So any query requiring that each Affiliate field be specified would probably be too long
The table:
Affiliates_Cache – Primary key is Affiliate_ISBN, has the prices of the book on various affiliates (NULL if its not available). Affiliates_Cache is the one where i want to count the number of NULLs
I’m not sure if there are neater methods, but this should work:
Test case:
Result:
UPDATE: Further to the updated question:
If you have columns in your table that look like
affiliate_1,affiliate_2, etc, this is rarely a good idea as you would be mixing data with the metadata. In general, a recommended fix is to use another dependent table for the users-to-affiliates relationships, as in the following example:Then sorting the
userstable by the number of affiliates will look something like this:The advantages are plenty, but most importantly it makes queries such as the above easy to write, and flexible enough to work with any number of affiliates (an not limited by the number of columns you allocated).