COPY FROM with HEADER
Overview
When it comes to a table, we deal with its components like rows, columns, and headers. In Oxla, we provide 3 possible options for the header as follows:
- HEADER OFF
This option will not skip the header of the CSV file. Below are the available syntaxes besides HEADER OFF:
- HEADER ON
This option will skip the header of the CSV file and only follow the columns that have been specified before. Below are the available syntaxes besides HEADER ON:
- HEADER MATCH
This option will read the header and verify that the name matches the column names.
Syntax
The syntax for COPY FROM with HEADER is as follows:
Two parameters need to be specified in the syntax:
-
table_name
: the table that will receive data from the file. -
file_path
: a link to the file location in the server. -
Header_Syntax
: the specified header options.
Examples
Say you have created a CSV file called idvals.csv, and the file has been uploaded to the server:
id,quantity 1,5 2,2 3,1 4,8 5,4 6,3
Then, you create a table by specifying the column with an integer data type:
Now, let’s see an example case by case:
Case #1: HEADER OFF
- With reference to the table above, run the following query:
- An error output will appear.
This happens because we specified the table with an INTEGER column. While in the CSV file, we have STRING value which is “id” and “quantity”, which are not considered headers.
Another Option
- If you don’t want to include the headers (“id” and “quantity”), you can modify your CSV file by deleting the headers:
1,5 2,2 3,1 4,8 5,4 6,3
- Run the COPY FROM statement:
- You will get the following output which indicates that the file has successfully imported to the table:
- Display the table by using the SELECT statement to retrieve the table records:
Case #2: HEADER ON
- With reference to the idqty table above, run the following query:
- You will get the following output which indicates that the file has successfully imported to the table:
- To verify, use the SELECT statement to retrieve the table records:
We will get the below result, which displays the idqty table:
Case #3: HEADER MATCH
- Based on the idqty table above, if we run the following query:
- It will produce a successful output because the specified columns in the idqty table are matched with the header of the idvals.csv file:
- But, you will get a mismatched output when the header isn’t matched. Say that the idvals.csv file has “id” and “qty” header, as shown below:
id,qty 1,5 2,2 3,1 4,8 5,4 6,3
Then, you will get a mismatched output because it reads “qty” from the CSV file when the expected value is “quantity” as specified in the table.
Another Option
- Furthermore, you can also define the columns that you want to match as shown below:
The following output shows a successful result:
- But, if you change the ordering by switching the order of the columns:
- You will get a mismatch error message.