Wednesday, 2 September 2015

How to export mysql query results to csv?

How to export mysql query results to csv?

To Learn OR understand the exporting mysql results in CSV.
Lets have below simple example.


  1. Step 1: Create a employee table
    CREATE TABLE IF NOT EXISTS `employee` (
      `id` int(11) unsigned NOT NULL,
      `first_name` varchar(100) DEFAULT NULL,
      `last_name` varchar(100) DEFAULT NULL,
      `gender` enum('m','f') DEFAULT NULL,
      `status` enum('0','1') NOT NULL COMMENT '0-Inactive, 1-Active',
      `address` varchar(255) DEFAULT NULL,
      `created_at` datetime DEFAULT NULL,
      `modified_at` datetime DEFAULT NULL
    ) ENGINE=InnoDB AUTO_INCREMENT=6;

  2. Add The records in employee table
    INSERT INTO `employee` (`id`, `first_name`, `last_name`, `gender`, `status`, `address`, `created_at`, `modified_at`) VALUES
    (1, 'Sunil', 'Malhotra', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (2, 'Anil ', 'Yadav', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (3, 'Aman ', 'Verma', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (4, 'Ram ', 'Singh', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00'),
    (5, 'Arun', 'Kumar', 'm', '1', '3020 new town, chandigarh', '2015-09-02 12:38:00', '2015-09-02 12:38:00');
    

  3. Create a folder where you are going to export the csv file.
  4. Execute the Mysql Query.
    SELECT id,first_name,last_name,gender, STATUS, address FROM employee
    INTO OUTFILE 'E:/wamp/www/export/employee3.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    LINES TERMINATED BY '\n';

Tuesday, 1 September 2015

MySql replace NULL values with empty string without effecting Rowset

MySql replace NULL values with empty string without effecting Rowset

Question: What is NULL Value in MySQL?
NULL values means don't have any value. It is neither empty NOR it have any value.


Question: Give an Example which is give NULL Values in Query?
NULL values means don't have any value. It is neither empty NOR it have any values.
SELECT u.id, u.first_name,u.last_name,b.address1 FROM `users` as u LEFT JOIN billings as b on b.user_id=u.id order by u.id desc limit 5;
See Screenshot below:
Give an Example which is give NULL Values in Query



Question: How we can replace the null value with empty string?
We can use mysql IFNULL function to replace the null values with empty string. See Example:
SELECT IFNULL(null,"") as value 



Question: Give an Example to replace the NULL with empty string in mysql query?
We can use mysql IFNULL function to replace the null values with empty string. See Example:
SELECT u.id, u.first_name,u.last_name,IFNULL(b.address1,"") AS address1 FROM `users` as u LEFT JOIN billings as b on b.user_id=u.id  order by u.id desc limit 5; 

See Screenhot below:
Give an Example to replace the NULL with empty string in mysql query