tags:

views:

349

answers:

7

Hi,

Trying to figure out if this is possible select columns only where something exists?

Example, I have the following query

select phone, phone2
from jewishyellow.users
where phone like '813%'
and phone2

Basically, I'm trying to select only the rows where phone starts with 813 and phone2 has something in it?

+1  A: 

Compare value of phone2 with empty string:

select phone, phone2 
from jewishyellow.users 
where phone like '813%' and phone2<>""

Note that NULL value is interpreted as false.

Ivan Nevostruev
Single quotes, not double quotes.
OMG Ponies
@OMG Ponies: Why?
Ivan Nevostruev
`phone2<>""` will not make it past any SQL syntax checker.
OMG Ponies
@OMG Ponies: But it works in mysql. This is the only checker that's matter
Ivan Nevostruev
This actually worked perfectly! Thanks
mike
@ivan: News to me, sorry about that.
OMG Ponies
+1  A: 
select phone, phone2 from jewishyellow.users 
where phone like '813%' and phone2 is not null
klausbyskov
A: 
SELECT phone, phone2 
FROM jewishyellow.users 
WHERE phone like '813%' and (phone2 <> "");

May need some tweakage depending on what your default value is. If you allowed Null fill, then you can do "Not NULL" instead, which is obviously better.

Satanicpuppy
I won't mark you down but: 1) There is no `NOT()` function in MySQL 2) `phone2=""` will not make it past any SQL syntax checker.
OMG Ponies
Heh, sorry. I use a lot of different SQL servers.
Satanicpuppy
+3  A: 

To check if field is NULL use IS NULL, IS NOT NULL operators.

MySql reference http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

st.stoqnov
+1  A: 

If there are spaces in the phone2 field from inadvertant data entry, you can ignore those records with the IFNULL and TRIM functions:

SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
    AND TRIM(IFNULL(phone2,'')) <> '';
micahwittman
+1  A: 

Use:

SELECT t.phone, 
       t.phone2 
  FROM jewishyellow.users t
 WHERE t.phone LIKE '813%' 
   AND t.phone2 IS NOT NULL
OMG Ponies
+2  A: 

Check for NULL and empty string values:

select phone
, phone2 
from users 
where phone like '813%' 
and trim(coalesce(phone2, '')) <>''

N.B. I think COALESCE() is SQL standard(-ish), whereas ISNULL() is not.

davek