How to export specific column data in MySQL?

MySQLMySQLi Database

To export specific column data in MySQL, use OUTFILE −

select yourColumnName from yourTableName into outfile 'yourLocationOfFile’;

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20),
   StudentLastName varchar(20)
);
Query OK, 0 rows affected (0.54 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Doe');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('David','Miller');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Smith');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('Carol','Taylor');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('Sam','Williams');
Query OK, 1 row affected (0.18 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1         | John             | Doe             |
| 2         | David            | Miller          |
| 3         | John             | Smith           |
| 4         | Carol            | Taylor          |
| 5         | Sam              | Williams        |
+-----------+------------------+-----------------+
5 rows in set (0.00 sec)

Following is the query to export specific column data in MySQL −

mysql> select StudentLastName from DemoTable into outfile 'E:\StudentLastName.txt';
Query OK, 5 rows affected (0.00 sec)

The file location is ‘E:\StudentLastName.txt’. The screenshot of file and contents are as follows. We have successfully export column data to the file −

raja
Updated on 30-Jul-2019 22:30:25

Advertisements