%% Execute SQL Script Using PostgreSQL Native Interface
% Connect to a PostgreSQL database. Then, run two SQL SELECT statements from the SQL script file compare_sales.sql, import the results, and perform simple sales data analysis. The file contains two SQL queries: the first retrieves sales of products from US suppliers, and the second retrieves sales of products from foreign suppliers.
%
% Create a PostgreSQL native interface database connection to a PostgreSQL database using the data source name, user name, and password. The database contains the tables productTable and suppliers.

datasource = "PostgreSQLDataSource";
username = "dbdev";
password = "matlab";
conn = postgresql(datasource,username,password);

%
% Execute the SQL script. The SQL script contains two SQL queries that retrieve sales data from US and foreign suppliers, respectively.

scriptfile = "compare_sales.sql";
results = executeSQLScript(conn,scriptfile)

% The executeSQLScript function returns a structure array that contains two tables in the Data field. The first table contains the results of executing the first SQL query in the SQL script file. The second table contains the results of executing the second SQL query.
%
% Display the first eight rows of imported data for the second SQL query in the SQL script file. The data shows sales results from foreign suppliers.

data = head(results(2).Data)

%
% Retrieve the variable names in the table.

names = data.Properties.VariableNames

%
% Determine the highest sales amount in January.

max(data.jan_sales)

%
% Close the database connection.

close(conn)

% Copyright 2020 The MathWorks, Inc.