Wednesday, June 11, 2008

Random (yet useful) SQL Commands

CHECKING IF A FIELD IS NULL:
SELECT lastName, ID
FROM tbl_customers
WHERE lastName IS NULL OR ID IS NULL
** THIS statement pulls all rows that either the lastName OR the ID is null. **

You could also do this if you wanted to replace NULLs with something:
WHERE ISNULL(lastName, 'test')
*This replaces all lastName 's that are null with the word 'test'



USING LIKE AND WILDCARDS:
There's a million uses for the LIKE keyword.

Use LIKE for incomplete words
Use % for anything after or before
Use _ for a single character

ex:
SELECT * FROM tbl_people WHERE lastname LIKE 'A%' - everyone who's last name starts with an A
SELECT * FROM tbl_people WHERE lastname LIKE '%A%' - use this to choose anything before and after.
SELECT * FROM tbl_people WHERE lastname LIKE 'Anders_n' - uses the _ wildcard which will ONLY give ONE char - so here you would ONLY get Anderson's or Andersen's but never Andershen's (because we all know how many Andershen's there are out there!)

Finally - dont forget that we can use the NOT keyword in conjuction with LIKE -- so if you DIDNT want to see anyone whose names started with Ander (like those dreaded Andershen's!) - we could write.
SELECT * FROM tbl_people WHERE lastname NOT LIKE 'Ander%'
more to come...

No comments: