DATABASELINK 教程

Selecting Data with Raw SQL

The raw SQL command SELECT selects and returns data from a database. An alternative is to use the Mathematica command SQLSelect, described in "Selecting Data".

If you find that the examples in this tutorial do not work as shown, you may need to install or restore the example database with the package, as described in "Using the Example Databases".

This loads DatabaseLink and connects to the publisher database.

In[1]:=
Click for copyable input

This retrieves data within the table, ROYSCHED, for which the data in the ROYALTY column is between 0.11 and 0.12.

In[3]:=
Click for copyable input
Out[3]=

This carries out the same SELECT statement, but uses a prepared statement. The arguments to the statement are given as the third element of the SQLExecute command. The first argument is placed in the location of the and the second in the location of the .

In[4]:=
Click for copyable input
Out[4]=

Column and table names must be wrapped in SQLColumn and SQLTable, respectively. This will ensure they are not quoted as strings. The following selects elements of the ROYALTY column in the ROYSCHED table for which the TITLE_ID column value is .

In[5]:=
Click for copyable input
Out[5]=

If you want to give a sequence of arguments to a prepared statement, you can use SQLArgument. This is described in "SQL Execute: Argument Sequences in SQL-Style Queries".

In[6]:=
Click for copyable input
Out[6]=

Many databases offer functions that apply to the results of a SELECT operation. Typical examples are COUNT, MIN, MAX, SUM, and AVG. The documentation for your database will describe the details of the functions that are available. The following examples demonstrate some of these functions.

In[7]:=
Click for copyable input
Out[7]=
In[8]:=
Click for copyable input
Out[8]=

Many databases allow you to apply mathematical functions such as +, -, *, or / to the results.

In[9]:=
Click for copyable input
Out[9]=
In[10]:=
Click for copyable input
Out[10]=
In[11]:=
Click for copyable input
Out[11]=

You can also select only distinct values.

In[12]:=
Click for copyable input
Out[12]=

You can also group values.

In[13]:=
Click for copyable input
Out[13]//TableForm=

Many databases also support retrieving a range of results.

In[14]:=
Click for copyable input
Out[14]=
In[15]:=
Click for copyable input
Out[15]=

More complex SELECT statements using INNER JOIN and OUTER JOIN can be used in a FROM clause to combine records from two tables.

In[16]:=
Click for copyable input
Out[16]=
In[17]:=
Click for copyable input
Out[17]//TableForm=

This closes the connection.

In[18]:=
Click for copyable input
New to Mathematica? Find your learning path »
Have a question? Ask support »