The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
May 1998Online OnlyNew for Version 1 for MATLAB®5.2
July 1998First PrintingFor Version 1
Online onlyJune 1999Revised for Version 2 (Release 11)
December 1999Second printingFor Version 2 (Release 11)
Online onlySeptember 2000Revised for Version 2.1 (Release 12)
June 2001Third printingRevised for Version 2.2 (Release 12.1)
July 2002Online onlyRevised for Version 2.2.1 (Release 13)
November 2002Fourth printingVersion 2.2.1
June 2004Fifth printingRevised for Version 3.0 (Release 14)
October 2004Online onlyRevised for Version 3.1 (Release 14SP1)
March 2005Online onlyRevised for Version 3.0.2 (Release 14SP2)
September 2005 Online onlyRevised for Version 3.1 (Release 14SP3)
March 2006Online onlyRevised for Version 3.1.1 (Release 2006a)
September 2006 Online onlyRevised for Version 3.2 (Release 2006b)
October 2006Sixth printingRevised for Version 3.2 (Release 2006b)
March 2007Online onlyRevised for Version 3.3 (Release 2007a)
September 2007 Seventh printingRevised for Version 3.4 (Release 2007b)
March 2008Online onlyRevised for Version 3.4.1 (Release 2008a)
October 2008Online onlyRevised for Version 3.5 (Release 2008b)
March 2009Online onlyRevised for Version 3.5.1 (Release 2009a)
September 2009 Online onlyRevised for Version 3.6 (Release 2009b)
March 2010Online onlyRevised for Version 3.7 (Release 2010a)
Before You Begin
1
Working with Databases...........................1-2
Connecting to Databases
Supported Platforms
Supported Databases
Supported Drivers
Structured Query Language (SQL)
.................................1-3
...........................1-2
...............................1-2
..............................1-2
...................1-3
Contents
Supported Data Types
Data Retrieval Restrictions
Spaces in Table Names or Column Names
Quotation Marks in Table Names or Column Names
Reserved Words in Column Names
.............................1-4
.........................1-6
.............1-6
...................1-6
Working with Data Sources
2
Setting up ODBC Data Sources.....................2-2
Setting up JDBC Data Sources
Accessing Existing JDBC Data Sources
Modifying Existing JDBC Data Sources
......................2-3
..............2-4
..............2-5
.....1-6
Removing JDBC Data Sources
Troubleshooting JDBC Driver Problems
......................2-6
.............2-7
v
Database Toolbox Functions vs. Visual Query
3
When to Use Visual Query Build er..................3-2
Tasks You Can Perform Using Visual Query Builder
Limitations of Visual Query Builder
..................3-2
Builder
.....3-2
When to Use Database Toolbox Functions
............3-3
Using Visual Query Builder
4
Getting Started with Visual Query Builder ...........4-2
What Is Visual Query Builder?
Using Queries to Import Data
Using Queries to Export Data
Working with Preferences
Specifying Preferences
Saving Preferences
Displaying Query Results
How to Display Q uery Results
Displaying Data Relationally
Charting Q u ery Results
Displaying Query Results in an HTML Report
Using the MATLAB
Customize Display of Query Results
.............................4-6
................................4-9
............................ 4-14
®
Report Generator Software to
......................4-2
.......................4-2
.......................4-4
..........................4-6
.......................... 4-10
....................... 4-10
........................ 4-10
.......... 4-16
................ 4-17
viContents
Fine-Tuning Queries Using Advanced Query
Options
Retrieving All Occurrences vs. Unique Occurrences of
Data
Retrieving Data That Meets Specified Criteria
Grouping Statements
Displaying Results in a Specified Order
UsingHavingClausesToRefineGroupByResults
......................................... 4-22
.......................................... 4-22
.......... 4-24
.............................. 4-27
............... 4-31
...... 4-34
Creating Subqueries for Values from Multiple Tables ....4-37
Creating Queries That Include Results from Multiple
Tables
Additional Advanced Query Options
Retrieving BINARY and OTHER Sun Java Data
Types
........................................ 4-42
.................. 4-45
........................................... 4-46
Importing and Exporting BOOLEAN Data
Importing BOOLEAN Data from Databases to the MATLAB
Workspace
Exporting BOOLEAN Data from the MATLAB Workspace
to Databases
Saving Queries in Files
About Generated Files
VQB Q uery Elements in Generated Files
..................................... 4-48
...................................4-51
............................. 4-52
............................. 4-52
........... 4-48
.............. 4-53
Using Database Toolbox Functions
5
Getting Started with Database Toolbox Functions ....5-2
Visual Query Builder GUI: Importing Data ...........A-2
Visual Q uer y Builder GUI: Displaying Results
Visual Query Builder GUI: Advanced Query Options
Visual Query Builder GUI: Exporting Data
Using Database Toolbox Functions
..................A-2
........A-2
...........A-2
..A-2
Index
ix
xContents
Before You Begin
• “Working with Databases” on page 1-2
• “Supported Data Types” on page 1-4
• “Data Retrieval Restrictions” on page 1-6
1
1 Before You B egin
Working with Databases
In this section...
“Connecting to Databases” on page 1-2
“Supported Platforms” on page 1-2
“Supported Databases” on page 1-2
“Supported Drivers” on page 1-3
“Structured Query Language (SQL)” on page 1-3
Connecting to Databases
Before you can use this toolbox to connect to a database, you must set up data
sources. For more information, see “Configuring Your Environment” in the
Database Toolbox™ Getting Started Guide.
Supported Platforms
This toolbox runs on all platforms that the M ATLAB®software supports.
1-2
For more information, s ee Database Toolbox system requirements at
Note This toolbox does not support running MATLAB software sessions with
the
-nojvm startup option enabled on UNIX
trademark of the Open Group in the United States and other countries.)
®
platforms. (UNIX is a registered
Supported Databases
This to olbox supports importing and exporting data from any ODBC- and/or
JDBC-compliant database management system, including:
Working with Databases
• IBM DB2
• IBM®Informix
• Ingres
®
®
®
• Microsoft®Access™
• Microsoft
®
Excel
®
• Microsoft®SQL Server™
• MySQL
• Oracle
®
®
• Postgre SQL (Postgres)
®
• Sybase
SQL Anywhere
• Sybase SQL Server
®
®
Ifyouareupgradinganearlierversion of a database, you need not do
anything special for this toolbox. Simply configure the data sources for the
new version of the database application as you did for the original version.
Supported Drivers
This toolbox requires a database driver. Typically, you install a driver when
you install a database. For instructions about how to install a database
driver, consult your database administrator.
On Microsoft
®
Windows®platforms, the toolbox supports Open Database
Connectivity (ODBC) drivers and Sun™ Java™ Database Connectivity
(JDBC) drivers.
On UNIX platforms, the toolbox supports Java Database Connectivity
(JDBC) drivers. If your database does not ship with JDBC
drivers, download drivers from the Sun JDBC Web Site at
This toolbox supports American N ational Standards Institute (ANSI)
standard SQL commands.
1-3
1 Before You B egin
Supported Data Types
You can import the follow ing data types into the MATLAB workspace and
export them back to your database:
•
BOOLEAN
• CHAR
• DATE
• DECIMAL
• DOUBLE
• FLOAT
• INTEGER
• LONGCHAR
• NUMERIC
• REAL
1-4
• SMALLINT
• TIME
• TIMESTAMP
• TINYINT
Note The D atabase Toolbox software interprets this data type as BOOLEAN
and imports it into the MATLAB workspace as logical true (1) or false
. For more information about how the Database Toolbox software
(0)
handles
on page 4-48.
• VARCHAR
• NTEXT
BOOLEAN data, see “Importing and Exporting BOOLEAN Data”
Supported Data Types
You can import data of types n ot included in this list into the MATLAB
workspace. However, you may need to manipulate such data before you can
process it in MATLAB.
1-5
1 Before You B egin
Data Retrieval Restrictions
In this section...
“SpacesinTableNamesorColumnNames”onpage1-6
“Quotation Marks in Table Names or Column Names” on page 1-6
“Reserved Words in Column Names” on page 1-6
Spaces in Table Names or Column Names
Microsoft Access supports the use of spaces in table and column names, but
most other databases do not. Queries that retrieve data from tables and fields
whose n ames contain spaces require delimiters around table names and field
names. In Access™, enclose the table names or field names in quotation
marks, for example,
such as brackets, [ ]. In Visual Query Builder, table names and field names
that include spaces appear in quotation marks.
"order id". Other databases use different delimiters,
1-6
Quotation Marks in Table Names or Column Names
Do not include quotation marks in table names or column names. The
Database Toolbox softw are does not support data retrieval from table and
column names that contain quotation marks.
ReservedWordsinColumnNames
You cannot use the Database Toolbox software to import or export data in
columns whose names contain database reserved words, such as
TABLE.
DATE or
2
Working with Data Sources
• “Setting up ODBC Data Sources” on page 2-2
• “Setting up JDBC Data Sources” on page 2-3
• “Accessing Existing JDBC Data Sources” on page 2-4
• “Modifying Existing JDBC Data Sources” on page 2-5
• “Removing JDBC Data So urce s” on page 2-6
• “Troubleshooting JDBC Driver Problems” on page 2-7
2 Working with Data Sources
Setting up ODBC Data Sources
For instructions on setting up OD BC data sources, see “Setting Up Data
Sources for Use with ODBC D rivers” in the Database ToolboxGetting StartedGuide.
2-2
Setting up JDBC Data Sources
For instructions on setting up JDBC data sources, see “Setting Up Data
Sources for Use w ith JDBC Drivers” in the Database ToolboxGetting StartedGuide.
Setting up JDBC Data Sources
2-3
2 Working with Data Sources
Accessing Existing JDBC Data Sources
To access an existing data source from Visual Query Builder in future
MATLAB software sessions:
1 In Visual Query Builder, select Query > Define JDBC data source.
2 In the Define JDBC data sources dialog box, click Use Existing File.
3 In the Specif
MAT-file tha
The data sources in the selected MAT-file appear in the Define JDBC data
sources dialog box.
4 Click OK to close the Define JDBC data sources dialog box. The data
sources now appear in the Visual Query Builder Data source list.
y Existing JDBC data source MA T-file dialog box, select the
t contains the data sources you want to use and click Open.
2-4
Modifying Existing JDBC Data Sources
1 Access the existing data source as described in “Accessing Existing JDBC
Data Sources” on page 2-4.
2 Select the data source in the Define JDBC Data Sources dialog box .
3 Modify the data in the Driver and URL fields.
4 Click Add/Update.
5 Click OK to save your changes and close the Define JDBC data sources
dialog box.
ModifyingExistingJDBCDataSources
2-5
2 Working with Data Sources
Removing JDBC Data Sources
1 Access the existing data source as described in “Accessing Existing JDBC
Data Sources” on page 2-4.
2 Click Remove.
3 Click OK to sav
dialog box.
eyourchangesandclosetheDefineJDBCdatasources
2-6
Troubleshooting JDBC Driver Problems
This section describes how to address comm on data source access problems,
in which selecting a data source in the Visual Query Builder list produces
an error, or the data source is not in the list as expected. There are several
potential causes for these issues:
• The database is unavailable, or there are con n ectiv ity problems. Try
reselecting the data source in VQB. If you are still unable to access the
data source, contact your database administrator.
Troubleshooting JDBC Driver Problems
• You ran the
you defined a JDBC data source. In this case, redefine the data source by
following the instructions in “Setting Up Data Sources for Use with JDBC
Drivers” in the Database Toolbox Getting Started Guide.
clear all command in the MATLAB Command Window after
To start the Visual Query Builder, type querybuilder at the MATLAB prompt.
*Required step
Getting Started with Visual Query Builder
12 View query results in table,
chart, and report formats.
8 Set preferences
for data retrieval.
13 Save, load,
and run queries,
and generate
M-files.
6 Refine query.
7 View SQL
statement.
9* Assign variable
for results.
1* Specify Select.2* Select data
source.
3 Select
catalog
and schema.
4* Select
tables.
5* Select
fields to
retrieve.
11 Double-click to view query results
in MATLAB Array Editor.
10* Run query.
For a step-by-step example of how to use queries to import data into the
MATLAB workspace from a database, see “Using Queries to Import Database
4-3
4 Using Visual Query Builder
Data into the MATLAB Workspace” in the Database Toolbox Getting Started
Guide.
Using Queries to Export Data
The following steps summarize how to use VQB to export data.
4-4
To start the Visual Query Builder, type querybuilder at the MATLAB prompt.
*Required step
Getting Started with Visual Query Builder
9 Save, load, and
run queries, set
preferences for
exporting NULLs,
and generate
M-files.
7 View MATLAB
statement.
6* Specify variable
containing data
to export.
1* Specify Insert.2* Select data
source.
3 Select
catalog
and schema.
4* Select
tables.
5* Select fields
to which to
export data.
8* Run query.
For a step-by-step example of how to use queries to export data from the
MATLAB workspace to a database, see “Using Queries to Export MATLAB
WorkspaceDatatoaDatabase”intheDatabase Toolbox Getting StartedGuide.
4-5
4 Using Visual Query Builder
Working with Preferences
In this section...
“Specifying Preferences” on page 4-6
“Saving Preferences” on page 4-9
Specifying Preferences
This section describes how to set VQB preferences to specify:
• How
• The format of data retrieved from databases
• The method of error notification
1 Click Query > Preferences. The Preferences dialog box appears.
NULL data in a database is represented after you import it into the
MATLAB workspace
4-6
Working with Preferences
4-7
4 Using Visual Query Builder
2 Specify the Preferences settings as described in the following table.
Preference ValueDescription
Read
NULL
numbers
as
Data
return
format
Error
handling
0
numeric
report
If you accept the default value for this field, NULL data imported
from databases into the M ATLAB workspace appears as
Setting this field to 0 causes
MATLABworkspacetoappearas
Select a data format based on the type of data you are importing,
memory considerations, and your preferred method of working
with retrieved data.
Cell arrays and structures support mixed data types, but require
more memory and process more slowly than numeric matrices.
Select
• The data you are retrieving is numeric, or
• You need to convert nonnumeric data to the format specified
• Set this field to store or empty to direct errors to a dialog box
NaN.
NULL data imported into the
0s.
numeric if:
in the Read NULL numbers as field.
rather than to the MATLAB Command Window.
4-8
• Set this field to
Command Window.
report to display query errors in the MATLAB
3 Click OK.
4 Assign the query results to a workspace variable, A.
5 Click Execute to rerun the query.
Information about the retrieved data appears in the Data area.
6 To see the results, enter A in the Command Window.
Preferences apply only to the current MATLAB software session. They are not
saved with queries. Default Preferences apply when you start a new session,
orafteryouclearallvariables(using,forexample,the
It is a good practice to check Preferences settings before you run queries.
clear all command).
4-9
4 Using Visual Query Builder
Displaying Query Results
In this section...
“How to Display Query Results” on page 4-10
“Displaying Data Relationally” on page 4-10
“Charting Query Results” on page 4-14
“Displaying Query Results in an HTML Report” on page 4-16
“Using the MATLAB®Report Generator SoftwaretoCustomizeDisplayof
Query Results” on page 4-17
How to Display Query Results
To display query results, perform one of the following actions:
• Enter the variable name to which to assign the query results in the
MATLAB Command W indow.
4-10
• Double-click the variable in the VQB Data area to view the data in the
Variable Editor.
The examples in this section use the saved query
configure this query:
1 Click Quer y > Preferences,andsetRead NULL numbers as to 0.
2 Click Query > Load.
3 In th
4 In VQB, enter a value for the M ATLAB workspace variable,for
e Load SQL Statement dialog box, select
name
example,
field and click Open.
A,andclickExecute.
basic.qry.Toloadand
basic.qry from th e File
Displaying Data Relationally
To display the results of basic.qry:
1 Execute basic.qry.
2 Click Display > Data.
The query results appearinafigurewindow.
Displaying Query Results
This display shows only unique values for each field, so you should not
read each row as a single record. In this examp le , there are 10 entries for
StockNumber, 8 entries for January and February, and 10 entries for
March. The number of entries in each field corresponds to the number of
unique values in the field.
ck a value in the figure window, for example, StockNumber
3 Cli
ee its ass ociated values.
to s
400876,
4-11
4 Using Visual Query Builder
The data associated with the selected value appears in bold font and is
connected with a dotted line. The data shows that sales for item 400876 are
3000 in January, 2400 in February, and 1500 in March.
4-12
4 As another example, click 3000 under January. It shows three different
items with sales of 3000 units in January: 400314, 400876, and 400999.
Displaying Query Results
4-13
4 Using Visual Query Builder
Charting Query R
To chart the resu
1 Click Display >
The Visual Query Builder Charting dialog box appears.
lts of
esults
basic.qry:
Chart.
4-14
2 Select a type of chart from the Charts list. In this example, choose a pie
chart by specifying
A preview of the pie chart, with each stock item displayed in a different
color, appears at the bottom of the dialog box.
The pie chart preview now shows percentages for March data.
4 To display a legend, which maps colors to the stock numbers, select the
Show legend check box.
The Legend labels field becomes active.
5 Select StockNumber from the Legend labels list box.
A legend appears in the chart prev iew. D rag and move the legend in the
preview as needed.
4-15
4 Using Visual Query Builder
Displaying Query Results in an HTML Report
To display results for basic.qry in an HTML report, click Display > Report.
The query results appear as a table in a Web browser. Each row represents a
record from the database. In this example, sales for item 400876 are 3000 in
January, 2400 in February, and 1500 in March.
6 Click Close to close the Charting dialog box.
4-16
Displaying Query Results
Note Because some browsers do not start automatically, you may need to
open your Web browser before displaying the query results.
Using the MATLAB Report Generator Software to
Customize Display of Query Results
To use the MATLAB®Report G enerator™ software to customize the display
of the results of
1 Click Display > Report Generator.
2 The Report Explorer opens, listing sample report templates
that you can use to create custom reports. Select the template
matlabroot/toolbox/database/vqb/databasetlbx.rpt from the Options
paneinthemiddleoftheReportExplorerwindow.
basic.qry:
4-17
4 Using Visual Query Builder
4-18
3 Open the report template for editing by clicking Open a Report file or
stylesheet.
a In the Outline pane on the left, under Report Generator >
databasetlbx.rpt,select
b In the Properties pane on the right, do the following:
Table.
Displaying Query Results
i In Table Content > Workspace Variable Name,enterthename
ofthevariabletowhichyouassignedthequeryresultsinVQB,for
example,
'A'.
ii Under Header/Footer Options,setNumber of header rows to
c Click Apply.
4 Click File > Report to run the report.
The report appears in a Web browser.
0.
ld names do not automatically display as column headers in the report.
5 Fie
display the field names:
To
4-19
4 Using Visual Query Builder
a Modify the workspace variable A as follows:
A = [{'Stock Number', 'January', 'February', 'March'};A]
b In the MATLAB Report Generator properties pane, change Number of
header rows to
field names as headings.
Each row represents a record from the database. For example, sales for
item 400876 are 3000 in January, 2400 in February, and 1500 in March.
1 and regenerate the report. The report now displays
4-20
Displaying Query Results
For more information about the MATLAB Report Generator product, click the
Help button in the R eport Explorer or see the MATLAB Report Generator
documentation.
Note Because some browsers are not configured to launch automatically, you
may need to open your Web browser before displaying the report.
4-21
4 Using Visual Query Builder
Fine-Tuning Queries Using Advanced Quer y Options
In this section...
“Retrieving All Occurrences vs. Unique Occurrences of Data” on page 4-22
“Retrieving Data That Meets Specified Criteria” on page 4-24
“Grouping Statements” on page 4-27
“Displaying Results in a Specified Order” on page 4-31
“Using Having Clauses To Refine Group By Results” on page 4-34
“Creating Subqueries for Values f r om Multiple Tables” on page 4-37
“Creating Queries That Include Results from Multiple Tables” on page 4-42
“Additional Advanced Query Options” on page 4-45
Note For more information about advanced query options, select Help in
any of the dialog boxes for the options.
4-22
Retrieving All Occurrences vs. Unique Occurrences
of Data
To use the dbtoolboxdemo data source to demonstrate how to retrieve all
versus distinct occurrences of data:
1 Set the Data return format preference to cellarray.
2 Set Read NULL numbers as to NaN.
3 In D
4 In Data source,selectdbtoolboxdemo.
5 I
6 In Fields,selectJanuary.
ata operation, choos e Select.
Do not specify Catalog or Schema.
n Tables,select
SalesVolume.
Fine-Tuning Queries Using Advanced Query Options
7 To retrieve all occurrences of January:
a In Advanced query options, select All.
b Assign the query results to the MATLAB workspace variable Al l.
c Click Execute to run the query.
8 To retrieve only unique occurrences of data:
a In Advanced query options,selectDistinct.
b Assign the query re sults to a MATLAB workspace variable Dist inct.
c Click Execute to run the query.
9 In the MATLAB Command Window, enter A ll, Distinct to display the
query results:
4-23
4 Using Visual Query Builder
Retrieving Data That Meets Specified Criteria
Use basic.qry and the Where field in Advanced query options to retrieve
stock numbers greater than 400000 and less than 500000:
The value 3000 appearsthreetimesinAll, but appears only once in
Distinct.
1 Load basic.qry.
2 Set the Data return format preference to cellarray.
3 Set Read NULL numbers as to NaN.
4 In Advanced query options,clickWhere.
The WHERE Clauses dialog box appears.
4-24
5 In Fields, select the field whose values you want to restrict, StockNumber.
6 In Condition,specifythatStockNumber must be greater than 400000.
a Select Relation.
b In the drop-down list to the right of Relation,select>.
c In the field to the right of the drop-down list, enter 4 00000.
The WHERE Clauses dialog box now looks as follows.
d Click Apply.
Fine-Tuning Queries Using Advanced Query Options
Theclausethatyoudefined,
Current clauses area.
StockNumber > 400000,appearsinthe
4-25
4 Using Visual Query Builder
7 Add the condition that StockNumber must also be less than 500000.
a In Current clauses, select StockNumber > 400000.
b In Current clauses,clickEdit or double-click the StockNumber entry.
c For Operator, select AND.
d Click Apply.
The Current clauses field n ow displays:
StockNumber > 400000 AN D
e In Fields, select StockNumber.
f In Condition, select Relation.
g In the drop-down list to the right of Relation,select<.
h In the field to the right of the drop-down list, enter 500000.
i Click Apply.
4-26
The Current clauses field n ow displays:
StockNumber > 400000 AN D
StockNumber < 500000
8 Click OK.
The WHERE Clauses dialog box closes. The Where field and SQL
statement display the Where Clause you specified.
9 Assign the query results to the MATLAB workspace variable A.
10 Click Execute.
Fine-Tuning Queries Using Advanced Query Options
11 To view the results, enter A in the Command Window:
12 Save this query as basic_where.qry.
Grouping Statements
Use the WHERE Clauses dialog box to group query statements. In this
example, modify
February, or March exceed
units.
basic_where.qry to retrieve data where sales in January,
1500 units, if sales in each month exceed 1000
To modify
1 Click Where in VQB. The WHERE Clauses dialog box appears.
2 Modify the query to retrieve data if sales in January, February, or March
basic_where.qry:
exceed 1500 units.
4-27
4 Using Visual Query Builder
a In Current clauses, select StockNumber < 500000 and click Edit.
b For Operator,selectOR and click Apply.
c In Fields, select January.ForRelation, select > and enter 1500 in its
field. For Operator, select
d Repeat step c twice, specifying February and March in Fields.
OR.ClickApply.
The WHERE Clauses dialog box now looks as follows.
4-28
3 Group the criteria that require sales in each month to exceed 1500 units.
a In Current clauses, select the statement January > 1500 OR.Click
Shift+click to select
b Click Group.
An opening parenthesis is added before
parenthesis is added after
February > 1500 OR and March > 1500 also.
January and a closing
March > 1500, indicating that these
statements are evaluated as a group.
Fine-Tuning Queries Using Advanced Query Options
4 Modify the query to retrieve data if sales in each month exceed 1000 units.
a Select March > 1500 ) in Current clauses and click Edit.
b Select AND for Operator and click Apply.
c Select January in Fields. Select > for Relation and enter 1 000 in its
field. Select
AND for Operator.ClickApply.
d Repeat step c twice, specifying February and March in Fields.
The WHERE Clauses dialog box now looks as follows.
4-29
4 Using Visual Query Builder
e Click OK.
4-30
The WHERE Clauses dialog box closes. The SQL statement dialog box
displays the modified w here clause.
5 Assign t
6 Click Execute to run the query.
he query results to the MATLAB workspace variable
AA.
Fine-Tuning Queries Using Advanced Query Options
7 To view the results, enter AA in the MATLAB Command Window.
Removing Gr
ouping of Statements
To use the WHERE Clauses dialog box to remove grouping criteria from the
previous example:
1 In Current clauses, select (January > 1000 AND.
2 Click Shi
3 Click Ungroup.
ft+click to select
February > 1000 AND an d March > 1000) also.
The parentheses are removed from the statements, indicating that their
grouping is removed.
Displaying Results in a Specified Order
Use Order by in Advanced query options to specify the order in which
query results display.
This example uses the
Data That Meets Specified Criteria” on page 4-24. The results of
basic_where.qry are sorted so that January is the primary sort field,
February the secondary, and March the last. Results for January and
February appear in ascending order, and results for March appear in
descending order.
basic_where.qry query you created in “Retrieving
To specify the order in which results appear in
basic_where.qry:
4-31
4 Using Visual Query Builder
1 Load basic_where.qry.
2 Set the Data return format preference to cellarray.
3 Set Read NULL numbers to NaN.
4 In Advanced query options, select Order by.
The Order By Clauses dialog box appears.
4-32
5 Enter values for the Sort key number and Sort order fields for the
appropriate Fields.
To specify
January as the primary sort field and display results in
ascending order:
a In Fields, select January.
b For Sort key number,enter1.
c For Sort order,selectAscending.
d Click Apply.
The Current clauses area now displays:
January ASC
Fine-Tuning Queries Using Advanced Query Options
6 To specify Februa ry as the second sort field and display results in
ascending order:
a In Fields,selectFebruary.
b For Sort key number,enter2.
c For Sort order,selectAscending.
d Click Apply.
The Current clauses area now displays:
January ASC
February ASC
7 To specify March as the third sort field and display res ults in descending
order:
a In Fields,selectMarch.
b For Sort key number,enter3.
c For Sort order,selectDescending.
d Click Apply.
The Current clauses area now displays:
January ASC
February ASC
March DESC
8 Click OK.
The Order By Clauses dialog box closes. The Order by field and the SQL
statement in VQB display the specified Order By clause.
9 Assign the query results to the MATLAB workspace variable B.
10 Click Execute to run the query.
4-33
4 Using Visual Query Builder
11 To view the results, enter B in the MATLAB C ommand Window. Enter A to
display the unordered query results and compare them to
look as follows:
B. Your results
4-34
For B, results are first sorted by January sales, in ascending order. The
lowest value for
first. The highest value, 5000 (for item number for 400345), appears last.
For items 400999, 400314, and 400876,
Therefore, the second sort key,
appear in ascending order: 1500, 2400, and 2400 respectively.
For items 400314 and 400876,
sort key,
1800 and 1500, respectively.
March sales, applies. March sales appear in descending order:
January sales, 1200 (for item number 400455), appears
January sales were 3000.
February sales, applies. February sales
February sales were 2400, so the third
Using Having Clauses To Refine Group By Results
UsingtheHAVINGClausesDialogBox
Use the Having function to refine the results of a Group By clause.
Fine-Tuning Queries Using Advanced Query Options
After specifying a group-by clause in Advanced query options,click
Having. The HAVING Clauses dialog box appears.
1 From the Fields list box, select the entry whose value to restrict.
2 Define the Condition for the selected field, as described in “Retrieving
Data That Meets Specified Criteria” on page 4-24.
3 Select Operator to add another condition.
4 Click Apply to create the clause.
The subquery appears in the Current clauses area.
5 Repeat steps 1 through 4 to add more conditions as needed.
6 Change the clauses as needed:
• To edit a clause:
a Select the clause from Current clauses and click Edit.
b Modify the Fields, Condition,andOperator fields as needed.
c Click Apply.
• To group clauses:
4-35
4 Using Visual Query Builder
Example: Using Having Clauses
This example restricts the results from basic_where.qry to sales greater
than 2000 for January and February:
d Select the clauses to group from Current clauses.UseCtrl+click or
Shift+click to select multiple clauses.
e Click Group. Parentheses are added around the set of clauses.
To ungroup clauses, select the clauses and then click Ungroup.
• To delete a clause, Select the clause from Current clauses and click
Delete.UseCtrl+click or Shift+click to select multiple clauses.
7 Specify a subquery in the HAVING Clauses dialog box, as needed. For
more information, see “Creating Subqueries for Values from Multiple
Tables” on page 4-37.
8 Click OK.
The Having Clauses dialog box closes. The SQL statement in the Visual
Query Builder dialog box updates to reflect the specified having clause.
4-36
1 In Advanced query options,clickHaving. The HAVING Clauses dialog
box appears.
2 For January:
a Select > as the Relation Condition.
b Enter 2000 as the Relation value.
c Select the AND Operator.
d Click Apply.
3 For February:
a Select > as the Relation Condition.
b Enter2000 as the Relation value.
c Click Apply. The HAVING Clauses dialog box appears as follows.
Fine-Tuning Queries Using Advanced Query Options
4 Click OK.
The Having Clauses dialog box closes. The SQL statement field in the
VQB dialog box reflects the specified Having clause.
5 Assign a MATLAB workspace variable C,andclickExecute to run
the query.
Compare these results to those in “Displaying Results in a Specified Order”
on page 4-31.
Creating Subqueries for Values from Multiple Tables
Use the Where feature in Advanced query options to create subqueries.
Creating subqueries in this way is referred to as nested SQL.
This example uses
Database Toolbox Getting Started Guide.
The
salesVolume table has sales volumes and stock number fields, but no
product description field. The
basic.qry, which you created in “Saving Queries ” in the
productTable has product description and
4-37
4 Using Visual Query Builder
stock number fields, but no sales volumes. This example retrieves the stock
number for the product whose description is
productTable table. It then gets the sales volume values for tha t stock
number from the
Building Blocks from the
salesVolume table.
1 Load basic.qry.
2 Set the Data return format Preference to cellarray and Read NULL
numbers as to
3 Click Where in Advanced query options.
NaN.
The WHERE Clauses dialog box appears.
4 Click Subquery.
The Subquery dialog box appears.
4-38
Fine-Tuning Queries Using Advanced Query Options
5 In Tables, select productTable, which includes the association between
the stock number and the p roduct description. The fields in that table
appear.
6 In Fields, select stockNumber, the field that is common to this table and
the table from which you are retrieving results.
The statement
SELECT stockNumber FROM p roductTable is created in the
SQL subquery statement.
7 Limit the query to product descriptions that are Building Blocks.
a In Fields in Subquery WHERE clauses, select productDescription.
b For Condition, select Relation.
c In the drop-down list to the right of Relation,select=.
d In the field to the right of the drop-down list, enter 'Building Blocks'.
e Click Apply.
TheclauseappearsintheCurrent subquery WHERE clauses field
and is add ed to the SQL subquery statement.
4-39
4 Using Visual Query Builder
4-40
8 Click OK to close the Subquery dialog box.
9 In the WHERE Clauses dialog box, click A pply.
This up
specif
dates the Current clauses area using the subquery criteria
ied in steps 3 through 8.
Fine-Tuning Queries Using Advanced Query Options
10 In the WHERE Clauses dialog box, click OK.
The WHERE Clauses dialog box closes. The SQL statement in the VQB
dialog box updates.
11 Assign the query results to the MATLAB workspace variable C.
12 Click Execute.
13 Type C at the prompt in the MATLAB Command Window to see the results.
14 The results are for item 400345, which has the product description
Building Blocks, although that is not evident from the results. Create
and run a query to verify that the product description is
a For Data source,selectdbtoolboxdemo.
b In Tables, select productTable.
c In Fields, select stockNumber and productDescription.
d Assign the query results to the MATLAB workspace variable P.
e Click Execute.
Building Blocks:
4-41
4 Using Visual Query Builder
f Type P at the prompt in the MATLAB Command Window to view the
results.
The results show that item 400345 has the product description Building
Blocks.
description
In the next section, you create a query that includes product
in the results.
4-42
Note YoucanincludeonlyonesubqueryinaqueryusingVQB;youcan
include multiple subqueries using Database Toolbox functions.
Creating Queries That Include Results from Multiple
Tables
A query whose results include values from multiple tables is said to perform a
join operation in SQL.
This example retrieves sales volumes by product description. It is like the
one in “Creating Subqueries for Values from Multiple Tables” on page 4-37,
but this example creates a query that returns
than
stock number.
The
salesVolume table has sales volume and stock number fields, but
no
product description field. The productTable table has pro duct
description
a query that retrieves data from both tables and equates the stock number
from
productTable with the stock number from salesVolume :
and stock number fields, but no sales volume field. To create
product description rather
Fine-Tuning Queries Using Advanced Query Options
1 Set the Data return format preference to cellarray and the Read
NULL numbers as preference to
2 For Data operation,chooseSelect.
3 For Data source, select dbtoolboxdemo.
NaN.
The Catalog, Schema,andTables for
dbtoolboxdemo appear.
Do not specify Catalog or Schema.
4 In Tables, select the tables from which you want to retrieve data. For this
example, click Ctrl+click and sele ct both
productTable and salesVolume.
The fields (columns) in those tables appear in Fields. Field
names appear in the format
productTable.stockNumber indicates the stock number in the product
table and
salesVolume.StockNumber indicates the stock number in the
fieldName.tableName. Therefore,
sales volume table.
5 In Fields,clickCtrl+click to select the following fields:
productTable.productDescription
•
• salesVolume.January
• salesVolume.February
• salesVolume.March
6 In this example, the Where clause equates the productTable.stockNumber
with the salesVolume.StockNumber, so that product description is
associated with sales volumes in the query results.
In Advanced query options,clickWhere to associate fields from
different tables. The WHERE Clauses dialog box appears.
7 In the WHERE clauses dialog box:
a In Fields, select productTable.stockNumber.
b For Condition, select Relation.
c In the drop-down list to the right of Relation,select=.
4-43
4 Using Visual Query Builder
d In the field to the right of the drop-down list, enter
salesVolume.StockNumber.
e Click Apply.
The clause appears in the Current clauses field.
4-44
f Click OK to close the W H ERE Clauses dialog box. The Where field and
SQL statement in VQB display the Where clause.
8 Assign the query results to the MATLAB workspace variable P1.
tion on advanced query options, choose an option and click
g box. For example, click Group by in Advanced query
en click Help in the Group by Clauses dialog box.
nced Query Options
4-45
4 Using Visual Query Builder
Retrieving BINARY and OTHER Sun Java Data Types
This example shows how to retrieve data of types BINARY and OTHER,which
may require manipulation before it can undergo MATLAB processing. To
retrieve images using the
image data,
1 For Data Operation, select Select.
2 In Data source,selectSampleDB.
3 In Tables,s
4 In Fields, select EmployeeID and Photo (which contains bitmap images).
5 Select Query > Preferences.
matlabroot/toolbox/database/vqb/parsebinary.m:
elect
SampleDB data source and a sample file that parses
Employees.
6 In the Data
7 As the MATLAB workspace variable,specifyA.
8 Click Execute to run the query.
return format field, specify
cellarray.
4-46
Retrieving BINARY and OTHER Sun™ Jav a™ Data Types
9 Type A in the MATLAB Command Window to view the query results.
6 Assign results to the MATLAB workspace variable P.
7 Click Execute to run the query.
VQB inserts two new rows into the
Products table.
View the table in Microsoft Access to verify that the data was correctly
inserted.
4-51
4 Using Visual Query Builder
Saving Queries in Files
In this section...
“About Generated Files” on page 4-52
“VQB Query Elements in G enerated Files” on page 4-53
About Generated Files
Select Query > Generate M-File to cre ate a file that contains the equivalent
Database Toolbox functions required to run an existing query that was
created in VQB. Edit the file to include MATLAB or related toolbox fu nctions,
as needed. To run the que ry, execute the file.
The following is an example ofafilegeneratedbyVQB.
% Set preferences with setdbprefs.
s.DataReturnFormat = 'cellarray';
s.ErrorHandling = 'store';
s.NullNumberRead = 'NaN';
s.NullNumberWrite = 'NaN';
s.NullStringRead = 'null';
s.NullStringWrite = 'null';
s.JDBCDataSourceFile = '';
s.UseRegistryForSources = 'yes';
s.TempDirForRegistryOutput = '';
setdbprefs(s)
4-52
% Make connection to database. Note that the password has been omitted.
% Using ODBC driver.
conn = database('dbtoolboxdemo','','password');
% Read data from database.
e = exec(conn,'SELECT A LL StockNumber,January,February FROM salesVolume');
e = fetch(e);
close(e)
% Close database connec tion.
close(conn)
Saving Queries in Files
VQB Query Elemen
The following VQ
• Generated code
you assigned qu
results to
you can add a st
as follows:
myVar = e.Data
• For securit
to connect t
string
'pas
that requi
in the data
B query elements do not appear in generated files.
files do not include MATLAB workspace variables to which
eryresultsintheVQBquery. Thefileassignsthequery
ccess these results using the variable
e;a
atement to the file that assigns a variable name to
y reasons, generated files do not include passwords required
o databases. Instead, the
sword'
as a placeholder. To run files to connect to databases
re passwords, substitute your password for the string
base
statement.
ts in Generated Files
e.Data. For example,
e.Data
database statement includes the
password
4-53
4 Using Visual Query Builder
4-54
UsingDatabaseToolbox
Functions
• “Getting Started with Database Toolbox Functions” on page 5-2
• “Importing Data from Databases into the MATLAB Workspace” on page 5-3
• “Viewing Information About Imported Data” on page 5-5
• “Exporting Data from the MATLAB Workspace to a New Record in a
Database” on page 5-7
5
• “Replacing Existing Data in Databases with Data Exported from the
MATLAB Workspace” on page 5-11
• “Exporting Multiple Records from the MATLAB Workspace” on page 5-13
• “Retrieving BINARY or OTHER Sun Java SQL Data Types” on page 5-17
• “Working with Database Metadata” on page 5-19
• “Using Driver Functions” on page 5-25
• “About Objects and Methods in the Database Toolbox Software” on page
5-27
5 Using Database Toolbox™ Functions
Getting Star ted with Database Toolbox Functions
The following sections provide examples of how to use Database Toolbox
functions. M-files that include functions used in some of these examples are
available in
Follow these simple examples consecutively wh en you first start using the
product. Once you are familiar with Database Toolbox usage, refer to these
examples as needed.
matlab/toolbox/database/dbdemos.
5-2
Importing Data from Databases into the MATLAB®Works p ace
Importing Data from Databases into the MATLAB
Workspace
This example demonstrates a sample workflow on a sample database called
SampleDB.
1 Before you connect to a database, set the maximum time that you want to
allow the MATLAB software session to try to connect to a database to 5
seconds.
logintimeout(5)
Note If you are connecting to a database using a JDBC connection, you
must use different function synta x in this step. For more information, see
the
logintimeout function reference page.
2 Use the database function to define a MATLAB variable, conn,to
represent the returned connection object. Pass the following arguments
to this function:
Note If you are connecting to a database using a JDBC connection, you
need to specify different syntax for the
information, see the
3 Use ping to check that the database connection status is successful.
4 Use the exec function to open a cursor and execute an SQL statement.
Pass the following arguments to
database reference page.
exec:
database function. For more
5-3
5 Using Database Toolbox™ Functions
• conn, the name of the connection object
select country from cus tomers, a SQL statement that selects the
•
country column of data from the customers table
curs = exec(conn, 'select country fr om customers')
The exec function returns the MATLAB variable curs.
5 The returned data contains strings, so you must convert it to a format that
supports strings. Use
setdbprefs('DataReturnFormat','cellarray')
6 To stop working now and resume working on the next example at a later
time, close the cursor and the connection as follows:
close(curs)
close(conn)
setdbprefs to specify the format cellarray:
5-4
Viewing Information About Imported Data
Viewing Information About Imported Data
This example shows how to view information about imported data and close
theconnectiontothedatabaseusingthefollowing Database Toolbox functions:
•
attr
• close
• cols
• columnnames
• rows
• width
For more information on these functions, see
matlab\toolbox\database\dbdemos\dbinfodemo.m.
1 Open the cursor and connection if needed:
conn = database('SampleDB', '', '');
curs = exec(conn, 'select country fro m customers');
setdbprefs('DataReturnFormat','cellarray');
curs = fetch(curs, 10);
2 Use rows to return the number of rows in the data set:
numrows = rows(curs)
numrows =
10
3 Use cols to return the number of columns in the data set:
numcols = cols(curs)
numcols =
1
4 Use columnnames to return the names of the columns in the data set:
colnames = columnnames(curs)
colnames =
5-5
5 Using Database Toolbox™ Functions
'country'
5 Use width to return the column width, or size of the field, for the specified
column number:
colsize = width(curs, 1)
colsize =
6 Use attr to view multiple attributes for a column: