4MKBE‖

kJs5m‖Query Design

GU8Jd‖The Query Design View allows you to create and edit a database query.

To access this command...

In a database file window, click the Queries icon, then choose Edit - Edit.


note

vGBE5‖Most databases use queries to filter or to sort database tables to display records on your computer. Views offer the same functionality as queries, but on the server side. If your database is on a server that supports views, you can use views to filter the records on the server to speed up the display time.


note

WZcUE‖Selecting the Create View command from the Tables tab page of a database document, you see the View Design window that resembles the Query Design window described here.


JMyC7‖The Query Design window layout is stored with a created query, but cannot be stored with a created view.

TEBj6‖The Design View

zkTQc‖To create a query, click the Queries icon in a database document, then click Create Query in Design View.

AtAHv‖The lower pane of the Design View is where you define the query. To define a query, specify the database field names to include and the criteria for displaying the fields. To rearrange the columns in the lower pane of the Design View, drag a column header to a new location, or select the column and press +arrow key.

74LSC‖In the top of the query Design View window, the icons of the Query Design Bar and the Design bar are displayed.

hYsxY‖If you want to test a query, double-click the query name in the database document. The query result is displayed in a table similar to the Data Source View. Note: the table displayed is only temporary.

B4HEH‖Keys in Query Design View

Cvd4o‖Key

mCy9S‖Function

yybiC‖F4

FMTZD‖Preview

YQhGF‖F5

C9yhE‖Run Query

jdEeJ‖F7

6Y6Uw‖Add Table or Query


WN7wR‖Browse

5y4VZ‖When you open the query design for the first time, you see a dialog in which you must first select the table or query that will be the basis for your new query.

FBQA9‖Double-click fields to add them to the query. Drag-and-drop to define relations.

note

eG8FD‖While designing a query, you cannot modify the selected tables.


NLywF‖Remove tables

TbQzA‖To remove the table from Design View, click the upper border of the table window and display the context menu. You can use the Delete command to remove the table from the Design View. Another option is to press the Delete key.

VLTKB‖Move table and modify table size

amBsQ‖You can resize and arrange the tables according to your preferences. To move tables, drag the upper border to the desired position. Enlarge or reduce the size in which the table is displayed by positioning the mouse cursor on a border or on a corner and dragging the table until it is the desired size.

UoCRG‖Table Relations

BFCxB‖If there are data relations between a field name in one table and a field name in another table, you can use these relations for your query.

jcLbE‖If, for example, you have a spreadsheet for articles identified by an article number, and a spreadsheet for customers in which you record all articles that a customer orders using the corresponding article numbers, then there is a relationship between the two "article number" data fields. If you now want to create a query that returns all articles that a customer has ordered, you must retrieve data from two spreadsheets. To do this, you must inform LibreOfficeDev about the relationship which exists between the data in the two spreadsheets.

FspJi‖To do this, click a field name in a table (for example, the field name "Item-Number" from the Customer table), hold down the mouse button and then drag the field name to the field name of the other table ("Item-Number" from the Item table). When you release the mouse button, a line connecting the two fields between the two table windows appears. The corresponding condition that the content of the two field names must be identical is entered in the resulting SQL query.

FmAaU‖The creation of a query that is based on several related sheets is only possible if you use LibreOfficeDev as the interface for a relational database.

note

N2f8q‖You cannot access tables from different databases in a query. Queries involving multiple tables can only be created within one database.


nLSiq‖Specifying the relation type

Js8Ga‖If you double-click on the line connecting two linked fields or call the menu command Insert - New Relation, you can specify the type of relation in the Relations dialog.

rAkmw‖ Alternatively, press Tab until the line is selected, then press Shift+F10 to display the context menu and there choose the command Edit. Some databases support only a subset of the possible join types.

n3PMB‖Deleting relations

jCb4H‖To delete a relation between two tables, click the connection line and then press the Delete key.

3UCig‖Alternatively, delete the respective entries in Fields involved in the Relations dialog. Or press Tab until the connecting vector is displayed highlighted, then press Shift+F10 to open the context menu and select Delete command.

pBybB‖Defining the query

yGfhU‖Select conditions to define the query. Each column of the design table accepts a data field for the query. The conditions in one row are linked with a Boolean AND.

UB5nG‖Specifying field names

jyKMG‖First, select all field names from the tables that you want to add to the query. You can do this either by drag-and-drop or by double-clicking a field name in the table window. With the drag-and-drop method, use the mouse to drag a field name from the table window into the lower area of the query design window. As you do this, you can decide which column in the query design window will receive the selected field. A field name can also be selected by double-clicking. It will then be added to the next free column in the query design window.

66Dcr‖Deleting field names

AbhrW‖To remove a field name from the query, click the column header of the field and choose the Delete command on the context menu for the column.

V92gB‖Saving the query

2kWoA‖Use the Save icon on the Standard toolbar to save the query. You will see a dialog that asks you to enter a name for the query. If the database supports schemas, you can also enter a schema name.

M9UQL‖Schema

4Jwm3‖Enter the name of the schema that is assigned to the query or table view.

6Q72c‖Query name or table view name

Cw73K‖Enter the name of the query or table view.

qgbNu‖Filtering data

Q9pG5‖To filter data for the query, set the desired criteria in the lower area of the query design window. The following options are available:

xxoMA‖Field

4KDzZ‖Enter the name of the data field that is referred to in the Query. All settings made in the filter option rows refer to this field. If you activate a cell here with a mouse click you'll see an arrow button, which enables you to select a field. The "Table name.*" option selects all data fields with the effect that the specified criteria will be applied to all table fields.

Z3pwF‖Alias

EDa3A‖Specifies an alias. This alias will be listed in the query instead of the field name. This makes it possible to use user-defined column labels. For example, if the data field is named PtNo and, instead of that name, you would like to have PartNum appear in the query, enter PartNum as the alias.

vvWbt‖In a SQL statement, aliases are defined as follows:

CGsBz‖SELECT column AS alias FROM table.

TWexq‖For example:


SELECT "PtNo" AS "PartNum" FROM "Parts"

roTzi‖Table

GM9Sp‖The corresponding database table of the selected data field is listed here. If you activate this cell with a mouse click, an arrow will appear which enables you to select a different table for the current query.

JGcfa‖Sort

uXuDt‖If you click on this cell, you can choose a sort option: ascending, descending and unsorted. Text fields will be sorted alphabetically and numerical fields numerically. For most databases, administrators can set the sorting options at the database level.

XsqW8‖Visible

AAZfA‖If you mark the Visible property for a data field, that field will be visibly displayed in the resulting query. If you are only using a data field to formulate a condition or make a calculation, you do not necessarily need to display it.

eQFRR‖Criteria

fWRgB‖Specifies a first criteria by which the content of the data field is to be filtered.

qpADC‖or

KFVy8‖Here you can enter one additional filter criterion for each line. Multiple criteria in a single column will be interpreted as boolean OR.

eXvp7‖You can also use the context menu of the line headers in the lower area of the query design window to insert a filter based on a function:

5x8LE‖Functions

3ktGt‖ The functions which are available here depend on those provided by the database engine.

qFuqw‖If you are working with the embedded HSQL database, the list box in the Function row offers you the following options:

9tdDn‖Option

SQL

kBvXF‖Effect

zCunm‖No function

kZMTN‖No function will be executed.

6dWZZ‖Average

AVG

NfRNs‖Calculates the arithmetic mean of a field.

6z2Kj‖Count

COUNT

rvWA5‖Determines the number of records in the table. Empty fields can either be counted (a) or excluded (b).

UyAx2‖a) COUNT(*): Passing an asterisk as the argument counts all records in the table.

FNCC8‖b) COUNT(column): Passing a field name as an argument counts only the records in which the specified field contains a value. Records in which the field has a Null value (i.e. contains no textual or numeric value) will not be counted.

2ubvb‖Maximum

MAX

ds4ey‖Determines the highest value of a record for that field.

EhSWy‖Minimum

MIN

VxmeB‖Determines the lowest value of a record for that field.

CvkuF‖Sum

SUM

82gAC‖Calculates the sum of the values of records for the associated fields.

zCzVC‖Group

GROUP BY

tSPNG‖Groups query data according to the selected field name. Functions are executed according to the specified groups. In SQL, this option corresponds to the GROUP BY clause. If a criterion is added, this entry appears in the SQL HAVING sub-clause.


qHfpD‖You can also enter function calls directly into the SQL statement. The syntax is:

Qg6Ue‖SELECT FUNCTION(column) FROM table.

qAAoF‖For example, the function call in SQL for calculating a sum is:


VrHLf‖SELECT SUM("Price") FROM "Article".

dABCo‖Except for the Group function, the above functions are called Aggregate functions. These are functions that calculate data to create summaries from the results. Additional functions that are not listed in the list box might be also possible. These depend on the specific database engine in use and on the current functionality provided by the Base driver used to connect to that database engine.

BVC6J‖To use other functions not listed in the list box, you must enter them manually under Field.

WkboS‖You can also assign aliases to function calls. If you do not want to display the query string in the column header, enter a desired substitute name under Alias.

98GCC‖The corresponding function in an SQL statement is:

WACG9‖SELECT FUNCTION() AS alias FROM table

EjzuD‖Example:


G9URE‖SELECT COUNT(*) AS count FROM "Item"
note

xiNnR‖If you run such a function, you cannot insert any additional columns for the query other than as an argument in a "Group" function.


dRKaU‖ Examples

N5CBE‖In the following example, a query is run through two tables: an "Item" table with the "Item_No" field and a "Suppliers" table with the "Supplier_Name" field. In addition, both tables have a common field name "Supplier_No."

P5hJD‖The following steps are required to create a query containing all suppliers who deliver more than three items.

  1. ZhRQD‖Insert the "Item" and "Suppliers" tables into the query design.

  2. LMRUV‖Link the "Supplier_No" fields of the two tables if there is not already a relation of this type.

  3. qWhFA‖Double-click on the "Item_No" field from the "Item" table. Display the Function line using the context menu and select the Count function.

  4. TgPA2‖Enter >3 as a criterion and disable the Visible field.

  5. VwEhF‖Double-click the "Supplier_Name" field in the "Suppliers" table and choose the Group function.

  6. zsjaa‖Run the query.

EzQsj‖If the "price" (for the individual price of an article) and "Supplier_No" (for the supplier of the article) fields exist in the "Item" table, you can obtain the average price of the item that a supplier provides with the following query:

  1. qAByp‖Insert the "Item" table into the query design.

  2. tjfuE‖Double-click the "Price" and "Supplier_No" fields.

  3. 6dBkt‖Enable the Function line and select the Average function from the "Price" field.

  4. x8JB3‖You can also enter "Average" in the line for the alias name (without quotation marks).

  5. D4A9u‖Choose Group for the "Supplier_No" field.

  6. BUYS9‖Run the query.

EkHzB‖The following context menu commands and symbols are available:

PesFs‖Functions

BchuJ‖Shows or hides a row for the selection of functions.

yx5XE‖Table Name

ELTGJ‖Shows or hides the row for the table name.

DDFEA‖Alias Name

LDFZB‖Shows or hides the row for the alias name.

wnNhq‖Distinct Values

23sAF‖Retrieves only distinct values from the query. This applies to multiple records that might contain several repeating occurrences of data in the selected fields. If the Distinct Values command is active, you should only see one record in the query (DISTINCT). Otherwise, you will see all records corresponding to the query criteria (ALL).

RZED7‖For example, if the name "Smith" occurs several times in your address database, you can choose the Distinct Values command to specify in the query that the name "Smith" will occur only once.

2GvRf‖For a query involving several fields, the combination of values from all fields must be unique so that the result can be formed from a specific record. For example, you have "Smith in Chicago" once in your address book and "Smith in London" twice. With the Distinct Values command, the query will use the two fields "last name" and "city" and return the query result "Smith in Chicago" once and "Smith in London" once.

m5UcG‖In SQL, this command corresponds to the DISTINCT predicate.

GHsJd‖Limit

MijJg‖Allows you to limit the maximum number of records returned by a query.

B6S5f‖If a Limit construction is added, you will get at most as many rows as the number you specify. Otherwise, you will see all records corresponding to the query criteria.

MGqK3‖Formulating filter conditions

iFSpm‖When formulating filter conditions, various operators and commands are available to you. Apart from the relational operators, there are SQL-specific commands that query the content of database fields. If you use these commands in the LibreOfficeDev syntax, LibreOfficeDev automatically converts these into the corresponding SQL syntax via an internal parser. You can also enter the SQL command directly and bypass the internal parser. The following tables give an overview of the operators and commands:

fXeDd‖Operator

mfdEx‖Meaning

mBZgC‖Condition is satisfied if...

=

gqkRK‖equal to

hw7KZ‖... the content of the field is identical to the indicated expression.

A8XJU‖The operator = will not be displayed in the query fields. If you enter a value without any operator, the = operator is automatically assumed.

<>

mWwUE‖not equal to

Db7BG‖... the content of the field does not correspond to the specified expression.

>

dtjkU‖greater than

gCWug‖... the content of the field is greater than the specified expression.

<

QkAKk‖less than

xxPdk‖... the content of the field is less than the specified expression.

>=

4aJjX‖greater than or equal to

2rwQm‖... the content of the field is greater than or equal to the specified expression.

<=

ADRZk‖less than or equal to

9KtmZ‖... the content of the field is less than or equal to the specified expression.


DBXG9‖LibreOfficeDev command

Yo7MG‖SQL command

pJay6‖Meaning

qmaX5‖Condition is satisfied if...

IS EMPTY

IS NULL

do6XQ‖is null

NPqBL‖... the field contains no data. For Yes/No fields with three possible states, this command automatically queries the undetermined state (neither Yes nor No).

IS NOT EMPTY

IS NOT NULL

7Rfbd‖is not empty

w3Tva‖... the field is not empty, i.e it contains data.

LIKE

GGKUH‖placeholder (*) for any number of characters

gbEWB‖placeholder (?) for exactly one character

LIKE

bQa5J‖

agxhB‖placeholder (%) for any number of characters

EE9ii‖Placeholder (_) for exactly one character

za5g2‖is an element of

2Y3zW‖... the data field contains the indicated expression. The (*) placeholder indicates whether the expression x occurs at the beginning of (x*), at the end of (*x) or inside the field content (*x*). You can enter as a placeholder in SQL queries either the SQL % character or the familiar (*) file system placeholder in the LibreOfficeDev interface.

CPJyr‖The (*) or (%) placeholder stands for any number of characters. The question mark (?) in the LibreOfficeDev interface or the underscore (_) in SQL queries is used to represent exactly one character.

NOT LIKE

NOT LIKE

AAEXi‖Is not an element of

9vFBZ‖... the field does not contain data having the specified expression.

BETWEEN x AND y

BETWEEN x AND y

CD2Ra‖falls within the interval [x,y]

cDe2u‖... the field contains a data value that lies between the two values x and y.

NOT BETWEEN x AND y

NOT BETWEEN x AND y

KYAXv‖Does not fall within the interval [x,y]

cVfAF‖... the field contains a data value that does not lie between the two values x and y.

IN (a; b; c...)

DBBQE‖Note that semicolons are used as separators in all value lists!

IN (a, b, c...)

evEuh‖contains a, b, c...

eeFC2‖... the field name contains one of the specified expressions a, b, c,... Any number of expressions can be specified, and the result of the query is determined by a boolean OR operator. The expressions a, b, c... can be either numbers or characters

NOT IN (a; b; c...)

NOT IN (a, b, c...)

JXq76‖does not contain a, b, c...

U5doB‖... the field does not contain one of the specified expressions a, b, c,...

= TRUE

= TRUE

cECKt‖has the value True

fbgDt‖... the field name has the value True.

= FALSE

= FALSE

39zcD‖has the value false

fGHY6‖... the field data value is set to false.


qQETa‖Examples

LuvGC‖='Ms.'

8GaiA‖returns field names with the field content "Ms."

<'2001-01-10'

C3BDE‖returns dates that occurred before January 10, 2001

mnGgM‖LIKE 'g?ve'

T7ZhS‖returns records with field content such as "give" and "gave".

LIKE 'S*'

f6T3F‖returns records with field contents such as "Sun".

BETWEEN 10 AND 20

AvbKu‖returns records with field content between the values 10 and 20. (The fields can be either text fields or number fields).

IN (1; 3; 5; 7)

3tymM‖returns records with the values 1, 3, 5, 7. If the field name contains an item number, for example, you can create a query that returns the item having the specified number.

cBAnB‖NOT IN ('Smith')

uusce‖returns records that do not contain "Smith".


N2oSA‖ Like Escape Sequence: {escape 'escape-character'}

EjzuD‖Example:


SELECT * FROM Item WHERE ItemName LIKE 'The *%' {escape '*'}

newGb‖The example will give you all of the entries where the item name begins with 'The *'. This means that you can also search for characters that would otherwise be interpreted as placeholders, such as *, ?, _, % or the period.

gNA7T‖ Outer Join Escape Sequence: {oj outer-join}

EjzuD‖Example:


SELECT Article.* FROM {oj item LEFT OUTER JOIN orders ON item.no=orders.ANR}

mWG9p‖Querying text fields

sxYQF‖To query the content of a text field, you must put the expression between single quotes. The distinction between uppercase and lowercase letters depends on the database in use. LIKE, by definition, is case-sensitive (though some databases don't interpret this strictly).

BEp4G‖Querying date fields

CJEmy‖ Date fields are represented as #Date# to clearly identify them as dates. Date, time and date/time constants (literals) used in conditions can be of either the SQL Escape Syntax type, or default SQL2 syntax.

Zzuo6‖Date Type Element

JKys2‖SQL Escape syntax #1 - may be obsolete

AzkWz‖SQL Escape syntax #2

UJ6VA‖SQL2 syntax

9V3Ky‖Date

{D'YYYY-MM-DD'}

{d 'YYYY-MM-DD'}

'YYYY-MM-DD'

YNF3S‖Time

{D'HH:MM:SS'}

{t 'HH:MI:SS[.SS]'}

'HH:MI:SS[.SS]'

ssX5b‖DateTime

{D'YYYY-MM-DD HH:MM:SS'}

{ts 'YYYY-MM-DD HH:MI:SS[.SS]'}

'YYYY-MM-DD HH:MI:SS[.SS]'


EjzuD‖Example:


SELECT {d '1999-12-31'} FROM world.years

EjzuD‖Example:


SELECT * FROM mytable WHERE years='1999-12-31'

CZdA4‖All date expressions (date literals) must be enclosed with single quotation marks. (Consult the reference for the particular database and connector you are using for more details.)

HXdKT‖Querying Yes/No fields

xWzix‖To query Yes/No fields, use the following syntax for dBASE tables:

A4Uh7‖Status

FnXiE‖Query criterion

e6DJr‖Example

Guy7d‖Yes

p9WTn‖for dBASE tables: not equal to any given value

RFrvz‖=1 returns all records where the Yes/No field has the status "Yes" or "On" (selected in black),

3P4ZB‖No

BzBAa‖.

TFsQG‖=0 returns all records for which the Yes/No field has the status "No" or "Off" (no selection).

9KXzK‖Null

CwGZv‖IS NULL

dyXYc‖IS NULL returns all records for which the Yes/No field has neither of the states Yes or No (selected in gray).


note

YWk5J‖The syntax depends on the database system used. You should also note that Yes/No fields can be defined differently (only 2 states instead of 3).


mmVa8‖Parameter queries

FthAC‖Parameter queries allow the user to input values at run-time. These values are used within the criteria for selecting the records to be displayed. Each such value has a parameter name associated with it, which is used to prompt the user when the query is run.

Be7XG‖Parameter names are preceded by a colon in both the Design and SQL views of a query. This can be used wherever a value can appear. If the same value is to appear more than once in the query, the same parameter name is used.

f2NMg‖In the simplest case, where the user enters a value which is matched for equality, the parameter name with its preceding colon is simply entered in the Criterion row. In SQL mode this should be typed as WHERE "Field" = :Parameter_name

warning

DZCXm‖Parameter names may not contain any of the characters <space>`!"$%^*()+={}[]@'~#<>?/,. They may not be the same as field names or SQL reserved words. They may be the same as aliases.


tip

WBEtt‖A useful construction for selecting records based on parts of a text field's content is to add a hidden column with "LIKE '%' || :Part_of_field || '%'" as the criterion. This will select records with an exact match. If a case-insensitive test is wanted, one solution is to use LOWER (Field_Name) as the field and LIKE LOWER ( '%' || :Part_of_field || '%' ) as the criterion. Note that the spaces in the criterion are important; if they are left out the SQL parser interprets the entire criterion as a string to be matched. In SQL mode this should be typed as LOWER ( "Field_Name" ) LIKE LOWER ( '%' || :Part_of_field || '%' ).


EAESi‖Parameter queries may be used as the data source for subforms, to allow the user to restrict the displayed records.

DRj78‖Parameter Input

BisCF‖The Parameter Input dialog asks the user to enter the parameter values. Enter a value for each query parameter and confirm by clicking OK or typing Enter.

eGETM‖The values entered by the user may consist of any characters which are allowable for the SQL for the relevant criterion; this may depend on the underlying database system.

tip

seFhG‖The user can use the SQL wild-card characters "%" (arbitrary string) or "_" (arbitrary single character) as part of the value to retrieve records with more complex criteria.


wRe6v‖SQL Mode

5avVu‖SQL stands for "Structured Query Language" and describes instructions for updating and administering relational databases.

wDAAY‖In LibreOfficeDev you do not need any knowledge of SQL for most queries, since you do not have to enter the SQL code. If you create a query in the query designer, LibreOfficeDev automatically converts your instructions into the corresponding SQL syntax. If, with the help of the Switch Design View On/Off button, you change to the SQL view, you can see the SQL commands for a query that has already been created.

hBQFv‖You can formulate your query directly in SQL code. Note, however, that the special syntax is dependent upon the database system that you use.

kkuBG‖If you enter the SQL code manually, you can create SQL-specific queries that are not supported by the graphical interface in the Query designer. These queries must be executed in native SQL mode.

LgvXF‖By clicking the Run SQL command directly icon in the SQL view, you can formulate a query that is not processed by LibreOfficeDev and sent directly to the database engine.