String and dates

From SQLZoo
Jump to navigation Jump to search

Search for a string across columns

schema:scott
DROP TABLE bedroom
 CREATE TABLE bedroom(
  name VARCHAR(20),
  floorcolor VARCHAR (20),
  ceilingcolor VRACHAR(20),
  wallcolor VARCHAR(20));
INSERT INTO bedroom VALUES ('Jim','RED','GREEN','YELLOW');
INSERT INTO bedroom VALUES ('Bob','YELLOW','BLUE','BLACK');
INSERT INTO bedroom VALUES ('Allan','BLUE','PINK','BLACK');
INSERT INTO bedroom VALUES ('George','BLUE','GREEN','OAK');
SELECT name FROM bedroom
WHERE floorcolor = 'YELLOW'
OR ceilingcolor = 'YELLOW'
OR wallcolor = 'YELLOW'

Using OR increases the chances for careless mistakes instead CONCAT could be used to make the query more efficient. To avoid problems make sure to add in separators and if a value cna be null make sure to use it is wrapped in COALESCE OR NVL for example: COALESCE(floorcolor,).

SELECT name FROM bedroom
WHERE CONCAT (':',floorcolor,':',ceilingcolor,':',wallcolor,':')
LIKE '%:YELLOW:%'
DataWars, Data Science Practice Projects - LogoDataWars: Practice Data Science/Analysis with +100 Real Life Projects