Tuesday, May 28, 2013

Complex SQL Queries with columns

Advanced MySQL queries with CASE, IF and FIND_IN_SET:



CREATE TABLE `students` (
 `id` INT(11) NOT NULL AUTO_INCREMENT,
 `name` VARCHAR(50) NULL DEFAULT NULL,
 `grade` SET('a','b','c','d','e') NULL DEFAULT NULL,
 PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6;


INSERT INTO `students` (`id`, `name`, `grade`) VALUES (1, 'Mark', 'a,c,d');
INSERT INTO `students` (`id`, `name`, `grade`) VALUES (2, 'John', 'c,d');
INSERT INTO `students` (`id`, `name`, `grade`) VALUES (3, 'Ronald', 'a,b,d');
INSERT INTO `students` (`id`, `name`, `grade`) VALUES (4, 'Morgan', 'c,d');
INSERT INTO `students` (`id`, `name`, `grade`) VALUES (5, 'Ronaldo', 'a,b,c,d');


SELECT  
 CASE WHEN name='John' THEN 'found John' ELSE 'no John' END as John_Column, 
 CASE WHEN name='Morgan' THEN 'found Morgan' ELSE 'no Morgan' END as Morgan_Column, 
 name,
 id
FROM students;

SELECT  
 CASE 
  WHEN name='John' THEN 'found John' 
  WHEN name='Morgan' THEN 'found Morgan'  
  ELSE 'no John and no Morgan' END as MoreNames, 
 name,
 id
FROM students;


SELECT IF(name LIKE 'Ron%','yes','no') as Names_starting_with_Ron, name, id from students;


SELECT * FROM students WHERE FIND_IN_SET('a', grade);

No comments:

Post a Comment