Difference between revisions of "String over columns"

From SQLZOO
Jump to: navigation, search
Line 2: Line 2:
 
<div class='ht'>
 
<div class='ht'>
 
<div class=params>schema:scott</div>
 
<div class=params>schema:scott</div>
<source lang=sql class='tidy'>DROP TABLE bedroom</source>
+
<source lang=sql class='tidy'>DROP TABLE bedrooms</source>
<source lang=sql class='setup'> CREATE TABLE bedroom(
+
<source lang=sql class='setup'> CREATE TABLE bedrooms(
 
   name VARCHAR(20),
 
   name VARCHAR(20),
 
   floorcolor VARCHAR(20),
 
   floorcolor VARCHAR(20),
 
   ceilingcolor VRACHAR(20),
 
   ceilingcolor VRACHAR(20),
 
   wallcolor VARCHAR(20));
 
   wallcolor VARCHAR(20));
INSERT INTO bedroom VALUES ('Jim','RED','GREEN','YELLOW');
+
INSERT INTO bedrooms VALUES ('Jim','RED','GREEN','YELLOW');
INSERT INTO bedroom VALUES ('Bob','YELLOW','BLUE','BLACK');
+
INSERT INTO bedrooms VALUES ('Bob','YELLOW','BLUE','BLACK');
INSERT INTO bedroom VALUES ('Allan','BLUE','PINK','BLACK');
+
INSERT INTO bedrooms VALUES ('Allan','BLUE','PINK','BLACK');
INSERT INTO bedroom VALUES ('George','BLUE','GREEN','OAK');
+
INSERT INTO bedrooms VALUES ('George','BLUE','GREEN','OAK');
 
</source>
 
</source>
 
<div>
 
<div>
  SELECT name FROM bedroom
+
  SELECT name FROM bedrooms
 
  WHERE floorcolor = 'YELLOW'
 
  WHERE floorcolor = 'YELLOW'
 
  OR ceilingcolor = 'YELLOW'
 
  OR ceilingcolor = 'YELLOW'
Line 24: Line 24:
 
COALESCE(floorcolor,'').
 
COALESCE(floorcolor,'').
 
</div>
 
</div>
<source lang='sql' class='def'>SELECT name FROM bedroom
+
<source lang='sql' class='def'>SELECT name FROM bedrooms
 
WHERE CONCAT (':',floorcolor,':',ceilingcolor,':',wallcolor,':')
 
WHERE CONCAT (':',floorcolor,':',ceilingcolor,':',wallcolor,':')
 
LIKE '%:YELLOW:%'</source>
 
LIKE '%:YELLOW:%'</source>

Revision as of 11:33, 30 July 2012

Search for a string across columns

schema:scott
DROP TABLE bedrooms
 CREATE TABLE bedrooms(
  name VARCHAR(20),
  floorcolor VARCHAR(20),
  ceilingcolor VRACHAR(20),
  wallcolor VARCHAR(20));
INSERT INTO bedrooms VALUES ('Jim','RED','GREEN','YELLOW');
INSERT INTO bedrooms VALUES ('Bob','YELLOW','BLUE','BLACK');
INSERT INTO bedrooms VALUES ('Allan','BLUE','PINK','BLACK');
INSERT INTO bedrooms VALUES ('George','BLUE','GREEN','OAK');
SELECT name FROM bedrooms
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 bedrooms
WHERE CONCAT (':',floorcolor,':',ceilingcolor,':',wallcolor,':')
LIKE '%:YELLOW:%'
Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense