Libreoffice 4.0 Base Handbook Course
Libreoffice 4.0 Base Handbook Course
Libreoffice 4.0 Base Handbook Course
Base Handbook
Copyright
This document is Copyright © 2013 by its contributors as listed below. You may distribute it and/or
modify it under the terms of either the GNU General Public License
(http://www.gnu.org/licenses/gpl.html), version 3 or later, or the Creative Commons Attribution
License (http://creativecommons.org/licenses/by/3.0/), version 3.0 or later.
All trademarks within this guide belong to their legitimate owners.
Contributors
Jochen Schiffers Robert Großkopf Jost Lange
Hazel Russman Martin Fox Andrew Pitonyak
Dan Lewis Jean Hollis Weber
Acknowledgments
This book is based on an original German document, which was translated by Hazel Russman and
Martin Fox.
Feedback
Please direct any comments or suggestions about this document to:
documentation@global.libreoffice.org
Base Handbook 3
Linking tables............................................................................................................................. 48
Entering data into tables............................................................................................................ 52
Entry using the Base GUI...................................................................................................... 52
Direct entry using SQL.......................................................................................................... 57
Problems with these data entry methods...............................................................................59
Chapter 4
Forms.................................................................................................................................. 61
Forms make data entry easier................................................................................................... 62
Creating forms........................................................................................................................... 62
A simple form........................................................................................................................ 62
Toolbars for form design........................................................................................................ 63
Form properties......................................................................................................................... 66
Properties of controls............................................................................................................ 69
A simple form completed....................................................................................................... 95
Main forms and subforms........................................................................................................ 103
One view – many forms........................................................................................................... 115
Chapter 5
Queries.............................................................................................................................. 121
General information on queries................................................................................................ 122
Entering queries....................................................................................................................... 122
Creating queries using the Query Design dialog................................................................. 122
Query enhancement using SQL Mode................................................................................ 134
Using an alias in a query.......................................................................................................... 141
Queries for the creation of list box fields.................................................................................. 142
Queries as a basis for additional information in forms..............................................................143
Data entry possibilities within queries...................................................................................... 143
Use of parameters in queries................................................................................................... 144
Subqueries............................................................................................................................... 144
Correlated subqueries.............................................................................................................. 145
Queries as source tables for queries....................................................................................... 145
Summarizing data with queries................................................................................................ 146
More rapid access to queries using table views....................................................................... 147
Chapter 6
Reports..............................................................................................................................149
Creating reports using the Report Builder................................................................................ 150
The user interface of the Report Builder.................................................................................. 150
General properties of fields................................................................................................. 157
Data properties of fields...................................................................................................... 161
Functions in the Report Builder................................................................................................ 162
Entering formulas................................................................................................................ 162
User-defined functions........................................................................................................ 168
Formula entry for a field...................................................................................................... 169
Conditional print.................................................................................................................. 169
Conditional formatting......................................................................................................... 169
Chapter 7
Linking to Databases....................................................................................................... 171
General notes on database linkage......................................................................................... 172
4 Base Handbook
Registration of databases........................................................................................................ 172
Data source browser................................................................................................................ 172
Data to Text......................................................................................................................... 174
Data to Fields...................................................................................................................... 177
Mail merge............................................................................................................................... 178
Data source of current document........................................................................................ 178
Explorer on/off..................................................................................................................... 178
Creating mail merge documents.............................................................................................. 178
Label printing........................................................................................................................... 185
Direct creation of mail merge and label documents................................................................. 188
Mail merge using the mouse............................................................................................... 188
Creating form letters by selecting fields............................................................................... 189
External forms.......................................................................................................................... 190
Database use in Calc............................................................................................................... 191
Entering data into Calc........................................................................................................ 191
Exporting data from Calc into a database............................................................................ 193
Converting data from one database to another........................................................................ 196
Chapter 8
Database tasks................................................................................................................. 197
General remarks on database tasks........................................................................................ 198
Data filtering............................................................................................................................. 198
Searching for data................................................................................................................... 200
Code snippets.......................................................................................................................... 201
Getting someone's current age........................................................................................... 201
Getting a running balance by categories............................................................................. 202
Line numbering................................................................................................................... 203
Getting a line break through a query................................................................................... 205
Grouping and summarizing................................................................................................. 205
Chapter 9
Macros...............................................................................................................................207
General remarks on macros.................................................................................................... 208
Improving usability................................................................................................................... 209
Automatic updating of forms................................................................................................ 209
Filtering records.................................................................................................................. 210
Searching data records....................................................................................................... 213
Comboboxes as listboxes with an entry option.................................................................... 215
Navigation from one form to another................................................................................... 225
Removing distracting elements from forms......................................................................... 226
Database tasks expanded using macros................................................................................. 226
Making a connection to a database..................................................................................... 226
Securing your database...................................................................................................... 227
Database compaction.......................................................................................................... 228
Decreasing the table index for autovalue fields................................................................... 228
Dialogs..................................................................................................................................... 229
Chapter 10
Database Maintenance.................................................................................................... 239
General remarks on maintaining databases............................................................................. 240
Compacting a database........................................................................................................... 240
Resetting autovalues............................................................................................................... 240
Base Handbook 5
Querying database properties.................................................................................................. 240
Testing tables for unnecessary entries..................................................................................... 241
Testing entries using relationship definition......................................................................... 241
Editing entries using forms and subforms............................................................................ 242
Queries for finding orphan entries....................................................................................... 243
Database search speed........................................................................................................... 243
Effect of queries.................................................................................................................. 243
Effect of listboxes and comboboxes.................................................................................... 244
Appendix ......................................................................................................................... 245
Barcodes................................................................................................................................. 246
Data types for the table editor.................................................................................................. 246
Integers............................................................................................................................... 246
Floating-point numbers........................................................................................................ 246
Text..................................................................................................................................... 247
Time.................................................................................................................................... 247
Other................................................................................................................................... 247
Built-in functions and stored procedures.................................................................................. 248
Numeric............................................................................................................................... 248
Text..................................................................................................................................... 249
Date/Time............................................................................................................................ 250
Database connection........................................................................................................... 251
System................................................................................................................................ 251
Information tables for HSQLDB................................................................................................ 252
Database repair for *.odb files.................................................................................................. 253
Connecting a database to an external HSQLDB...................................................................... 255
Changing the database connection to external HSQLDB........................................................257
Changing the database connection for multi-user access...................................................257
Auto-incrementing values with external HSQLDB............................................................... 259
6 Base Handbook
Preface
Who is this book for?
Anyone who wants to get up to speed quickly with LibreOffice Base will find this book valuable. You
may wish to first read Chapter 8, Getting Started with Base, in the Getting Started guide.
Help system
LibreOffice comes with an extensive Help system. This is your first line of support for using
LibreOffice. To display the full Help system, press F1 or select LibreOffice Help from the Help
menu. In addition, you can choose whether to activate Tips, Extended Tips, and the Help Agent
(using Tools > Options > LibreOffice > General).
If Tips are enabled, place the mouse pointer over any of the icons to see a small box (“tooltip”) with
a brief explanation of the icon’s function. For a more detailed explanation, select Help > What's
This? and hold the pointer over the icon.
8 Base Handbook
This site provides support for LibreOffice, among other programs:
http://forum.openoffice.org/en/forum/
Illustrations
LibreOffice runs on Windows, Linux, and Mac OS X operating systems, each of which has several
versions and can be customized by users (fonts, colors, themes, window managers). The
illustrations in this guide were taken from a variety of computers and operating systems. Therefore,
some illustrations will not look exactly like what you see on your computer display.
Also, some of the dialogs may be differ because of the settings selected in LibreOffice. You can
either use dialogs from your computer system (default) or dialogs provided by LibreOffice. To
change to using LibreOffice dialogs:
1) On Linux and Windows operating systems, go to Tools > Options >LibreOffice > General
on the main menu bar to open the dialog for general options.
2) On a Mac operating system, go to LibreOffice > Preferences > General on the main
menu bar to open the dialog for general options.
3) Select Use LibreOffice dialogs in Open/Save dialogs and, in Linux and Mac OS X operating
systems only, Print dialogs to display the LibreOffice dialogs on your computer display.
4) Click OK to save your settings and close the dialog.
Preface 9
Icons
The icons used to illustrate some of the many tools available in LibreOffice may differ from the
ones used in this guide. The icons in this guide have been taken from a LibreOffice installation that
has been set to display the Galaxy set of icons.
If you wish, you can change your LibreOffice software package to display Galaxy icons as follows:
1) On Linux and Windows operating systems, go to Tools > Options >LibreOffice > View on
the main menu bar to open the dialog for view options.
2) On a Mac operating system, go to LibreOffice > Preferences > View on the main menu
bar to open the dialog for view options.
3) In User interface > Icon size and style select Galaxy from the options available in the drop-
down list.
4) Click OK to save your settings and close the dialog.
Some Linux operating systems, for example Ubuntu, include LibreOffice as part of
the installation and may not include the Galaxy set of icons. You should be able to
Note download the Galaxy icon set from the software repository for your Linux operating
system.
10 Base Handbook
Figure 1: Dialog showing common controls
Preface 11
Frequently asked questions
How is LibreOffice licensed?
LibreOffice is distributed under the Open Source Initiative (OSI) approved Lesser General
Public License (LGPL). The LGPL license is available from the LibreOffice website:
http://www.libreoffice.org/download/license/
May I distribute the PDF of this book, or print and sell copies?
Yes, as long as you meet the requirements of one of the licenses in the copyright statement at
the beginning of this book. You do not have to request special permission. In addition, we
request that you share with the project some of the profits you make from sales of books, in
consideration of all the work we have put into producing them.
12 Base Handbook
Chapter 1
Introduction to Base
Introduction
In everyday office operation, spreadsheets are regularly used to aggregate sets of data and to
perform some kind of analyses on them. As the data in a spreadsheet is laid out in a table view,
plainly visible and able to be edited or added to, many users ask why they should use a database
instead of a spreadsheet. This handbook explains the differences between the two, beginning with
a short section on what can be done with a database.
This chapter introduces two database examples and the entire Handbook is built around these.
One database is named Media_without_macros.odb and the other, extended with the
inclusion of macros, is named Media_with_macros.odb.
The Base environment contains four work areas: Tables, Queries, Forms, and Reports. Depending
on the work area selected, various tasks—creating new content or calling up existing elements—
may be carried out.
Base starts with the Form view, because forms are the elements most commonly used when
working with databases.
14 Base Handbook
Data input using forms
Simple forms show just one table as in the upper part of the Loan form.
The table structure for such a form is relatively basic and easy to set up. In the table shown above,
the same data can be directly input in the rows and columns of the table as when using the form.
• The first field shows a primary key (“ID”) which is automatically generated. More on this
topic can be found in the chapter on Tables.
• The second field, Media_ID, stores the primary key of the Media table, a number which
refers to the Media. In the form the media id, title and author are shown in the drop-down
menu.
16 Base Handbook
• The third field, Reader_ID, stores the primary key of the Reader table. This key is a number
which refers to the reader. In the form the Last name and First name of the reader are
shown.
• The fourth field stores the loan date. If this date is present and is later than the current
date, the corresponding data set for the reader is shown in the bottom table of the form
under Return.
• The field marked Extension contains information about extensions of the loan for an item.
The meaning of the values 1, 2 and so on is explained later. The database contains a
special table called Settings for this type of information.
The input of this data permits the management of a simple library.
The query shown above lists all media which are currently out on loan. It calculates for each item
how long it has been on loan and the balance of the loan period.
• All media for which the Return_Date field is empty is listed. As an additional overview, the
medium name is included in the query together with the Media_ID.
• The reference to the Reader is established with the primary key of the Reader table.
• The value of the LoanDays field is calculated as the difference between the Loan_Date and
the current date.
• The number of LoanDays is subtracted from the Loan Time to give the remaining number
of days in the loan period. The Loan Time can vary with different media types.
• In the Settings table a value of '1' for Extension corresponds to an extension of the loan
period of 7 days. In the data set above, the line with Media_ID '2' shows an extension of 7
days.
The recall notice is generated by means of a query from the previously input data. The user of the
database needs only to choose the Recall report and a recall letter can be printed out and sent to
all persons who have a recall entry made in the form on the previous page.
In such a report there may be multiple entries (overdue items) for a particular person. If the table
containing the items for this person exceeds the space on a page, it is extended to cover a
succeeding page.
Such a report is more encompassing than a mail merge letter produced with Writer. It automatically
gathers together the data sets for printing and arranges the necessary accompanying text
accordingly.
18 Base Handbook
Chapter 1 Introduction to Base 19
Chapter 2
Creating a Database
How to create a new database
General notes on the creation of a database
The basics of creating a database in LibreOffice are described in Chapter 8 of the Getting Started
guide, Getting Started with Base.
The database component of LibreOffice, called Base, provides a graphical interface for working
with databases. In addition, LibreOffice contains a version of the HSQL database engine. This
HSQLDB database can only be used by a single user. The entire data set is stored in an ODB file
which has no file locking mechanism when opened by a user.
22 Base Handbook
MySQL databases
There was an extension for MySQL, the MySQL Native Connector, which should allow Base to
connect directly to a MySQL database. The extension was in the LibreOffice Extensions center
under the Base Category but is not being developed at present.
General access to MySQL for versions of LibreOffice from 3.5 onwads is via JDBC or ODBC. To be
able to use JDBC, it is necessary to install mysql-connector-java.jar. This Java Archive file is best
copied into the same folder where the current java version used in LibreOffice is located. This is
likely to be a subfolder like ...javapath.../lib/ext for a Linux installation.
Alternatively the appropriate folder containing the Java archive can be set through Tools >
Options > Java > ClassPath.
The method of access to an existing MySQL database is shown in the following steps.
Creation of a new database is only possible in the internal HSQLDB format. Connection to an
external database is only possible when the database already exists.
Select the Connect to an existing database option. A list of database formats is contained on the
pull-down menu. Select MySQL.
24 Base Handbook
Type in the JDBC driver class and click the Test class button. A dialog should pop up confirming
that the connector is loaded and accessible using Java. The mysql-connector-java.jar file must
either be in the same path as the version of Java in use in LibreOffice or directly linked in to
LibreOffice.
If a direct connection was selected, this test will generate error messages. Without
Note testing, Base will, at the end of the Assistant, open the database window and
connection to MySQL.
26 Base Handbook
The connection test starts the authentication process using the user name previously input. After
the correct password is input, a dialog announces the result of the test. If MySQL is not running at
this time, an error message is shown.
The final step is registering the database. The database can, if necessary, be registered at a later
time to allow its use with Writer or Calc.
28 Base Handbook
The tables in the database are contained in the tree under the name of the database.
The view of the table tree can be closed by clicking on the database name. For a single database
connection this does not make much sense, but it does give a visible indication of the direct
connection.
Instead of only the database input in Step 3 of the Wizard (see lower status bar), LibreOffice opens
all databases that are available in MySQL to the user “robby”.
Queries must include in the MySQL syntax not only the table name but also the database which
contains, for example, the following code:
… FROM "myphplib"."ASB" AS "ASB", "myphplib"."Kategorien" AS "Kategorien"
It is also possible in every such case to specify an alias, made up from the database and table
names. More details are given in the chapter on Queries.
Tables can be created and deleted in a database. Fields with auto values may be created when
setting up the structure of tables. In MySQL the starting value of such fields defaults to 1.
The connection is made to a specific folder. All DBF files in this folder will be included and shown in
the ODB database and can be linked together using queries.
Tables in dBase have no primary key. They can in principle be described as corresponding to the
worksheets in Calc.
30 Base Handbook
Tables can be created and will then be copied as new files in the folder previously selected.
The number of different field types for a new dBase table is clearly less than when the internal
HSQLDB format is used. In the following figure there are still some field types with the same type
name.
The dBase format is especially suitable for the exchange and extensive editing of data. In addition,
spreadsheet calculations can directly access dBase tables. It may be better to manipulate the data
in Base because Calc requires the input of the type of character encoding, whereas Base simply
takes the appropriate encoding provided by the operating system. Old dBase files may exhibit
small decoding errors where special characters have been used.
Spreadsheets
Calc or Excel spreadsheets can also be used as the table source for databases. If, however, a
Calc spreadsheet is used, no editing of the table data will be possible. If the Calc document is still
open, it will be write protected.
The only questions to be answered are the location of the spreadsheet file and whether or not it is
password protected. Base then opens the spreadsheet and includes all worksheets in the
document. The first row is used for the field names and the worksheet names become the table
names.
Relationships between spreadsheets cannot be set up in Base, as Calc is not suitable for use as a
relational database.
All tables are shown. As in Calc, the tables are not editable. Base uses the table data only for
queries and mail merge applications.
32 Base Handbook
Chapter 3
Tables
General information on tables
Databases store data in tables. The main difference from the tables in a simple spreadsheet is that
the fields into which the data is written must be clearly defined beforehand. For example, a
database does not allow a text field to contain numbers for use in calculations. Such numbers are
displayed, but only as strings, whose actual numerical value is zero. Similarly, images cannot be
included in all types of fields.
Details of which data types are available can be obtained from the Table Design window in Base.
They are shown in the Appendix to this handbook.
Simple databases are based on only one table. All data elements are entered independently, which
can lead to multiple entry of the same data. A simple address book for private use can be created
in this way. However, the address book of a school or a sports association could contain so much
repetition of postcodes and locations that these fields are better placed in one or even two
separate tables.
Storing data in separate tables helps:
• Reduce repeated input of the same content
• Prevent spelling errors due to repeated input
• Improve filtering of data in the displayed tables
When creating a table, you should always consider whether multiple repetitions, especially of text
or images (which consume a lot of storage) may occur in the table. If so, you need to export them
into another table. How to do this in principle is described in Chapter 8, Getting Started with Base,
in the Getting Started with LibreOffice book.
34 Base Handbook
Figure 2: Relationship diagram for the example database media_without_macros
One-to-many relationships
The media_without_macros database lists the titles of the media in one table. Because titles can
have multiple subtitles or sometimes none at all, the subtitles are stored in a separate table.
This relationship is known as one-to-many (1:n). Many subtitles may be assigned to one medium,
for example the many track titles for a music CD. The primary key for the Media table is stored as a
foreign key in the Subtitle table. The majority of relationships between tables in a database are
one-to-many relationships.
Chapter 3 Tables 35
Many-to-many relationships
A database for a library might contain a table for authors’ names and a table for the media. The
connection between an author and, for example, books that author has written, is obvious. The
library might contain more than one book by one author. It might also contain books with multiple
authors. This relationship is known as many-to-many (n:m). Such relationships require a table that
acts as an intermediary between the two tables concerned. This is represented in Figure 3 by the
rel_Media_Author table.
Thus, in practice, the n:m relationship is solved by treating it as two 1:n relationships. In the
intermediate table, the Media_ID can occur more than once, as can the Author_ID. But when using
them as a pair, there is no duplication: no two pairs are identical. So this pair meets the
requirements for the primary key for the intermediate table.
For a given value for Media_ID, there is only one title of the media and one ISBN.
For a given value for Author_ID, there is only one Author's first and last name. So,
Note for a given pair of these values, there is only one ISBN and only one Author. This
makes the pair unique.
One-to-one relationships
36 Base Handbook
therefore leads to fields being exported which will be filled with content for only some of the
records.
Chapter 3 Tables 37
In this table all fields that are directly entered are assumed not to be also in use for other media
with the same content. Duplication should therefore be avoided.
For this reason, planned fields in the table include the title, the ISBN, an image of the cover, and
the year of publication. The list of fields can be extended if required. So, for instance, librarians
might want to include fields for the size (number of pages), the series title, and so on.
The Subtitle table contains the detailed content of CDs. As a CD can contain several pieces of
music, a record of the individual pieces in the main table would require a lot of additional fields
(Subtitle 1, Subtitle 2, etc.) or the same item would have to be entered many times. The Subtitle
table therefore stands in a n:1 relationship to the Media table.
The fields of the Subtitle table are (in addition to the subtitle itself) the sequence number of the
subtitle and the duration of the track. The Length field must first be defined as a time field. In this
way, the total duration of the CD can be calculated and displayed in a summary if necessary.
The authors have a n:m relationship to the media. One item can have several authors, and one
author might have created several items. This relationship is controlled by the rel_Media_Author
table. The primary key of this linking table is the foreign key, formed from the Author and Media
tables. The rel_Media_Author table includes an additional sorting (Author_Sort) of authors, for
example by the sequence in which they are named in the book. In addition, a supplementary label
such as Producer, Photographer and so on is added to the author where necessary.
Category, Mediastyle, Town and Publisher have a 1:n relationship.
For the Category, a small library can use something like Art or Biology. For larger libraries,
general systems for libraries are available. These systems provide both abbreviations and
complete descriptions. Hence both fields appear under Category.
The Mediastyle is linked to the loan period Loantime. For example, video DVDs might on principle
have a loan period of 7 days, but books might be loaned for 21 days. If the loan period is linked to
any other criteria, there will be corresponding changes in your methodology.
The Town table serves not only to store location data from the media but also to store the locations
used in the addresses of users.
Since Publishers also recur frequently, a separate table is provided for them.
The Media table has in total four foreign keys and one primary key, which is used as a foreign key
in two tables, as shown in Figure 5.
Loan table
The central table is Loan (see Figure 6). It is the link between the Media and Reader tables. In
case you need to find out retrospectively who has taken out a book (for example, if someone
notices during the loan process that the book is damaged, or if you wish to make a list of the most
popular media), the Loan_Date in the loan record is not simply deleted during the return process.
Instead a Return_Date is recorded.
Similarly, Reminders are integrated into the loan procedure. Each reminder is separately entered
into the Recall table so that the total number of reminders can be determined.
As well as an extension period in weeks, there is an extra field in the loan record that enables
media to be loaned using a barcode scanner (Media_ID_BC). Barcodes contain, in addition to the
individual Media_ID, a check digit which the scanner can use to determine if the value scanned in
is correct. This barcode field is included here only for test purposes. It would be better if the
primary key of the Media table could be directly entered in barcode form, or if a macro were used
to remove the check digit from the entered barcode number before storage.
Finally we need to connect the Reader to the loan. In the actual reader table, only the name, an
optional lock, and a foreign key linking to the Gender table are included in the plan.
38 Base Handbook
Figure 6: Loan
The Gender table ensures that the correct Salutation is used in reminders. The writing of
reminders can then be automated as far as possible. In addition, some given names can be
equally masculine or feminine. Therefore the separate listing of gender is required even when
reminders are written out by hand.
Chapter 3 Tables 39
The rel_Reader_Schoolclass table, like the Address table, has a 1:1 relationship with the
Reader table. This was chosen because either the school class or the address might be required.
Otherwise the Schoolclass_ID could be put directly into the pupil table; the same would be true of
the complete content of the address table in a public library system.
A School class usually consists of a year designation and a stream suffix. In a 4-stream school,
this suffix might run from a to d. The suffix is entered in the Class table. The year is in a separate
Grade table. That way, if readers move up a class at the end of each school year, you can simply
change the year entry for everyone.
The Address is also divided. Street is stored separately because street names within an area are
often repeated. Post code and town are separated because there are often several post codes for
a single area and therefore more post codes than towns. So compared with the Address table, the
Postcode table contains significantly fewer records and the Town table even fewer.
How this table structure is put to use is explained further in the Chapter 4, Forms, in this handbook.
Creating tables
Most LibreOffice users will generally use the graphical user interface (GUI) exclusively to create
tables. Direct entry of SQL commands becomes necessary when, for example, a field must
subsequently be inserted at a particular position, or a standard value must be set after the table
has been saved.
Table terminology: The picture below shows the standard division of tables into columns and rows.
TABLE
COLUMN COLUMN
Field Name Field Type Field Name Field Type
(FIELD) (TYPE) NULL DEFAULT (FIELD) (TYPE) NULL DEFAULT
ROW Record
Data records are stored in a single row of the table. Individual columns are largely defined by the
field, the type, and the rules that determine if the field can be empty. According to the type, the size
of the field in characters can also be determined. In addition, a default value can be specified to be
used when nothing was entered into the field.
In the Base GUI, the terms for a column are described somewhat differently, as shown below.
Field becomes Field Name, Type becomes Field Type. Field Name and Field Type are entered into
the upper area of the Table Design window. In the lower area you have the opportunity to set,
under the Field properties the other column properties, in so far as they can be set using the GUI.
Limitations include setting the default value of a date field to the actual date of entry. This is
possible only by using the appropriate SQL command (see “Direct entry of SQL commands” on
page 43).
40 Base Handbook
Default values: The term "Default value" in the GUI does not mean what the
database user generally understands as a default value. The GUI displays a certain
value visibly, which is saved with the data.
Note
The default value in a database is stored in the table definition. It is then written into
the field whenever this is empty in a new data record. SQL default values do not
appear when editing table properties.
Creating an index
Sometimes it is useful to index other fields or a combination of other fields in addition to the
primary key. An index speeds up searching and can also be used to prevent duplicate entries.
Each index has a defined sort order. If a table is displayed without sorting, the sort order will be
according to the content of the fields specified in the index.
Open the table for editing by right-clicking and using the context menu. Then you can access index
creation with Tools > Index Design.
Chapter 3 Tables 41
Figure 9: Creating a new Index
On the Indexes dialog (Figure 9), click New Index to create an index in addition to the primary key.
The new index is automatically given the name index1. The Index field specifies which field or
fields are to be used for this index. At the same time you can choose the Sort order.
42 Base Handbook
NULL is used in databases to designate an empty cell, one that contains nothing.
Note No calculation is possible using a NULL field. This contrasts with spreadsheets, in
which empty fields automatically contain the value 0 (zero).
Example: In a media database, the media number and the loan date are entered when the item is
loaned out. When the item is returned, a return date is entered. In theory, an index using the fields
Media_ID and ReturnDate could easily prevent the same item from being loaned out repeatedly
without the return date being noted. Unfortunately this will not work because the return date initially
has no value. The index will prevent an item from being marked as returned twice with the same
date but it will do nothing else.
You can then enter commands into the upper area of the window (shown in Figure 11). The lower
area shows the result or, if appropriate, the reason why the command failed.
Queries cannot be created here. For these, the Query Design window offers an extra possibility of
editing the query in SQL Mode.
Chapter 3 Tables 43
Figure 11: Dialog for direct entry of SQL commands
A summary of the possible commands for the built-in HSQLDB engine can be found at
http://www.hsqldb.org/doc/1.8/guide/ch09.html. The contents are described in the following
sections. Some commands only make sense when dealing with an external HSQLDB database
(Specify User, etc.). Where necessary, these are dealt with in the section “Working with external
HSQLDB” in the Appendix to this handbook.
Table creation
A simple command to create a usable table is:
CREATE TABLE "Test" ("ID" INT PRIMARY KEY, "Text" VARCHAR(50));
CREATE TABLE "Test": Create a table with the name "Test".
( ): with the specified field names, field types and options.
"ID" INT PRIMARY KEY, "Text" VARCHAR(50): Field name "ID" with the numeric type
integer as the primary key, field name "Text" with the text type variable text length and the text size
limited to 50 characters.
CREATE [MEMORY | CACHED | [GLOBAL] TEMPORARY | TEMP | TEXT] TABLE
"Table name" ( <Field definition> [, ...] [,
<Constraint Definition>...] ) [ON COMMIT {DELETE | PRESERVE} ROWS];
44 Base Handbook
[MEMORY | CACHED | [GLOBAL] TEMPORARY | TEMP | TEXT]:
The default setting is MEMORY: HSQLDB creates all tables in core memory. This setting also
applies to the tables that are written into the embedded database by LibreOffice Base. Another
possibility would be to write the tables to the hard drive and use memory only to buffer access
to the hard drive (CACHED). Tables in TEXT format (such as CSV) are not writable in internal
databases that are set up purely in MEMORY, while Base cannot access TEMPORARY or TEMP
tables. The SQL commands are carried out in this case but the tables are not displayed (and
therefore cannot be deleted) using the GUI, and data entered via SQL is likewise not visible to
the query module of the GUI, unless the automatic deletion of the contents after the final
commit is prevented. Any request in this case shows a table without any contents.
Tables built directly with SQL are not immediately displayed. You must either use View >
Refresh Tables or simply close the database and then reopen it.
<Field definition>:
"Field name" Data type [(Number of characters[,Decimal places])]
[{DEFAULT "Default value" | GENERATED BY DEFAULT AS IDENTITY (START
WITH <n>[, INCREMENT BY <m>])}] | [[NOT] NULL] [IDENTITY] [PRIMARY
KEY]
Allows default values to be included in the field definition.
For text fields, you can enter text in single quotes or NULL. The only SQL function allowed is
CURRENT_USER. This only makes sense if HSQLDB is being used as an external Server
database with several users.
For date and time fields, a date, a time, or a combination of the two can be entered in single
quotes or else NULL. You must ensure that the date follows the American conventions (yyyy-
mm-dd), that time has the format hh:mm:ss, and that a combined date/time value has the
format yyyy-mm-dd hh:mm:ss.
Allowed SQL functions:
for the current date CURRENT_DATE, TODAY, CURDATE()
for the current time CURRENT_TIME, NOW, CURTIME()
for the current data time stamp CURRENT_TIMESTAMP, NOW.
For boolean Fields (yes/no) the expressions FALSE, TRUE, NULL can be entered. These
must be entered without single quotes.
For numeric fields, any valid number in the range, or NULL is possible. Here too, if you enter
NULL, do not use quotes. When entering decimals, make sure that the decimal point is a dot
(period) and not a comma.
For binary fields (images, etc.) any valid hexadecimal string in single quotes or NULL is
possible. A hexadecimal example string is: '0004ff', which represents 3 bytes, first 0, then 4 and
finally 255 (0xff). As binary fields in practice need only be entered for images, you need to know
the binary code of the image that is to serve as a default.
NOT NULL: The field value cannot be NULL. This condition can only be given in the field
definition.
Hexadecimal system: Numbers are based on 16. A mixed system consisting of the
numbers 0 to 9 and the letters a to f provides 16 possible digits for each column.
Note With two columns, you can have 16*16=256 possible values. This corresponds to 1
Byte (28).
Chapter 3 Tables 45
<Constraint definition>:
[CONSTRAINT "Name"]
UNIQUE ( "Field_name 1" [,"Field_name 2"...] ) |
PRIMARY KEY ( "Field_name 1" [,"Field_name 2"...] ) |
FOREIGN KEY ( "Field_name 1" [,"Field_name 2"...] )
REFERENCES "other_table_name" ( "Field_name_1" [,"Field_name 2"...])
[ON {DELETE | UPDATE}
{CASCADE | SET DEFAULT | SET NULL}] |
CHECK(<Search_condition>)
Constraints define conditions that must be fulfilled when data is entered. Constraints can be
given a name.
UNIQUE ("Field_name"): the field value must be unique within that field
PRIMARY KEY ("Field_name"): the field value must be unique and cannot be NULL
(primary key)
FOREIGN KEY ("Field_name") REFERENCES <"other_table_name">
("Field_name"): The specified fields of this table are linked to the fields of another table.
The field value must be tested for referential integrity as foreign keys; that is, there must be a
corresponding primary key in the other table, if a value is entered here.
[ON {DELETE | UPDATE} {CASCADE | SET DEFAULT | SET NULL}]: In the case of a
foreign key, this specifies what is to happen if, for example, the foreign record is deleted. It
makes no sense, in a loan table for a library, to have a user number for which the user no
longer exists. The corresponding record must be modified so that the relationship between the
tables remains valid. Usually the record is simply deleted. This happens if you select ON
DELETE CASCADE.
CHECK(<Search_condition>): Formulated as a WHERE condition, but only for the current
record.
You need constraints when the relationship between tables or the index for certain fields must
be defined.
Table modification
Sometimes you might wish to insert an additional field into a particular position in the table.
Suppose you have a table called Addresses with fields ID, Name, Street, and so on. You realize
that perhaps it would be sensible to distinguish first names and last names.
ALTER TABLE "Addresses" ADD "First Name" VARCHAR(25) BEFORE "Name";
ALTER TABLE "Addresses": Alter the table with the name "Addresses".
ADD "First Name" VARCHAR(25): insert the field "FirstName" with a length of 25 characters.
BEFORE "Name": before the field "Name".
The possibility of specifying the position of additional fields after the creation of the table is not
available in the GUI.
ALTER TABLE "Table_name" ADD [COLUMN] <Field_definition> [BEFORE
"already_existing_field_name"];
The additional designation COLUMN is not necessary in cases where no alternative choices are
available.
46 Base Handbook
ALTER TABLE "Table_name" DROP [COLUMN] "Field_name";
The field "Field name" is erased from the table Table_name. However this does not take place if
the field is involved in a view or as a foreign key in another table.
ALTER TABLE "Table_name" ALTER COLUMN "Field_name" RENAME TO
"New_field_name"
Changes the name of a field.
ALTER TABLE "Table_name" ALTER COLUMN "Field_name" SET DEFAULT
<Standard value>};
Sets a specific default value for the field. NULL removes an existing default value.
ALTER TABLE "Table_name" ALTER COLUMN "Field_name" SET [NOT] NULL
Sets or removes a NOT NULL condition for a field.
ALTER TABLE "Table_name" ALTER COLUMN <Field definition>;
The field definition corresponds to the one from the Table creation with the following restrictions:
• The field must already be a primary key field to accept the property IDENTITY.
IDENTITY means, that the field has the property AutoValue. This is possible only for
INTEGER or BIGINT fields. For these field type descriptions, see the Appendix to this
handbook.
• If the field already has the property IDENTITY but it is not repeated in the field definition,
the existing IDENTITY property is removed.
• The default value will become that specified in the new field definition. If the definition of the
default value is left blank, any default already defined is removed.
• The property NOT NULL continues into the new definition, if not otherwise defined. This is
in contrast to the default value.
• In some cases, depending on the type of modification, the table must be empty in order for
the change to occur. In all cases the change will have effect only if it is possible in principle
(for example a change from NOT NULL to NULL) and the existing values can all be
translated (for example a change from TINYINT to INTEGER).
ALTER TABLE "Table_name" ALTER COLUMN "Field_name" RESTART WITH
<New_field_value>
This command is used exclusively for an IDENTITY field. It determines the next value for a field
with the Autovalue function set. It can be used, for example, when a database is initially used with
test data, and subsequently provided with real data. This requires the contents of the tables to be
deleted and a new value such as "1" to be set for the field.
ALTER TABLE "Table_name"
ADD [CONSTRAINT "Condition_name"] CHECK (<Search_condition>);
This adds a search condition introduced by the word CHECK. Such a condition will not apply
retrospectively to existing records, but it will apply to all subsequent changes and newly entered
records. If a constraint name is not defined, one will be assigned automatically.
Example:
ALTER TABLE "Loan" ADD CHECK
(IFNULL("Return_Date","Loan_Date")>="Loan_Date")
The Loan table needs to be protected from input errors. For example, you must prevent a return
date being given that is earlier than the loan date. Now if this error occurs during the return
process, you will get an error message Check constraint violation …
ALTER TABLE "Table_name"
ADD [CONSTRAINT "Constraint_name"] UNIQUE ("Field_name1",
"Field_name2" ...);
Chapter 3 Tables 47
Here a condition is added that forces the named fields to have different values in each record. If
several fields are named, this condition applies to the combination rather than the individual fields.
NULL does not count here. A field can therefore have the same value repeatedly without causing
any problems, if the other field in each of the records is NULL.
This command will not work if there is already a UNIQUE condition for the same field combination.
ALTER TABLE "Table_name"
ADD [CONSTRAINT "Constraint_name"] PRIMARY KEY ("Field_name1",
"Field_name2" ...);
Adds a primary key, optionally with a constraint, to a table. The syntax of the constraint is the same
as when a table is created.
ALTER TABLE "Table_name"
ADD [CONSTRAINT "Constraint_name"] FOREIGN KEY ("Field_name1",
"Field_name2" ...)
REFERENCES "Table_name_of_another_table" ("Field_name1_other_table",
"Field_name2_other_table" ...)
[ON {DELETE | UPDATE} {CASCADE | SET DEFAULT | SET NULL}];
This adds a foreign key (FOREIGN KEY) to the table. The syntax is the same as when a table is
created.
The operation will terminate with an error message, if any value in the table does not have a
corresponding value in the table containing that primary key.
Example: The Name and Address tables are to be linked. The Name table contains a field with
the name Address_ID. The value of this should be linked to the field ID in the Address table. If the
value "1" is found in Address_ID but not in the ID field of the Address table, the link will not work. It
will not work either if the two fields are of different types.
ALTER TABLE "Table_name" DROP CONSTRAINT "Constraint_name";
This command removes the named constraint (UNIQUE, CHECK, FOREIGN KEY) from a table.
ALTER TABLE "Table_name" RENAME TO "new_table_name";
Finally this command changes only the name of a table.
Deleting tables
DROP TABLE "Table name" [IF EXISTS] [RESTRICT | CASCADE];
Deletes the table "Table name".
IF EXISTS prevents an error occurring if this table does not exist.
RESTRICT is the default arrangement and need not be explicitly chosen; it means that deletion
does not occur if the table is linked to another table by the use of a foreign key or there is an active
view of this table. Queries are not affected as they are not stored within HSQLDB.
If instead you choose CASCADE, all links to the table "Table_name" are deleted. In the linked
tables, all foreign keys are set to NULL. All views referring to the named table are also completely
deleted.
Linking tables
In principle you can have a database without links between tables. The user must then ensure
during data entry, that the relationships between the tables remain correct. This usually occurs
through the use of suitable input forms that manage this.
48 Base Handbook
Deleting records in linked tables is not a simple matter. Suppose you wish to delete a particular
street from the Street table in Figure 7, where this field is linked with the Address table as a foreign
key in that table. The references in the Address table would disappear. The database does not
allow this, once the relationship has been created. In order to delete the Street, the precondition
must be fulfilled, that it is no longer referenced in the Address table.
Basic links are made using Tools > Relationships. This creates a connection line from the primary
key in one table to the defined foreign key in the other.
You may receive the following error message when creating such a link:
This message shows some text in English and the internal SQL command that caused the error.
Column types do not match in statement—As the SQL command is displayed as well, the
reference is clearly to the columns Address.str_ID and Street.ID. For test purposes one of these
fields was defined as an Integer, the other as Tiny Integer. Therefore no link could be created since
the one field cannot have the same value as the other.
In this case the column types match. The SQL statement is the same as in the first example. But
again there is an error:
Integrity constraint violation – no parent 1, table: Address ... —The integrity of the relationship
is not ensured. In the field of the Address table, Address.str_ID, there is a number 1, which is not
present in Street.ID. The parent table here is Street, since its primary key is the one that must
exist. This error is very common, when two tables are to be linked and some fields in the table with
the prospective foreign key already contain data. If the foreign key field contains an entry that is not
present in the parent table (the table containing the primary key), this is an invalid entry.
Chapter 3 Tables 49
If the linking is carried out successfully and subsequently there is an attempt to enter a similarly
invalid record into the table, you get the following error message:
Again this is an integrity violation. Base refuses to accept the value 1 for the field str_ID after the
link has been made because the Street table contains no such value in the ID field.
The properties of a link can be edited so that the deletion of a record from the Street table will
simultaneously set to NULL the corresponding entries in the Address table.
The properties shown in Figure 12 always relate to an action linked to the change in a record from
the table containing the corresponding primary key. In our case this is the Street table. If the
primary key of a record in this table is altered (Update), the following actions might take place.
No action
Changing the primary key Street.ID is not allowed in this case, as it would break the
relationship between the tables.
Update cascade
If the primary key Street.ID is changed, the foreign key is automatically changed to its new
value. This ensures that the linkage is not damaged. For example, if a value is changed from 3
to 4, all records from the Address table that contain the foreign key Address.Street_ID with the
value 3, have it changed to 4.
50 Base Handbook
Figure 13: Editing the properties of a relationship
Set null
All records which contain this particular primary key will now have no entry in the foreign key
field Address.Street_ID; the field will be NULL.
Set default
If the primary key Street_ID is changed, the value of Address.Street_ID originally linked to it is
set to the previously defined default value. For this purpose we need an unambiguous
definition of a default value. The LibreOffice Base GUI up to Version 3.5 does not seem to
provide this. If the default is set using the SQL statement:
ALTER TABLE "Address" ALTER COLUMN "Street_ID" SET DEFAULT 1;
the link definition ensures that the field will return to this value in the case of an Update. So if
the primary key in the Street table is changed, the corresponding foreign key in the Address
table will be set to 1. This is useful when a record is required to have a street field, in other
words this field cannot be NULL. But be careful! If 1 is not in use, you will have created a link to
a non-existent value. In this case HSQLDB seems to have been designed without due thought.
It is therefore possible to destroy the integrity of the relationship.
Attention If the default value in a foreign key field is not linked to a primary key of the foreign
table, a link to a value would be created, that isn't possible. The referential integrity
of the database would be destroyed.
It would be better not to use the possibility to set the value to default.
If a record is deleted from the Street table, the following options are available.
No Action
No action takes place. If the requested deletion affects a record in the Address table, the
request will be refused.
Chapter 3 Tables 51
Cascading Delete
If a record is deleted from the Street table and this affects a record in the Address table, that
record will also be deleted.
That might seem strange in this context but there are other table structures in which it makes a
lot of sense. Suppose you have a table of CDs and a table which stores the titles on these
CDs. Now if a record in the CD table is deleted, many titles in the other table have no meaning
as they are no longer available to you. In such cases, a cascading deletion makes sense. It
means that the user does not need to delete all these titles before deleting the CD from the
database.
Set to Null
This is the same as for the update option.
Set to Default
This is the same as for the update option and requires the same precautions.
To avoid error messages from the database as far as possible, since these may not
Tip always be comprehensible to the user, the No Action option should definitely be
avoided.
52 Base Handbook
When you reach the last field of a record, the cursor automatically jumps to the next record. The
previous entry is committed to storage. Additional storage using File > Save is not necessary and
indeed not possible. The data is already in the database.
Caution For the HSQLDB, data is in working memory. It will only be transferred to the hard
drive when Base is closed (unfortunately from the viewpoint of data security). If Base
for some reason does not close down in an orderly fashion, this can lead to loss of
data.
If no data is entered into a field that has been previously defined during table design as mandatory
(NOT NULL), the appropriate error message is displayed:
Attempt to insert null into a non-nullable column …
The corresponding column, the table and the SQL command (as translated by the GUI) are also
displayed.
Changing a record is easy: find the field, enter a different value, and leave the row again.
To delete a record, select the row by clicking its header (the grey area to the left), right-click and
choose Delete Rows.
The Sort, Search, and Filter functions are very useful for retrieving particular records.
Sorting tables
Chapter 3 Tables 53
The field name of the column and the current sort order are selected. If a previous quick sort has
been carried out, the first row will already contain the corresponding field name and sort order.
Searching tables
Functions for searching records are extensive and perhaps not the first choice for locating a
particular record for users accustomed to search engines.
Before you search, make sure the columns you will be searching are wide enough to
show correctly the records that you will find. The search window remains in the
Tip foreground and you will not be able to correct the settings for column width in the
underlying table. To reach the table, you must break off the search.
The search takes over terms from the field from which it was invoked.
To make the search effective, the search area should be limited as far as possible. It would be
pointless to search for the above text from the Title field in the Author field. Instead, the field name
Title is already suggested as the single Field name.
Further settings for the search can make things easier through specific combinations. You can use
the normal SQL placeholders ("_" for a variable character, "%" for an arbitrary number of variable
characters, "\" as an escape character, to enable these special characters themselves to be
searched for).
Regular expressions are described in detail in LibreOffice Help. Apart from that, the Help available
for this module is rather sparse.
54 Base Handbook
Figure 18: Entry mask for a Record search
The similarity search function is useful when you need to exclude spelling mistakes. The higher the
values that you set, the more records will be shown in the final list.
This search module is most suitable for people who know, from regular use, exactly how to achieve
a given result. Most users are more likely to succeed in finding records by using a filter.
Chapter 4 of this handbook describes the use of forms for searching, and how the use of SQL and
macros can accomplish a keyword search.
Chapter 3 Tables 55
Filtering tables
You can filter a table quickly by using the AutoFilter. Place the cursor in a field, and one click on
the icon causes the filter to take over the content of this field. Only those records are shown for
which the chosen field has the same content. The figure below shows filtering according to an
entry in the Pub_Year column.
The filter is active, as shown by the filter icon with a green check mark. The filter symbol is shown
pressed in. If the button is clicked again, the filter continues to exist, but all records are now shown.
So, if you want, you can always return to the filtered state.
Clicking on the Remove Filter/Sort icon at the extreme right causes all existing filters and sorts to
be removed. The filters become inactive and can no longer be recovered with their old values.
You can still enter records normally into a filtered table or one that has been
Tip restricted by a search. They remain visible in the table view until the table is updated
by pressing the Refresh button.
The Standard Filter icon opens a dialog inwhich you can filter using several simultaneous criteria,
similar to doing a sort. If AutoFilter is in use, the first line of the Standard Filter will already show
this existing filter criterion.
56 Base Handbook
The Standard Filter provides many of the functions of SQL data filtering. The following SQL
commands are available.
GUI Condition Description
= Exact equality; corresponds to like, but without any additional placeholders
<> Unequal
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
like For text, written in quotation marks ( ' '); "_" for a variable character, "%"
for an arbitrary number of variable characters
not like Opposite of like, in SQL NOT LIKE
empty No entry, not even a space character. In SQL this is expressed by the term
NULL
Not empty Opposite of empty, in SQL NOT NULL
Before one filter criterion can be combined with another, the following row must have at least one
field name selected. In Figure 20, the word – none – is shown instead of a field name, so the
combination is not active. The combination operators available are AND and OR.
The field name can be a new field name or a previously selected one.
Even for large data collections, the number of retrieved records can be reduced to a manageable
set with skillful filtering using these three possible conditions.
In the case of filtering forms too, there are some further possibilities (described in the following
chapter) which are not provided by the GUI.
Chapter 3 Tables 57
In the first table, as many new records are inserted into "Field_name", as are present in the column
"Other_fieldname" in the second table. Naturally a Select-Formula can be used here to limit the
number of entries.
58 Base Handbook
Problems with these data entry methods
Entry using a table alone takes no account of links to other tables. This is clear from an example of
a media loan.
The Loan table consists of foreign keys for the item being lent (Media_ID) and the corresponding
reader (Reader_ID) as well as a loan date (Loan_Date). In the table, therefore, we need to enter at
the time of the loan two numeric values (Media number and Reader number) and a date. The
primary key is automatically entered in the ID field. Whether the reader actually corresponds to the
number is not apparent unless a second table for the readers is open at the same time. Whether
the item was loaned out with the correct number is also not apparent. Here the loan must rely on
the label on the item or on another open table.
All this is much easier to accomplish using forms. Here the users and the media can be looked up
using list box controls. In forms, the names of user and item are visible and their numeric identifiers
are hidden. In addition, a form can be so designed that a user can be selected first, then a loan
date, and each set of media are assigned this one date by number. Elsewhere these numbers can
be made visible with the exactly corresponding media descriptions.
Direct entry into tables is useful only for databases with simple tables. As soon as you have
relationships between tables, a specially designed form is better. In forms, these relationships can
be better handled by using sub-forms or list fields.
Chapter 3 Tables 59
Chapter 4
Forms
Forms make data entry easier
Forms are used when direct entry into a table is inconvenient, to pick up errors in data entry
promptly, or when too many tables make direct management of data impossible.
Desktop
A Form in Base is a structure invisible Form
to the user. It serves within Base to
allow contact with the database. Control field 1
What is visible to the user is the set of Control field 2
Note
Controls, which serve for the entry or
display of text, numbers, and so on. Control field 3
These controls are divided by the GUI
into various types. Control field ...
Creating forms
The simplest way to create a form is to use the Form Wizard. Use of the Wizard to create a form is
described in Chapter 8, Getting Started with Base, in the Getting Started with LibreOffice guide.
That chapter also explains how you can further modify the form after using the Wizard.
This handbook describes the creation of a form without using the Wizard. It also describes the
properties of the various types of controls in a form.
A simple form
We start by using the task Create Form in Design View in the Forms area of the main Base
window.
This calls up the Form Editor and the Form Shown in Design View window appears (Figure 21).
The Form Controls toolbar is docked on the left side. The Form Design toolbar (Figure 22) is
docked at the bottom. If these toolbars do not appear automatically, use View > Toolbars to
display them. Without these toolbars, it is not possible to create a form.
The blank area shows a grid of dots. This grid helps you to position the controls accurately,
especially in relation to each other. The symbols at the right end of the Form Design toolbar show
that the grid is visible and active.
62 Base Handbook
Figure 21: Form shown in Design View
Chapter 4 Forms 63
Figure 22: Available buttons on the Form Design toolbar
In the Form Navigator (Figure 23), right-click on Forms to open a context menu. Choose New >
Form to create a new form. The other choices in the context menu (Open in Design Mode and
Automatic Control Focus) correspond to buttons in Figure 22; we will discuss them later.
The form carries the default name Form. You can change this name immediately or later. It has no
significance unless you need to access some part of the form using macros. The only thing you
need to ensure is that two elements with the same name do not occur on the same level in the
folder tree.
64 Base Handbook
The context menu of the form (shown below) provides the way to create form properties.
Chapter 4 Forms 65
When you select a form control, you automatically create a
form. For example, suppose you choose a text field: the cursor
changes shape and a rectangular shape may be drawn on the
white surface of the form. Then, on the stippled surface of the
form, a text field appears.
Now you can create the form by right-clicking and using the
context menu for the control (Figure 26).
Select the Form menu option (highlighted in the illustration) to
set properties for the form you have just created. The form has
the default name Form.
Form properties
When the form properties are called up using the context menu in the Form Navigator or the
context menu of a form control, a Form Properties window appears. It has three tabs: General,
Data and Events.
General tab
Here you can change the Name of the form. In addition there are design possibilities that have
no significance inside Base. They show only the more general possibilities for design using a
form editor; when you create a Web form you will need to use them.
66 Base Handbook
Data tab
For creating internal forms in Base, this is the most important tab. Here you can set the
following initial properties for the form:
Content type: Choose between Table, Query and SQL command. While Table can always be
used for data entry into a form, this is not always the case for Query (for more information, see
Chapter 5, Queries, in this book) or direct entry of a SQL command. Here we are dealing with a
query that is not visible in Base's query container but has in principle the same structure.
Content: According to whether Table or Query was chosen above, all available tables and
queries are listed. If a SQL command is to be created, you can invoke the Query Editor by
using the button with the three dots to the right of the Content field.
Analyze SQL command: If the analysis of SQL commands should not be permitted (because,
for example, you are using code that the GUI cannot show correctly), you should choose No
here. However this will prevent the form accessing the underlying data using a filter or a sort.
Filter: Here you can set a filter. To get help with this, click the button to the right of the field. See
also Chapter 3, Tables, in this book.
Sort: Here you can set up a Sort for your data. To get help, click the button to the right of the
field. See also Chapter 3, Tables.
Allow additions: Should the entry of new data be allowed? By default this is set to Yes.
Allow modifications: Should editing of the data be allowed? By default also Yes.
Allow deletions: The deletion of data is also allowed by default.
Add data only: If you choose this option, an empty form will always be displayed. There will be
no access to existing data, which can neither be edited nor viewed.
Navigation bar: The appearance of the Navigation Bar at the bottom of the screen can be
switched on or off. There is also a possibility, when you have a subform, always to show the
Navigation Bar for the main form, so that activation of this toolbar affects the main form only.
This setting for the Navigation Bar is not relevant to the internal navigation toolbar that can be
added as a form control if required.
Cycle: The Default option for Base databases is that after entry into the last field in a form, the
Tab key takes you to the first field of the next record – that is, a new record will be created. For
Chapter 4 Forms 67
databases, this has the same effect as All records. By contrast, if you choose Active record, the
cursor will move only within the record; when it reaches the last field, it will jump back to the
first field in that record. Current page refers particularly to HTML Forms. The cursor jumps from
the end of a form to the next form on that page further down.
Events tab
Events can trigger macros. A click on the button on the right (…) allows macros to be linked to
the event.
Reset: The form is emptied of all new entries that have not yet been saved.
Before submitting: Before the form data are sent. This is only meaningful for Web forms.
When loading: Only when opening the form. Not when loading a new record into the form.
Reloading: This takes place when the content of the form is refreshed, for example by using a
button on the Navigation Bar.
Unloading: This option seems not to function. It would be expected to refer to the closing of the
form.
Record action: This includes, for example, storage using a button. In tests, this action regularly
duplicates itself; macros run twice in succession.
Record change: The opening of a form counts as a record change. Whenever one record
changes to another within the form, this action likewise occurs twice. Macros are therefore run
twice in succession.
Fill parameters: This macro will be run if a parameter query is to be invoked in a subform, but
for some reason the parameter is not correctly transmitted from the main form. If this event is
not caught, a parameter query will follow the loading of the form.
Error occurred: This event could not be reconstructed.
68 Base Handbook
Properties of controls
Once a form has been created, it can be filled with visible controls. Some controls allow the content
of the database to be displayed, or data to be entered into the database. Other controls are used
exclusively for navigation, for searching, and for carrying out commands (interaction). Some
controls serve for additional graphical reworking of the form.
Chapter 4 Forms 69
Default settings for many controls
As with forms, properties are grouped into three categories: General, Data and Events. General
comprises everything that is visible to the user. The data category specifies the binding to a field in
the database. The Events category controls actions, which can be bound to some macro. In a
database without macros, this category plays no role.
General tab
70 Base Handbook
Non-enabled fields cannot be used
and are grayed out. Useful for
control using macros. (Example: If
Field 1 contains a value, Field 2
must not contain one; Field 2 is
deactivated.)
Chapter 4 Forms 71
Background color of the text field.
72 Base Handbook
Data tab
Data field: Here you create the binding with the table on which the form is based.
Empty string is NULL: Whether an empty string should be treated as (NULL) or the content
simply deleted.
Entry required: This condition should match the one in the table. The GUI will prompt for entry if
the user has not entered a value.
Filter proposal: When the data is to be filtered, the content of this field is temporarily stored as
a suggestion. Caution – with large contents, this choice can use a lot of storage.
Events tab
Changed: This event takes place when a control is modified and afterwards loses the focus.
Text modified: Refers to the content, which can in fact be text, numeric, or whatever. Occurs
after each additional character is entered.
Chapter 4 Forms 73
When receiving focus: The cursor enters the field. Under no circumstances must the macro
create a message dialog on the screen; clicking in such a dialog causes the form field to lose
the focus and then recover it, triggering the macro again. A loop is created which can only be
broken by using the keyboard.
When losing focus: The cursor leaves the field. This can lead to the same kind of interplay
when the handling of the event causes it to recur.
Key: Refers to the keyboard. For example, a key is pressed when you move through the form
using the Tab key. This causes a field to receive the focus. Then the key is released.
Mouse: Self-explanatory; These events only takes place if the mouse is or was already within
the field ("outside" corresponds to the javascript onMouseOut).
Reset: The form is emptied of all data. This happens, for example, when starting a new record.
When a form is first loaded, the two events Prior to reset and After resetting occur in
succession, before the form is available for input.
Updating: If the event is bound to a form control, update takes place when the focus is lost and
jumps to another form control, after altering the content of the field. Changes in the form are
accepted and displayed. When a form is closed, the two events Before updating and After
updating occur in succession.
Text field
As well as the properties set out on page 70, text fields can have the following additional
properties:
General tab
74 Base Handbook
Active only for single-line fields.
Changes characters to see only
points.
Data tab
Nothing of significance.
Events tab
Nothing of significance.
Numeric field
In addition to properties already described, the following properties exist:
General tab
Maximum value.
Data tab
There is no check on whether a field can be NULL. If there is no entry, the field will be NULL
and not 0.
No filter proposal is offered.
Events tab
The "Changed" event is absent. Changes must be handled using the "Text modified" event (the
word text is not to be taken literally here).
Date field
As well as the properties described on page 70, the following are to be noted.
General tab
Chapter 4 Forms 75
Maximum value.
Data tab
There is no check on whether a field can be NULL. If there is no entry, the field will be NULL
and not 0.
No filter proposal is offered.
Events tab
The "Changed" event is absent. Changes must be handled using the "Text modified" event (the
word text is not to be taken literally here).
Time field
As well as the properties listed on page 70, the following features are available.
General tab
Data tab
There is no check on whether a field can be NULL. If there is no entry, the field will be NULL
and not 0.
No filter proposal is offered.
Events tab
The "Changed" event is absent. Changes must be handled using the "Text modified" event (the
word text is not to be taken literally here).
76 Base Handbook
Currency field
In addition to the properties already listed on page 70, the following features are available:
General tab
Min. value, Max. value, Increment, Default value, Decimal places, and Thousands separator.
correspond to the general properties listed on page 75. In addition to these, there is only:
The symbol is displayed but not
stored in the table that underlies the
form.
Data tab
There is no check on whether a field can be NULL. If there is no entry, the field will be NULL
and not 0.
No filter proposal is offered.
Events tab
The "Changed" event is absent. Changes must be handled using the "Text modified" event (the
word text is not to be taken literally here).
Formatted field
In addition to the properties listed on page 70, the following features are offered:
General tab
Minimum and maximum values, and the default value, depend on the formatting. Behind the
button for Formating is a flexible field that makes most currency and numeric fields
unnecessary. Unlike a simple currency field, a pattern field can show negative sums in red.
The button to the right with the three
dots provides a choice of numeric
formats, as you usually do in Calc.
Among the numeric formats can be seen, alongside Date, Time, Currency or normal numeric
format, possibilities for using fields with a measurement unit such as kg (see Figure 27). See
also the general Help on numeric format codes.
Data tab
Nothing special to report.
Events tab
The "Changed" event is absent. Changes must be handled using the "Text modified" event (the
word text is not to be taken literally here).
Chapter 4 Forms 77
Figure 27: Formatted field with general numeric options
List box
When a list box is created, the List Box Wizard appears by default. This automatic appearance can
be switched off if required using the Wizards On/Off button (shown in Figure 24).
Wizard
78 Base Handbook
The form is already defined. It is bound to a Table named Loans. A list box shows the user
different data from what is actually transmitted into the table. This data usually comes from
another table in the database, and not from the table to which the form is bound.
The Loans table is supposed to show which Reader has borrowed which Media. However this
table does not store the name of the reader but the corresponding primary key from the Reader
table. It is therefore the Reader table that forms the basis for the list box.
The Surname field from the Reader table should be visible in the list box. This serves as the
Display field.
The Reader_ID field occurs in the Loan table which underlies the form. This table is described
here as the Value table. The primary key ID from the Reader table must be bound to this field.
The Reader table is described here as the List table.
The list box has now been created complete with data and default configuration and is fully
functional.
In addition to the properties listed on page 70, the following features are available.
Chapter 4 Forms 79
General tab
Data tab
In addition to the usual data properties Data field and Input required, there are significant
properties which affect the binding between the displayed data and the data to be entered into
the table that underlies the form.
Type of list contents: Valuelist | Table | Query | SQL | SQL [Native] | Tablefields
List contents Valuelist: If list entries have been created under General, the corresponding
values to be stored are entered here. The list contents are loaded with individual items
separated by Shift – Enter. The List content field then shows them as
"Value1";"Value2";"Value3" … The Bound Field property is inactive.
80 Base Handbook
List contents Table: Here one of the database tables can be selected. However this is seldom
possible as it requires the content of the table to be so structured that the first table field
contains the values to be displayed in the list field, and one of the following fields contains the
primary key which the table underlying the form uses as a foreign key. The position of this field
within the table is specified in Bound Field, where the Numbering begins with 0 for the first
field of the database table. But this 0 is reserved for the displayed value, in the above
example the Surname, while the 1 refers to the ID field.
List contents Query: Here a query is first created separately and stored. The creation of such
queries is described in Chapter 5, Queries. Using the query, it is possible to move the ID field
from the first position in the underlying table to the second position, here represented by the
bound field 1.
List contents SQL: The List Box Wizard fills this field. The query constructed by the Wizard
looks like this:
The query is the simplest possible.
The Surname field occurs at
position 0, the ID field at position 1.
Both are read from the Reader
table. As the bound field is Field 1, this SQL formula works. Here should be added ORDER BY
"LastName" ASC. So you haven't to scroll to long through the list to find somebody. An
additional problem might be, that LastName could be the same for more than one reader. So
FirstName must be added in the view of the list box. When there are readers with the same
LastName and the same FirstName, the primary key ID must also be shown. See Chapter 5,
Queries, for information on how this works.
List contents SQL [Native]: The SQL formula is entered directly, not using the Wizard. Base
does not evaluate the query. This is suitable when the query contains functions that might
perhaps not be understood by the Base GUI. In this case the query is not checked for errors.
More about direct SQL Mode can be found in Chapter 5, Queries.
List contents tablefields: Here Field names from a table are listed, not their content. For the
Reader table, the List contents would be "ID", "Given name", "Surname", "Lock", "Gender_ID".
Events tab
In addition to the standard events, the following events are available:
Execute action: If a value is chosen by the keyboard or the mouse, the list box executes this
action.
Item status changed: This could be the change of the displayed content of a list box through
the use of the drop-down button. It could also be a click on the drop-down button of the field.
Error occurred: Unfortunately, this event cannot be reconstructed for list boxes.
Chapter 4 Forms 81
Combo box
As soon as a combo box is created, a Wizard appears by default, just as with a list box. This
automatic behavior can be switched off if necessary using the Wizards On/Off button (see
Figure 24).
Combo boxes write the selected text directly into the table underlying the form. Therefore the
following example shows both the table linked to the form and the one selected for the control as
the Reader table.
Wizard
Again the form is predefined, this time with the Reader table. As the data to be displayed in the combo
box is also to be stored in this table, the source selected for the data for the list is likewise the Reader
table.
In the Reader table the FirstName field occurs. This should be displayed in the combo box.
82 Base Handbook
In a database, there seems to be little point in not storing the value of a combo box within a field.
We want to read given names from the Reader table, and also to make them available for new
readers, so that new records do not need to be created for a given name that already exists in the
database. The combo box shows the first name, and text input is not necessary.
If a new value does need to be entered, this can be done easily in a combo box, as the box shows
exactly what is going into the underlying table for the form.
In addition to the properties shown on page 70 and described for list boxes, the following features
are available.
General tab
During entry of new values, a list of
matching values (if any) is displayed
for possible selection.
Data tab
The data fields conform to the existing default settings and the settings for a list box. The SQL
command however shows a special feature:
SELECT DISTINCT "FirstName" FROM "Reader"
Adding the DISTINCT keyword ensures that duplicate given names are shown only once.
However, creation using the Wizard once more makes it impossible for the content to be
sorted.
Events tab
The events correspond to those for a list box.
Chapter 4 Forms 83
Check box
The check box appears immediately as a combination of a check box field and a label for the box.
In addition to the properties described on page 70, the following features are available.
General tab
Data tab
84 Base Handbook
The check box can be given a reference value. However only the values of 1 (for On) or 0 (for
Off) can be transferred to the underlying data field (check boxes act as fields for the choice of
Yes and No).
Events tab
The fields "Changed", "Text modified". "Before updating" and "After updating" are all absent.
Additional fields for a check box are "Execute action" (see List box) und "Item status changed"
(corresponds to "Changed").
Option button
The option button is similar to the check box described above, except for its general properties and
its external (round) form.
When several option buttons in the form are linked to the same table field, only one of the options
can be selected.
General tab
The option button is designed to be
used in groups. One of several
options can then be selected. That is
why a Group name appears here,
under which the options can be
addressed.
Data tab
See under Check box. Here, however, reference values that are entered are actually
transferred to the data field.
Events tab
See under Check box.
Image control
A image control handles the entry and display of graphical material in the database. The underlying
data field must be a binary field.
Entry into a image control takes place either by a double-click with the mouse to open a file
selection dialog, or a right-click to choose whether an existing graphic is to be deleted or replaced.
A graphical control by default has no Tab stop.
In addition to the properties described on page 70, the following features are available.
General tab
Chapter 4 Forms 85
No: The image will not be fitted to
the field. If it is too big, the field will
show a window into the image. The
image is not distorted.
Keep ratio: The image is fitted to the
control but not distorted (aspect ratio
preserved).
Autom. Size: The image is fitted to
the control and may be shown in a
distorted form.
Data tab
Nothing further to report.
Events tab
The events "Changed", "Text modified", "Before updating" and "After updating" are missing..
Pattern field
An input mask is used to control input into the field. Characters are pre-specified for particular
positions, determining the properties of entered characters. The preset characters are stored along
with the entered ones.
In addition to the properties described on page 70, the following features are available.
General tab
This determines what characters can
be entered.
86 Base Handbook
So, for example, you can define the literal mask as "__/__/2012" and the edit mask as
"NNLNNLLLLL", to allow the user to enter four characters only for a date.
Data tab
Nothing further to report.
Events tab
The "Changed" event is absent.
Table control
This is the most comprehensive control. It provides a table, which can then be provided with
controls for individual columns. This not only allows the actual data to be viewed during input, but
also the previously entered data, without the need to use the Navigation bar to scroll through the
records.
Not every field that is possible in a form can be selected for a table control field. Push buttons,
image buttons and option buttons are not available.
The Table Control Wizard assembles in a window the fields that will appear afterwards in the table.
In the control the Loans table is available for editing. In addition to the ID (primary key) field and
the Media_ID_BC field (entry of media using a bar-code scanner), all fields are to be used in the
control.
The previously created table control must now be further developed, to allow entry into the Loans
table. For fields such as Reader_ID or Media_ID, it would be more useful to be able to choose the
reader or the media directly, rather than a number representing the reader or media. For this
purpose, controls such as list boxes can be placed within the table control. This is declared later.
The formatting of the Extension field with two decimal places was certainly not intended.
Chapter 4 Forms 87
Figure 28: Output of the Table Control Wizard
In addition to the properties listed on page 70, the following features are available.
General tab
Height of individual lines. With no
value here, the height is
automatically adjusted to the font
size. Multi-line text fields are then
shown as single lines to be scrolled.
Data tab
Since this is a field that contains no data itself but manages other fields, there are no data
properties.
Events tab
The "Changed" and "Text modified" events are missing. The "Error occurred" event is added.
Label field
In addition to the properties described on page 70, the following features are available.
General tab
By default a label is not wrapped. If it
is too long for the field, it is
truncated. Caution: word wrapping
does not recognize spaces, so if the
field is too small, a break can occur
within a word.
Data tab
None.
88 Base Handbook
Events tab
The label field reacts only to events that are connected with the mouse, a key or the focus.
Group box
A group box graphically groups several controls and provides them with a collective label.
If a group box is created with Wizards active, the Wizard proceeds from the assumption that
several option buttons will occur together within this frame.
This form is based on the Reader table. We are dealing with the choice of gender. The entries are
the labels of the option buttons.
Here the default option is "female". If there is to be no default field, the default entry in the
underlying table is NULL.
Chapter 4 Forms 89
The Wizard gives the option buttons separate values by default, here 1 for female and 2 for male.
These values correspond to the examples of primary key fields in the Gender table.
The value selected by clicking an option button is transferred to the Gender_ID field of the form’s
underlying table Readers. In this way the Readers table is provided with the corresponding foreign
key from the Gender table by using the option button.
The option button group is given a group box (frame) with the label Gender.
If female is selected in the active form, male is deselected. This is a characteristic of option buttons
that are bound to the same field in the underlying table. In the example shown above, the option
buttons replace a two-element list box.
In addition to the properties described on page 70, the following features are available.
90 Base Handbook
General tab
The label can be changed from its default value. At present the frame properties (Line
thickness, line color) cannot be changed but you can change the font formatting.
Data tab
None, since this control serves only for visual grouping of fields.
Events rab
The group box reacts to events involving the mouse, a key, or the focus.
Push button
In addition to the properties described on page 70, the following features are available.
General tab
Label on the button.
Chapter 4 Forms 91
Should a graphic appear on the
button?
Data tab
None. A button only carries out actions.
Events tab
"Approve action", "Execute action" and "Item status changed".
Image button
In addition to the properties already described on page 70, the following features are available.
General tab
Similar to a normal button. However this button has no text and the button itself is not visible.
You see only a frame around the graphic.
By default, an image button has no tab stop.
Caution: at the time of writing, hardly any actions work with this button. It is practically only
usable with macros.
Data tab
None; this control only carries out actions.
Events tab
"Approve action" and all events involving the mouse, a key, or the focus.
Navigation bar
The standard Form Navigation bar is inserted into forms at the lower edge of the screen. The
insertion of this toolbar can cause a brief rightward shift of the form as it builds up on the screen.
This can be distracting in cases where the navigation bar is switched off again for some parts of
the visible form, for example when there are subforms or more than one form in the visible form.
By contrast, a navigation bar control that is part of the form, separate from the corresponding
items, makes it clear through which items you navigate with the toolbar. The form for Loans, for
example, needs to search first through the readers and then show the media loaded to the reader.
The navigation bar control is positioned near the reader, so the user notices that the navigation bar
is used for the reader and not for the media loaned to the reader.
The standard Form Navigation bar makes available the buttons shown in Figure 30. The navigation
bar control shows the same buttons except those for Find Record, Form-Based Filters and Data
source as Table.
92 Base Handbook
Figure 30: Navigation buttons
In addition to the properties listed on page 70, the following features are available for the Navigator
Bar control.
General tab
The icon size is adjustable. In
addition you can choose which
groups are displayed. These are
shown in Figure 29 from left to
right using a vertical line as a
group separator: Positioning,
Navigation, Acting on a record,
and groups of commands for
Filtering and Sorting.
Data tab
None, as this control only carries out actions.
Events tab
All events that involve the Mouse, a key, or the focus.
Chapter 4 Forms 93
Independent of this form control, the insertable navigation bar naturally continues to exist with
the same items as the above figure.
This insertable navigation bar provides additionally the general record search, the form-based filter
and the display of the form's underlying data source in table view above the form.
If you are working not just with a form but with subforms and ancillary forms, you must be careful
that this insertable navigation bar does not disappear as you switch forms. That creates a
disturbing effect on the screen.
Multiple selection
If you use the Select icon (Figure 24) to select a large region or several elements of a form, the
following modifications may be carried out (see Figure 31).
94 Base Handbook
A simple form completed
A simple form has form controls for writing or reading records from a single table or query. Its
construction is shown by the following example.
Desktop
Form
Control field 1
Control field 2
Control field 3
The example of a simple form for library loans is shown here using several variants. The quick way
to use the Form Wizard is described in Chapter 8, Getting Started with Base, in the Getting Started
with LibreOffice guide. Here we describe the creation in Design View.
The heading for the form was created using a label field. The font was changed. The label field is
anchored to a paragraph in the top left corner of the document. Using the context menu of the label
field, a form was created that was linked to the Loans table (see “Form properties” on page 66).
The page has also been given a uniformly colored background.
This function, available on the Formula Design toolbar (see Figure 22), allows all fields of the
underlying table to be selected.
Chapter 4 Forms 95
Double-click on the fields to insert them into the form as a group with labels (unfortunately all on
the same spot). The group needs to be separated out so that the form eventually looks like the
following illustration. For a better view, all unnecessary toolbars have been removed from the
window, which has also been compressed so that not all elements of the Navigation bar are visible.
All fields have been selected except Media_ID_BC, which is designed to be used only with a
barcode scanner.
For each table field, an appropriate form control has been automatically selected. Numbers are in
numeric fields and are declared as integers without decimal places. Date fields are represented
correctly as date controls. All fields have been given the same width. If a graphical control had
been included, it would have been given a square field.
96 Base Handbook
Figure 33: Form controls: editing the group
The Form Navigator displays all the elements of the form with their labels. For controls, the names
are taken directly from the names of the fields in the underlying table. The names of the labels
have the suffix Label.
A click on Media_ID selects this field (Figure 34). Right-click to replace the selected field with a
different type of field, using the context menu (Figure 35).
Figure 34: Selecting form controls directly using the Form Navigator
Chapter 4 Forms 97
Figure 35: Replacing one kind of control by another
using the Form Navigator
This replacement is carried out for the Media_ID and Reader_ID controls.
The change is made visible in the Form Navigator by the change in the accompanying icon.
98 Base Handbook
The SQL query for the list field can now be created through the graphical user interface by clicking
on the button at the right. This is carried out automatically when a list box is created directly, but
not when it is formed by conversion from another type of control. For the SQL command, see
Chapter 5, Queries.
Since the list boxes are to be made drop-down, the following defects can be corrected at the same
time:
• The labels for the list boxes should be Media instead of Media_ID and Reader instead of
Reader_ID.
• The ID control should be declared as read-only.
• Any fields which are not absolutely necessary for issuing loans for a new medium do not
need a tab stop. Without it, the form can be traversed much faster. If necessary, the tab
stop can also be adjusted using the activation sequence (see page 70). Only the Media,
Reader and Loan date fields must be accessible in all cases using the Tab key.
• If the form is intended for carrying out loans, it is unnecessary and also confusing for
returned media to be displayed. Media with a return date should be filtered out. In addition,
the display order could be sorted by Reader, so that media on loan to the same person are
displayed successively. See the note on “Form properties” on page 66. However there is a
problem here in that readers can be sorted only by ID, not alphabetically, because the table
underlying the form only contains the ID.
Chapter 4 Forms 99
Table control
The use of the Table Wizard to create a table control has already been described on page 87. It
has however some defects which need to be improved:
• The Media_ID and Reader_ID fields must become list boxes.
• Numeric fields must be stripped of their decimal places, since the Wizard always specifies
two decimal places for numbers.
Changing fields within the table control is not possible using the same method as described for
other controls. In the Navigator, the description of fields ends with the table control. The Navigator
knows nothing about the controls that lie within the table control, referring to fields in the underlying
table. This equally applies later, when attempts are made to access the fields using macros. They
cannot be accessed by name.
The controls within the table control are called columns. Using the context menu, it is now possible
to replace one type of field by another. However the whole range of types is not available. There
are no push buttons, option boxes, or graphical controls.
The properties of the fields are hidden in the context menu behind the concept of columns. Here,
for example, the numeric field Extension can be changed so that no decimal places are shown.
You can move through a form using either the mouse or the Tab key. If you tab into a
table control, the cursor will move one field to the right for each additional tab; at the
Tip end of the line, it will move back to the first field of the next record in the table
control. To exit the table control, use Ctrl+Tab.
The order of the columns can be changed by dragging the column header:
If this is done in form design view, it is permanent. A temporary change in order can be carried out
during data entry by using the same method.
If only certain fields should be visible during use, you can use several different table controls in the
form, as the Tab is captured by default by each table control.
The form shown in Figure 36 is for the loan of media. Only the fields immediately necessary are
shown in the upper table control. The lower one shows all the fields, so that it is apparent which
person and medium the return is for.
The filtering is carried out using the button with the three dots, which opens the dialog shown
below. You can also enter the filter directly into the Filter text field if you know the SQL coding.
Using the GUI, you can now select the field named Return_Date. It will show only the records for
which the field is empty, where “empty” stands for the SQL designation NULL.
The cleaned-up form (shown in Figure 37) now looks rather simpler.
Of course there is still room for improvement, but compared with the earlier form, this version has
a clear advantage in that all the media are visible at a glance.
The processing of data using table controls is similar to using an actual table. A right-click on the
record header of an existing record causes it to be deleted, and an entry can be canceled or saved
in the case of new records.
When you leave a line, the record is automatically saved.
Desktop
Form Subform
Control field 1 Control field 1
Here the main form is linked to the Reader table. To speed up the search for readers, the table is
sorted alphabetically. We will do without a navigation bar, since the content of the subform would
come between the main form and the navigation bar. Instead we will use the built-in form control
(Figure 29).
Right-click on the main form in the Form Navigator to use the context menu to create a new form.
Once again this form has the default name of Form, but it is now an element in the subfolder of the
main form.
The Loans table is chosen for the subform. For the filter we specify that the Return date field
should be empty ("Return_Date" IS NULL). This prevents any media that have already been
returned from appearing. The records should be sorted by loan date. The ascending sort shows
the medium on loan for the longest period at the top.
Link master fields and Link slave fields are used to create a linkage to the main form, in which the
subform lies. The button with three dots shows once again that a helpful dialog is available for
creating these.
Under Loans, the fields in the Loans table are shown, under Readers those of the Reader table.
The Reader_ID from Loans should be set as equivalent to the ID from the Reader table.
Although this linkage has already been created in the database using Tools > Relationships (see
Chapter 3, Tables), the function that lies behind the Suggest button in this dialog does not
reference this and would suggest that the first foreign key in the Loan table, namely Media_ID,
The chosen link between the table for the subform and the table for the main form is now specified
in terms of fields from the tables.
To create a table control for the main form, we must now select the main form in the Form
Navigator. Then, if the Table Control Wizard is enabled, it will show the fields available in the main
form. We deal with the subform in a similar way.
Once the table controls have been set up, we need to carry out the modifications already
discussed when creating the simpler form:
• Replacing the numeric field Media_ID in the subform with a list box.
• Renaming the Media_ID field Media.
• Modifying the numeric fields to a format without decimal places.
• Limiting the minimum and maximum values.
• Renaming other fields, to save space or to add non-ASCII characters which should not be
used in field names in database tables.
Sort and filter functions are supplemented for the main form by adding a navigation bar. The other
fields on the navigation bar are not needed, as they are mostly available from the table control
(record display, record navigation) or else carried out by movement through the table control (data
storage).
The final form might look like the figure below.
The table is given a primary key with the value 0. This record will be repeatedly read and rewritten
by the main form.
This main form is linked to the subform in such a way that the value of the Integer field in the Filter
table is the same as the value of the Reader_ID field in the Loan Table. The subform’s properties
are unchanged from the version shown above.
Before we create a list box in the main form, we must switch off the wizards. The list box Wizard
only allows you to create a box that shows the content of a single field; it would be impossible to
have surname and given name and an additional number in the display area of a list box. As in the
simpler form, we now enter for the list box contents Surname, Given name – ID Nr. The list box
transmits the ID to the underlying table.
The main form consists only of the heading and the list box; the subform contains another heading,
the table control from the previous version and the button.
The form now functions better in that:
• No reader can now be edited, altered or deleted, and
• Readers can be found more quickly by typing into the control than by using a filter.
For a greater degree of functionality (returns without alteration of previous data) a second subform
must be created, linked to the same Loans table. To ensure the functionality of the list box in Figure
39, both subforms must be placed one level further down, as subforms of a subform. Data is
updated hierarchically from the main form down through the subforms. The button in the previously
described form must now be placed in the first subform and not in the two subforms that come
under it.
Here the Form Navigator is used to show the different levels. In the main form we have the text
field for the form title and the list box for finding the reader. The list box appears at the bottom of
the form, as it is declared after the subform. Unfortunately this display sequence cannot be altered.
The subform has only one button, for updating its contents and at the same time saving the main
Basically the names of forms and controls are without significance. However if these
names are to be accessed by macros, they must be distinguishable. You cannot
distinguish identical names at the same level.
Note
Naturally it makes sense, when creating larger form structures to have meaningful
names for forms and their controls. Otherwise finding the right field could quickly
become problematic.
The main form and the subform use the same table. In the subform, no data are entered. That is
why all the fields for this form are set to No. The main form and the subform are linked through the
field, whose value is to be transmitted to the sub-subforms: the Integer field in the Filter table.
In the first sub-subform, no existing data are displayed; it is used only for creating new data. For
this, the suggested filter is adequate. Only records matching the Reader_ID and with an empty
loan date field ("Loan_Date" IS NULL) will be displayed. In practice, this means an empty table
control. As the table control is not continuously updated, newly loaned media will remain within it
until the OK update button is used either to select a new name or to transfer the data into the
second sub-subform.
In the main form, an additional date field appears, along with a label referring to its content. The
value from the date field is stored in the Filter table and transferred by the linkages from subform to
sub-subform.
The linkage between the two forms now refers to two fields. The Integer field is bound to the
Reader_ID field of the sub-subform. The Date field is bound to the Loan_Date field. This ensures
that the Loan_Date is automatically transferred from the Filter table to the Loans table when the
loan is made.
Figure 41: The date of the loan is entered only once. When the Reader changes, it
must be reentered.
The date field is now removed from the table control, so that the latter contains only one search
field. This would be the ideal requirement for speeding up even more the work of the library. For in
fact each medium will have a printed accession number, so why does that have to be searched?
n n n
Mainform
1 1
n n
Subform Subform
Using list boxes, the main form based on the Media table can be assigned values from the
Category, Town or Publisher tables. Subforms are used to link the rel_Media_Author and Subtitle
tables with the main form and through it with the Media table.
The subform for the rel_Media_Author table again consists of two list boxes so that the foreign
keys from the Authors and Author_Add_ID (additions might be for example editor, photographer,
and so on) do not have to be entered directly as numbers.
For the media entry form, the list boxes usually have to be filled up gradually during the entry
process. For this purpose, further forms are built in alongside the main form. They exist
independently of the main form.
Control field 2
Form 2
Control field 1
Control field 2
On the left side is the main form with a view to searching and entry of new media. On the right side
of the form is a group box with the label Edit list box contents, providing a separate area intended
for filling up the list boxes in the main form. If the database has not existed for long, it will often be
necessary to make entries into these fields. However, the more entries that are available for the list
boxes of the main form, the less often will access to the table controls in the group box be
necessary.
Here in each case the complete data for a table are entered. In the early stages, it is often
necessary to have recourse to these side forms, since not many authors are yet stored in the
corresponding table.
When a new record is stored in one of the table controls, it is necessary to find the corresponding
list box in the main form and use the Update control (see Navigation bar) to read in the new values.
The Form Navigator shows a correspondingly large list of forms.
The field for the search term lies in the Filter form, the two table controls (for the author and the
subtitle) lie in the subform of the Media Entry main form.
In the Form Navigator, this form looks much more complex, as all the controls and labels appear
there. In the previous form, most of the fields were actually columns within the table controls and
were thus invisible to the Form Navigator.
Unfortunately the sequence within the Form Navigator cannot easily be changed. So, for example,
it would seem more sensible to place the subforms Subtitle and Author as branches of MainForm
right at the beginning. But within the Form Navigator, individual controls and subforms are simply
shown in the order in which they were created.
The activation sequence for a particular form is invoked, when an element of the form is selected
and then the Activation sequence button is clicked. For a simple form, it is not necessary to do
things in this order, but where there are many parallel forms, the function needs to know which
The activation sequence allows all the elements that transmit data to the underlying table of the
form or can carry out actions, to be put in order. This corresponds to setting the activation
sequence in the control properties listed on page 70.
Note that in the activation sequence, some controls appear for which the tab stop is actually
switched off. They are included in the list, but are not in fact accessed through the keyboard when
working with the form.
Fields can be automatically sorted in the order in which they appear on the form background. The
higher up a field lies, the earlier it comes in the sequence when you use Automatic Sort. For fields
at the same height, the leftmost field comes first. This sorting functions without error only when the
elements were exactly positioned using the grid when the form was created. Otherwise you will
need to adjust them. Simply select a control and use Move Up or Move Down to move it higher or
lower in the sequence.
If there is a subform, Automatic Sort jumps directly into the subform after completing the main
form. In the case of a table control, this causes the cursor during keyboard input to be trapped
within this subform; you can only free it by using the mouse or by pressing Ctrl+Tab.
The Automatic Sort functions only once for a table control. A subsequent subform with a table
control will not be included. Parallel forms are not taken into account either. An Automatic Sort
cannot be made retrospectively for a subform with a table control. The subform must be completely
removed (temporarily moved to another form).
The data substrate for the form for media entry is in this case not a table but a query. This is
necessary as the form is to be used not just for entering records but also for searching. The form
also contains a text field which shows, after saving, whether the ISBN number entered was correct.
This too is only possible using a comprehensive query. To understand the background of this, it is
therefore necessary to discuss the fundamentals of queries, covered in Chapter 5.
Entering queries
Queries can be entered both in the GUI and directly as SQL code. In both cases a window opens,
where you can create a query and also correct it if necessary.
From the tables available, select the Loan table. This window allows multiple tables (and also
views and queries) to be combined. To select a table, click its name and then click the Add button.
Or, double-click the table’s name. Either method adds the table to the graphical area of the Query
Design dialog.
When all necessary tables have been selected, click the Close button. Additional tables and
queries can be added later if required. However no query can be created without at least one table,
so a selection must be made at the beginning.
The selected field designation Loan.* has a special meaning. Here one click allows you to add all
fields from the underlying table to the query. When you use this field designation with the wildcard
* for all fields, the query becomes indistinguishable from the table.
In the above test, special attention should be paid to the first column of the query result. The active
record marker (green arrow) always appears on the left side of the table, here pointing to the first
record as the active record. While the first field of the first record in Figure 43 is highlighted, the
corresponding field in Figure 44 shows only a dashed border. The highlight indicates that this field
can be modified. The records, in other words, are editable. The dashed border indicates that this
field cannot be modified. Figure 43 also contains an extra line for the entry of a new record, with
the ID field already marked as <AutoField>. This also shows that new entries are possible.
A basic rule is that no new entries are possible if the primary key in the queried
Tip table is not included in the query.
The Loan_Date and Return_Date fields are given aliases. This does not cause them to be
renamed but only to appear under these names for the user of the query.
The table view above shows how the aliases replace the actual field names.
The Return_Date field is given not just an alias but also a search criterion, which will cause only
those records to be displayed for which the Return_Date field is empty. (Enter IS EMPTY in the
Criterion row of the Return_Date field.) This exclusion criterion will cause only those records to be
displayed that relate to media that have not yet been returned from loan.
Here the SQL formula created by our previous choices is revealed. To make it easier to read, some
line breaks have been included. Unfortunately the editor does not store these line breaks, so when
the query is called up again, it will appear as a single continuous line breaking at the window edge.
SELECT begins the selection criteria. AS specifies the field aliases to be used. FROM shows the
table which is to be used as the source of the query. WHERE gives the conditions for the query,
namely that the Return_date field is to be empty (IS NULL). ORDER BY defines the sort criteria,
namely ascending order (ASC – ascending) for the two fields Reader_ID and Loan date. This sort
specification illustrates how the alias for the Loan_Date field can be used within the query itself.
When working in Design View Mode, use IS EMPTY to require a field be empty.
When working in SQL Mode, use IS NULL which is what SQL (Structured Query
Tip Language) requires.
When you want to sort by descending order using SQL, use DESC instead of ASC.
So far the Media_ID and Reader_ID fields are only visible as numeric fields. The readers’ names
are unclear. To show these in a query, the Reader table must be included. For this purpose we
return to Design Mode. Then a new table can be added to the Design view.
If a link is absent, it can be created at this point by dragging the mouse from "Loan"."Reader_ID" to
"Reader"."ID".
Now fields from the Reader table can be entered into the tabular area. The fields are initially added
to the end of the query.
The position of the fields can be corrected in the tabular area of the editor using the mouse. So for
example, the First_name field has been dragged into position directly before the Loan_date field.
Now the names are visible. The Reader_ID has become superfluous. Also sorting by Surname and
First_name makes more sense than sorting by Reader_ID.
This query is no longer suitable for use as a query that allows new entries into the resulting table,
since it lacks the primary key for the added Reader table. Only if this primary key is built in, does
the query become editable again. In fact it then becomes completely editable so that the readers’
names can also be altered. For this reason, making query results editable is a facility that should
be used with extreme caution, if necessary under the control of a form.
Having a query that you can edit can create problems. Editing data in the query also
Caution edits data in the underlying table and the records contained in the table. The data
may not have the same meaning. For example, change the name of the reader, and
you have also changed what books the reader has borrowed and returned.
If you have to edit data, do so in a form so you can see the effects of editing data.
If we now switch back to SQL View, we see that all fields are now shown in double quotes: "Table
_name"."Field_name". This is necessary so that the database knows from which table the
previously selected fields come from. After all, fields in different tables can easily have the same
field names. In the above table structure this is particularly true of the ID field.
The following query works without putting table names in front of the field names:
SELECT "ID", "Number", "Price" FROM "Stock", "Dispatch"
WHERE "Dispatch"."stockID" = "Stock"."ID"
Note Here the ID is taken from the table which comes first in the FROM definition. The
table definition in the WHERE Formula is also superfluous, because stockID only
occurs once (in the Dispatch table) and ID was clearly taken from the Stock table
(from the position of the table in the query).
If a field in the query has an alias, it can be referred to – for example in sorting – by this alias
without a table name being given. Sorting is carried out in the graphical user interface according to
the sequence of fields in the tabular view. If instead you want to sort first by "Loan date" and then
by "Loan"."Reader_ID", that can be done if:
• The sequence of fields in the table area of the graphical user interface is changed (drag
and drop "Loan date" to the left of "Loan"."Reader_ID", or
• An additional field is added, set to be invisible, just for sorting (however, the editor will
register this only temporarily if no alias was defined for it) [add another "Loan date" field just
before "Loan"."Reader_ID" or add another "Loan"."Reader_ID" field just after "Loan date"],
or
• The text for the ORDER BY command in the SQL editor is altered correspondingly (ORDER
BY "Loan date", "Loan"."Reader_ID").
Specifying the sort order may not be completely error-free, depending on the LibreOffice version.
From version 3.5.3, sorting from the SQL view is correctly registered and displayed in the graphical
user interface, including the fields that are used in the query but are not visible in the query output.
(These fields do not have a check in the Visible row.)
A query may require a field that is not part of the query output. In the graphic in the
next section, Return_Date is an example. This query is searching for records that do
Tip not contain a return date. This field provides a criterion for the query but no useful
visible data.
The result of the query shows that Reader_ID '0' has a total of 3 media on loan. If the Count
function had been assigned to the Return_Date instead of the ID, every Reader_ID would have '0'
media on loan, since Return_date is predefined as NULL.
The corresponding Formula in SQL code is shown above.
Altogether the graphical user interface provides the following functions, which
correspond to functions in the underlying HSQLDB.
For an explanation of the functions, see “Query enhancement using SQL Mode“
on page 134.
A somewhat free translation would be: The following expression contains no aggregate function or
grouping.
When using Design View Mode, a field is only visible if the Visible row contains a
Tip check mark for the field. When using SQL Mode, a field is only visible when it follows
the keyword, SELECT.
When a field is not associated with a function, the number of rows in the query
output is determined by the search conditions. When a field is associated with a
function, the number of rows in the query output is determined by whether there is
any grouping or not. If there is no grouping, there is only one row in the query
output. If there is grouping, the number of rows matches the number of distinct
values that the grouping field has. So, all of the visible fields must either be
associated with a function or not be associated with a function to prevent this
Note conflict in the query output.
After this, the complete query is listed in the error message, but unfortunately
without the offending field being named specifically. In this case the field
Return_Date has been added as a displayed field. This field has no function
associated with it and is not included in the grouping statement either.
The information provided by using the More button is not very illuminating for the
normal database user. It just displays the SQL error code.
To correct the error, remove the check mark in the Visible row for the Return_Date field. Its search
condition (Criterion) is applied when the query is run, but it is not visible in the query output.
Using the GUI, basic calculations and additional functions can be used.
Only for people who use a comma for their decimal separator:
If you wish to enter numbers with decimal places using the graphical user interface,
Caution you must ensure that a decimal point rather than a comma is used to separate the
decimal places within the final SQL statement. Commas are used as field
separators, so new query fields are created for the decimal part.
An entry with a comma in the SQL view always leads to a further field containing the
numerical value of the decimal part.
The query now yields for each medium still on loan the fines that have accrued, based on the recall
notices issued and the additional multiplication field. The following query structure will also be
useful for calculating the fines due from individual users.
The "Loan"."ID" and "Loan"."Media_ID" fields have been removed. They were used in the previous
query to create by grouping a separate record for each medium. Now we will be grouping only by
the reader. The result of the query looks like this:
The simple query for the Title field from the Media table shows the test entries for this table, 9
records in all. But if you enter Subtitle into the query table, the record content of the Media table is
reduced to only 2 Titles. Only for these two Titles are there also Subtitles in the table. For all the
other Titles, no subtitles exist. This corresponds to the join condition that only those records for
which the Media_ID field in the Subtitle table is equal to the ID field in the Media table should be
shown. All other records are excluded.
By default, relationships are set as Inner Joins. The window provides information on the way this
type of join works in practice.
The two previously selected tables are listed as Tables Involved. They are not selectable here. The
relevant fields from the two tables are read from the table definitions. If there is no relationship
specified in the table definition, one can be created at this point for the query. However, if you have
planned your database in an orderly manner using HSQLDB, there should be no need to alter
these fields.
The most important setting is the Join option. Here relationships can be so chosen that all records
from the Subtitle table are selected, but only those records from Media which have a subtitle
entered in the Subtitle table.
Or you can choose the opposite: that in any case all records from the table Media are displayed,
regardless of whether they have a subtitle.
The Natural option specifies that the linked fields in the tables are treated as equal. You can also
avoid having to use this setting by defining your relationships properly at the very start of planning
your database.
For the type Right join, the description shows that all records from the Media table will be displayed
(Subtitle RIGHT JOIN Media). As there is no Subtitle that lacks a title in Media but there are
certainly Titles in Media that lack a Subtitle, this is the right choice.
Direct use of SQL commands is also accessible using the graphical user interface, as the above
figure shows. Click the icon highlighted (Run SQL command directly) to turn the Design View
Off/On icon off. Now when you click the Run icon, the query runs the SQL commands directly.
Here is an example of the extensive possibilities available for posing questions to the database
and specifying the type of result required:
SELECT [{LIMIT <offset> <limit> | TOP <limit>}][ALL | DISTINCT]
{ <Select-Formulation> | "Table_name".* | * } [, ...]
[INTO [CACHED | TEMP | TEXT] "new_Table"]
FROM "Table_list"
[WHERE SQL-Expression]
[GROUP BY SQL-Expression [, ...]]
[HAVING SQL-Expression]
[{ UNION [ALL | DISTINCT] | {MINUS [DISTINCT] | EXCEPT [DISTINCT] } |
INTERSECT [DISTINCT] } Query statement]
[ORDER BY Order-Expression [, ...]]
[LIMIT <limit> [OFFSET <offset>]];
[ALL | DISTINCT]
SELECT ALL is the default. All records are displayed that fulfill the search conditions. Example:
SELECT ALL "Name" FROM "Table_name" yields all names; if "Peter" occurs three times
and "Egon" four times in the table, these names are displayed three and four times
respectively. SELECT DISTINCT "Name" FROM "Table_name" suppresses query results
<Select-Formulation>
{ Expression | COUNT(*) |
{ COUNT | MIN | MAX | SUM | AVG | SOME | EVERY | VAR_POP | VAR_SAMP |
STDDEV_POP | STDDEV_SAMP }
([ALL | DISTINCT]] Expression) } [[AS] "display_name"]
Field names, calculations, record totals are all possible entries. In addition different functions
are available for the field shown. Except for COUNT(*) (which counts all the records) none of
these functions access NULL fields.
COUNT | MIN | MAX | SUM | AVG | SOME | EVERY | VAR_POP | VAR_SAMP |
STDDEV_POP | STDDEV_SAMP
COUNT("Name") counts all entries for the field Name.
MIN("Name") shows the first name alphabetically. The result of this function is always
formatted just as it occurs in the field. Text is shown as text, integers as integers, decimals as
decimals and so on.
MAX("Name") shows the last name alphabetically.
SUM("Number") can add only the values in numerical fields. The function fails for date fields.
AVG("Number") shows the average of the contents of a column. This function too is limited to
numerical fields.
SOME("Field_Name"), EVERY("Field_Name"): Fields used with these functions must
have the Yes/No [BOOLEAN] field type (contains only 0 or 1). Furthermore, they produce a
summary of the field content to which they are applied.
SOME returns TRUE (or 1) if at least one entry for the field is 1, and it returns FALSE (or 0) only
if all the entries are 0. EVERY returns 1 only if every entry for the field is 1, and returns FALSE
if at least one entry is 0.
The Boolean field type is Yes/No[BOOLEAN]. However, this field contains only 0 or
1. In query search conditions, use either TRUE, 1, FALSE or 0. For the Yes
Tip condition, you can use either TRUE or 1. For the No condition, use either FALSE or
0. If you try to use either “Yes” or “No” instead, you get an error message. Then you
will have to correct your error.
Example:
SELECT "Class", EVERY("Swimmer") FROM "Table1" GROUP BY "Class";
Class contains the names of the swimming class. Swimmer is a Boolean field describing
whether a student can swim or not (1 or 0). Students contains the names of the students.
Table1 contains these fields: its primary key, Class, Swimmer, and Students. Only Class and
Swimmer are needed for this query.
Because the query is grouped by the entries of the field Class, EVERY will return a value for
the field, Swimmer, for each class. When every person in a swimming class can swim, EVERY
returns TRUE. Otherwise EVERY returns FALSE because at least one student of the class can
not swim. Since the output for the Swimmer field is a checkbox, A check mark indicates TRUE,
and no check mark indicates FALSE.
VAR_POP | VAR_SAMP | STDDEV_POP | STDDEV_SAMP are statistical functions and affect
only integer and decimal fields.
All these functions return 0, if the values within the group are all equal.
"Table_name".* | * [, ...]
Each field to be displayed is given with its field names, separated by commas. If fields from
several tables are entered into the query, a combination of the field name with the table name
is necessary: "Table_name"."Field_name".
Instead of a detailed list of all the fields of a table, its total content can be displayed. For this
you use the symbol "*". It is then unnecessary to use the table name, if the results will only
apply to the one table. However, if the query includes all of the fields of one table and at least
one field from a second table, use:
"Table_name 1".*, “Table_name 2”.”Field_name”.
FROM <Table_list>
"Table_name 1" [{CROSS | INNER | LEFT OUTER | RIGHT OUTER} JOIN
"Table_name 2" ON Expression] [, ...]
The tables which are to be jointly searched are usually in a list separated by commas. The
relationship of the tables to one another is then additionally defined by the keyword WHERE.
If the tables are bound through a JOIN rather than a comma, their relationship is defined by the
term beginning with ON which occurs directly after the second table.
A simple JOIN has the effect that only those records are displayed for which the conditions in
both the tables apply.
Example:
SELECT "Table1"."Name", "Table2"."Class" FROM "Table1", "Table2" WHERE
"Table1"."ClassID" = "Table2"."ID"
is equivalent to:
SELECT "Table1"."Name", "Table2"."Class" FROM "Table1" JOIN "Table2"
ON "Table1"."ClassID" = "Table2"."ID"
Here the names and the corresponding classes are displayed. If a name has no class listed for
it, that name is not included in the display. If a class has no names, it is also not displayed. The
addition of INNER does not alter this.
SELECT "Table1"."Name", "Table2"."Class" FROM "Table1" LEFT JOIN
"Table2" ON "Table1"."ClassID" = "Table2"."ID"
If LEFT is added, all "Names" from "Table1" are displayed even if they have no "Class". If, on
the contrary, RIGHT is added, all Classes are displayed even if they have no names in them.
Addition of OUTER need not be shown here. (Right Outer Join is the same thing as Right Join;
Left Outer Join is the same thing as Left Join.)
[WHERE SQL-Expression]
The standard introduction for conditions to request a more accurate filtering of the data. Here
too the relationships between tables are usually defined if they are not linked together with
JOIN.
When fields are processed using a particular function (for example COUNT, SUM
Tip …), all fields that are not processed with a function but should be displayed are
grouped together using GROUP BY.
[HAVING SQL-Expression]
The HAVING formula closely resembles the WHERE formula. The difference is that the WHERE
formula applies to the values of selected fields in the query. The HAVING formula applies to
selected calculated values. Specifically, the WHERE formula can not use an aggregate function
as part of a search condition; the HAVING formula does.
The HAVING formula serves two purposes as shown in the two examples below. In the first
one, the search condition requires that the minimum run-time be less than 40 minutes. In the
second example, the search condition requires that an individual's balance must be positive.
The query results for the first one lists the names of people whose run-time has been less than
40 minutes at least one time and the minimum run-time. People whose run-times have all be
greater than 40 minutes are not listed.
The query results for the second one lists the names of people who have a total greater output
than input and their balance. People whose balance is 0 or less are not listed.
[SQL Expression]
SQL expressions are combined according to the following scheme:
[NOT] condition [{ OR | AND } condition]
Example:
SELECT * FROM "Table_name" WHERE NOT "Return_date" IS NULL AND
"ReaderID" = 2;
The records read from the table are those for which a “Return_date” has been entered and the
"ReaderID" is 2. In practice this means that all media loaned to a specific person and returned
can be retrieved. The conditions are only linked with AND. The NOT refers only to the first
condition.
SELECT * FROM "Table_name" WHERE NOT ("Return_date" IS NULL AND
"ReaderID" = 2);
Parentheses around the condition, with NOT outside them shows only those records that do not
fulfill the condition in parentheses completely. This would cover all records, except for those for
"ReaderID" number 2, which have not yet been returned.
Example:
SELECT "Name" FROM "Table1" WHERE EXISTS (SELECT "First_name" FROM
"Table2" WHERE "Table2"."First_name" = "Table1"."Name")
The names from Table1 are displayed for which first names are given in Table2.
| Value BETWEEN Value AND Value
BETWEEN value1 AND value2 yields all values from value1 up to and including value2. If
the values are letters, an alphabetic sort is used in which lower-case letters have the same
value as the corresponding upper-case ones.
What is hidden behind the numbers cannot be made visible by using a list box, as the foreign key
is input directly using the barcode. In the same way, it is impossible to use a list box next to the
item to show at least the unit price.
Here a query can help.
SELECT "Checkout"."Receipt_ID", "Checkout"."Total", "Stock"."Item",
"Stock"."Unit_Price", "Checkout"."Total"*"Stock"."Unit_price" AS
"Total_Price" FROM "Checkout", "Item" WHERE "Stock"."ID" =
"Checkout"."Item_ID";
Now at least after the information has been entered, we know how much needs to be paid for
3 * Item'17'. In addition only the information relevant to the corresponding Receipt_ID needs to be
filtered through the form. What is still lacking is what the customer needs to pay overall.
SELECT "Checkout"."Receipt_ID",
SUM("Checkout"."Total"*"Stock"."Unit_price") AS "Sum" FROM "Checkout",
"Stock" WHERE "Stock"."ID" = "Checkout"."Item_ID" GROUP BY
"Checkout"."Receipt_ID";
Design the form to show one record of the query at a time. Since the query is grouped by
Receipt_ID, the form shows information about one customer at a time.
Subqueries
Subqueries built into fields can always only return one record. The field can also return only one
value.
SELECT "ID", "Income", "Expenditure", ( SELECT SUM( "Income" ) -
SUM( "Expenditure" ) FROM "Checkout") AS "Balance" FROM "Checkout";
This query allows data entry (primary key included). The subquery yields precisely one value,
namely the total balance. This allows the balance at the till to be read after each entry. This is still
not comparable with the supermarket checkout form described in “Queries as a basis for additional
information in forms“. Naturally it lacks the individual calculations of Total * Unit_price, but also the
presence of the receipt number. Only the total sum is given. At least the receipt number can be
included by using a query parameter:
SELECT "ID", "Income", "Expenditure", ( SELECT SUM( "Income" ) -
SUM( "Expenditure" ) FROM "Checkout" WHERE "Receipt_ID" =
:Receipt_Number) AS "Balance" FROM "Checkout" WHERE "Receipt_ID" =
:Receipt_Number;
Subforms based on queries are not automatically updated on the basis of their
Note parameters. It is more appropriate to pass on the parameter directly from the main
form.
Correlated subqueries
Using a still more refined query, an editable query allows one to even carry the running balance for
the till:
SELECT "ID", "Income", "Expenditure", ( SELECT SUM( "Income" ) -
SUM( "Expenditure" ) FROM "Checkout" WHERE "ID" <= "a"."ID" ) AS
"Balance" FROM "Checkout" AS "a" ORDER BY "ID" ASC
The Checkout table is the same as Table "a". "a" however yields only the relationship to the current
values in this record. In this way the current value of ID from the outer query can be evaluated
within the subquery. Thus, depending on the ID, the previous balance at the corresponding time is
determined, if you start from the fact that the ID, which is an autovalue, increments by itself.
The Design View Mode cannot find the field contained in the inner query "Loan_ID", which governs
the relationship between the inner and outer queries.
When the query is run in SQL Mode, the corresponding content from the subquery is reproduced
without error. Therefore you do not have to use direct SQL mode in this case.
The outer query used the results of the inner query to produce the final results. These are a list
of the "Loan_ID" values that should be locked and why. If you want to further limit the final results,
use the sort and filter functions of the graphical user interface.
The normal linking of tables, after all tables have been counted, follows the keyword
WHERE.
If there is a LEFT JOIN or a RIGHT JOIN, the assignment is defined directly
Note
after the two table names using ON. The sequence is therefore always
Table1 LEFT JOIN Table2 ON Table1.Field1 = Table2.Field1
LEFT JOIN Table3 ON Table2.Field1 = Table3.Field1 ...
Two titles of the Media table do not yet have an author entry or a Subtitle. At the same time one
Title has a total of three Authors. If the Author Table is linked without a LEFT JOIN, the two
Media without an Author will not be shown. But as one medium has three authors instead of one,
the total number of records displayed will still be 15.
Only by using LEFT JOIN will the query be instructed to use the Media table to determine which
records to show. Now the records without Subtitle or Author appear again, giving a total of 17
records.
Using appropriate Joins usually increases the amount of data displayed. But this enlarged data set
can easily be scanned, since authors and subtitles are displayed in addition to the titles. In the
example database, all of the media-dependent tables can be accessed.
A query created using Create Query in SQL View has the disadvantage that it
cannot be sorted or filtered using the GUI. There are therefore limits to its use.
Tip A View on the other hand can be managed in Base just like a normal table – with the
exception that no change in the data is possible. Here therefore even in direct SQL-
commands all possibilities for sorting and filtering are available.
Views are a solution for many queries, if you want to get any results at all. If for example a
Subselect is to be used on the results of a query, create a View that gives you these results. Then
use the subselect on the View. Corresponding examples are to be found in Chapter 8, Database
Tasks.
Creating a View from a query is rather easy and straight forward.
1) Click the Table object in the Database section.
2) Click Create View.
3) Close the Add Table dialog.
When using the Report Builder, you should frequently save your work during editing.
In addition to saving within the Report Builder itself after each significant step, you
Caution should also save the whole database.
Depending on the version of LibreOffice that you are using, the Report Builder can
sometimes crash during editing.
The functionality of completed reports is not affected even if they were created under
another version, in which the problem does not occur.
Two output formats for reports are available for selection: ODF Text document (a Writer document)
or ODF Spreadsheet (a Calc document). If you just want a tabular view of your data, the Calc
document should definitely be chosen for your report. It is significantly faster to create and is also
easier to format subsequently, as there are fewer options to consider and columns can easily be
dragged to the required width afterward.
By default, the Report Builder looks for its data source in the first table in the database. This
ensures that at least a test of the functions is possible. A data source has to be chosen before the
report can be provided with fields.
The Report Builder provides a lot of additional buttons, so the table on the next page shows the
buttons with their descriptions. The buttons for aligning elements are not further described in this
chapter. They are useful for quick adjustment of fields in a single area of the Report Builder, but in
principle everything can be done by direct editing of field properties.
Just as with forms, it is helpful to use the appropriate navigator. So, for example, a careless click at
the start of the Report Builder can make it difficult to find the properties of the data for the report.
Such data may only be reachable through the report navigator. Left-click on Report and the
properties of the report are once more accessible.
Here grouping and sorting are by the Reader_Name field. Additional fields could also be included
in the table above. For example, if you also want to group and sort by the Loan_Date field, choose
this as the second line.
Directly under the table, several grouping actions are available for selection. You can move a group
up or down the list or completely remove it. As only one group is necessary for the planned report,
Figure 46 shows only the Delete symbol at the extreme right of the group actions as available.
The Sorting property is self-explanatory.
When the entry was created, the left side of the Report Builder immediately showed a new division.
Next to the field description Reader_Name you can now see Header. This section is for the group
header in the report. The header might contain the name of the person who will receive the recall
notice. In this case there is no group footer. Such a footer could contain the fine due, or the place
and current date and a space for the signature of the person sending the notice.
Figure 47 shows the report design for the recall notice. In the page header is the heading Libre
Office Library, inserted as a label field. Here you could also have a letterhead with a logo, since the
incorporation of graphics is possible. The fact that this level is called Page header does not imply
that there is no space above it. That depends on the page settings; if an upper margin has been
set, it lies above the page header.
In principle LibreOffice provides for the possibility of adding horizontal and vertical
lines. These are displayed in design mode. At present they do not appear when the
report is complete.
Note These lines have the further disadvantage that they are interpreted only as hairlines.
They can be reproduced better if rectangles are used. Set the background of the
rectangle to black and the size to, for example, 17cm wide and 0.03cm high. This
will create a horizontal line with a thickness of 0.03cm and a length of 17cm.
The Reader_Name footer closes the letter with a greeting formula and an area for the signature.
The footer is so defined that an additional page break will occur after this area. Also, contrary to the
default setup, it is specified that this area should be kept together in all cases. After all, it would
look rather odd if many recall notices had the signature on a separate page.
Keep together refers here to the page break. If you want the content of a record to be kept together
independently of the break, this is only possible at present if the record is not read in as Details but
is used as the basis for a grouping. You can choose Keep together = Yes, but it does not work; the
Details area becomes separated. You have to put the content of Details in a separate group to
keep it together.
A built-in function is used for calculating the total fines.
Reports for single records can also extend over more than one page. The size of the
report is quite separate from the page size. However, stretching the details area over
more than one page can lead to faulty breaks. Here the Report Builder still has
problems in calculating the spacing correctly. If both grouping areas and graphical
Note elements are included, this may result in unpredictable sizes for certain areas.
So far individual elements can be moved to positions outside the size of a single
page only with the mouse and cursor keys. The properties of the elements always
provide the same maximum distance from the upper corner of any area that lies on
the first page.
As with forms, fields are given names. By default, the name is that of the underlying database field.
A field can be set to be invisible. This may seem a bit pointless in the case of fields but is useful for
group headers and footers, which may be required to carry out other functions of the grouping
without containing anything that needs to be displayed.
If Print repeated values is deactivated, display of the field is inhibited when a field with the same
content is loaded directly before. This functions correctly only for data fields that contain text.
Numeric fields or date fields ignore the deactivation instruction, Label fields are completely faded
out when deactivated, even if they occur only once.
In the Report Builder the display of certain content can be inhibited by using Conditional Print
Expression or the value of the field can be used as a base for formatting text and background.
More on conditional expressions is given in “Conditional print” on page 169.
The setting for the mouse wheel has no effect because report fields are not editable. It seems to be
a leftover from the form definition dialog.
The Print When Group Change function could not be reproduced in reports either.
If the background is not defined as transparent, a background color can be defined for each field.
The other entries deal with the internal content of the field in question. This covers the font (for font
color, font weight, and so on, see Figure 48), the alignment of the text within the field, and
formatting with the corresponding Character dialog (see Figure 49).
A graphical control can contain graphics from both inside and outside the database. Unfortunately
it is not possible at present to store a graphic such as a logo permanently in Base. Therefore it is
essential that the graphic is available in the search path, even when you are presented with the
choice of embedding rather than linking images and the first field Set up as link can be set (literally
closed) to a corresponding planned functionality. This is one of several functions that are planned
for Base and are in the GUI but have not actually been implemented yet—so the buttons and
checkboxes have no effect.
Alternatively, of course, a graphic can be stored in the database itself and so becomes available
internally. But in that case, it must be accessible through one of the fields in the query underlying
the report.
To take up an external graphic, use the selection button beside the Graphic field to load it. To load
a graphical database field, specify the field under the Data tab.
The vertical alignment setting does not seem to have any effect during the design stage. When you
call up the report, however, the graphic appears in the correct position.
When scaling, you can select No, Keep aspect ratio, or Autom. Size. This corresponds to the
settings for a form:
• No: The image is not fitted to the control. If it is too large, a cropped version is shown. The
original image is not affected by this.
• Keep aspect ratio: The image is fitted to the control but not distorted.
• Automatic size: The image is fitted to the control and in some cases may be distorted.
You must draw the place for the chart using the mouse. In the general properties, in addition to the
familiar fields, you can choose a Chart type (see the corresponding types in Calc). In addition, you
can set a maximum number of records for the preview, which will give an impression of how the
chart will finally look.
Charts can be formatted in the same way as in Calc (double-click on the chart). For further
information, see the description in the LibreOffice Calc Guide.
The chart is linked in the Data section with the necessary data fields. Here, in a Media Top 10 list
example, the chart shows the frequency with which particular media are borrowed. The Query
Editor is used to create a suitable SQL command, as you would do for a listbox in a form. The first
column in the query will be used to provide the labels for the vertical bars in the chart, while the
second column yields the total number of loan transactions, shown in the height of the bars.
In the example above, the chart shows very little at first, since only limited test loans were carried
out before the SQL command was issued.
The chart on the next page, from the membership database of a society (German:
Mitgliederstatistik), has been prepared from a query that needs to be entered in direct SQL mode,
as the graphical user interface does not understand it. For this reason No (German: Nein) has
been chosen for Analyze SQL command, a choice that excludes any filtering and sorting with the
internal tools of the Report Builder. These fields are therefore grayed out. In the data properties of
the chart, Query (German: Abfrage) has been entered.
Fields are linked together in the same way as for a main form with a subform. In the report itself,
the age distributions of male and female members are listed in tabular form. They are grouped by
gender. Each group is given its own chart. So that the chart only contains data for the correct
gender, the Gender field (German: Geschlecht) in the report is linked to the Gender in the chart.
The creation of charts works at present only in Versions 3.3.x and 3.4.x. From
Version 3.5, LibreOffice can no longer open these reports. They can still be
produced, however.
Note
LibreOffice is not the only program to have problems with charts. In Version 3.3 of
OpenOffice.org, the display does not work either. OpenOffice.org does open the
reports, but with the charts missing.
In the properties dialog, the Data tab shows by default only the database field from which the data
for this report field will be read. However, in addition to the field types Field and Formula, the types
Function, Counter, and User-defined function are available.
You can select in advance the Sum, Minimum, and Maximum functions. They will apply either to
the current group or to the whole report. These functions can lead to problems if a field is empty
(NULL). In such fields, if they have been formatted as numbers, "NaN" appears; that is, there is no
numerical value present. For empty fields, no calculation is carried out and the result is always 0.
Such fields can be reformatted to display a value of 0 by using the following formula in the Data
area of the view.
IF([numericfield];[numericfield];0)
This function calculates with the actual value of a field that has no value. It would seem simpler to
formulate the underlying query for the report so that 0 is given instead of NULL for numeric fields.
Finally the detailed User-defined Function is available. It may happen that the Report Builder itself
chooses this variant, if a calculation has been requested, but for some reason it cannot correctly
interpret the data source.
Entering formulas
The Report Builder is based on the Pentaho Report Builder. A small part of its documentation is at
http://wiki.pentaho.com/display/Reporting/9.+Report+Designer+Formula+Expressions.
A further source is the Specifications for the OpenFormula Standard:
http://www.oasis-open.org/committees/download.php/16826/openformula-spec-20060221.html
Basic principles:
Next to the date field is a button with three dots whenever a formula can be entered. This button
starts the Function Wizard.
However there are far fewer functions than in Calc. Many functions do have Calc equivalents.
There the Wizard calculates the result of the function directly.
The Function Wizard does not always work perfectly. For instance, text entries are not taken up
with double quotes. However, only entries with double quotes are processed when starting the
function.
The following functions are available:
Function Description
Date and Time Functions
DATE Produces a valid date from numeric values for the year, the month
and the day.
DATEDIF Returns the total years, months or days between two date values.
(DAY | MONTH | YEAR)
DATEVALUE Converts an American date entry in text form (quoted) into a date
value. The American variant that is produced can then be
reformatted.
DAY Returns the day of the month for a given date.
DAY([Date field])
Mathematical functions
ABS Returns the absolute (non-negative) value of a number.
ACOS Calculates the arccosine of a number. - arguments between -1 and
1.
(since LO 3.5)
ACOSH Calculates the areacosine (inverse hyperbolic cosine) – argument
>= 1.
(since LO 3.5)
ASIN Calculates the arcsine of a number – argument between -1 and 1.
(since LO 3.5)
In the Report Navigator the function is displayed under Reader_Name group. By right-clicking on
this function, you can define additional functions by name.
The properties of the function SummeGebuehrLeser_Name are shown above. The formula adds
the field Charge to the value already stored in the function itself. The initial value is the value of the
Charge field on the first traverse of the group. This value is stored in the function under the function
name and is reused in the formula, until the loop is ended and the group footer is written.
Deep traversing seems to have no function for now, unless charts are being treated here as
subreports.
If Pre evaluation is activated for the function, the result can also be placed in the group header.
Otherwise the group header contains only the corresponding value of the first field of the group.
User-defined functions can also reference other user-defined functions. In that case you must
ensure that the functions used have already been created. Pre-calculation in functions that refer to
other functions must be excluded.
[SumMarksClass] / ([ClassNumber]+1)
refers to the Class group. The content of the Marks field is summed and the sum for all the records
is returned. The sum of the marks is divided by the sum of the records. To get the correct number,
1 must be added as shown with [ClassNumber]. This will then yield the average marks.
Conditional print
The general properties of group headers, group footers, and fields include a Conditional Print
Expression field. Formulas that are written in this field influence the content of a field or the display
of an entire region. Here, too, you can make use of the Function Wizard.
[Fieldname]="true"
causes the content of the named field to be displayed only if it is true.
Many forms of conditional display are not fully determined by the specified properties. For instance,
if a graphical separator line is to be inserted after the tenth place of a list of competition results, you
cannot simply use the following conditional display command for the graphic:
[Place]=10
This command does not work. Instead the graphic will continue to appear in the Details section
after each subsequent record.
It is safer to bind the conditional display to a group footer rather than to the graphic, if this is not
otherwise needed. The line is positioned in the group footer. Then the line does actually appear
after the 10th place, when formulated as above. But in that case the content that would previously
have appeared in the Details section must be stored in the group header.
Conditional formatting
Conditional formatting can be used, for example, to format a calender so that weekends are shown
differently. Choose Format > Conditional formatting and enter:
WEEKDAY([Date])=1
and the corresponding formatting for Sundays.
If you use ‘Expression is’ in conditional formatting, you can enter a formula. As is usual in Calc,
several conditions can be formulated and are evaluated sequentially. In the above example, first
Sunday is tested for, then Saturday. Finally there might be a query about the content of the field.
So for example the content ‘Holiday’ would lead to a different format.
Registration of databases
Many functions, such as printing labels or using data for form letters, require the registration of a
database in the configuration of LibreOffice.
Using Tools > Options > LibreOffice Base > Databases > New, a database can be registered for
subsequent use by other LibreOffice components.
The database is found using the file browser and connected to LibreOffice in a similar way as for a
simple form. The database itself must be given a suitably informative name, for which you can
simply use the name of the database file. The name serves as an alias, which can also be used in
queries to the database.
A click on the expansion sign in front of the database name opens the database and shows a sub-
folder for queries and another for tables. Other sub-folders of the database are not made available
here. Internal forms and reports can only be accessed by opening the database itself.
Only when you click on the Tables folder is the database actually accessed. For databases
protected by a password, the password must be entered at this point.
To the right of the name tree, you can see the table you have selected. It can be edited just as in
Base. However direct entry into tables should be carried out with caution in very complex relational
databases, as the tables are linked together with foreign keys. For example, the database shown
below has separate tables for street names, postcodes and towns.
For a proper view of the data (but without the ability to edit), queries or views are more suitable.
Of the icons in the toolbar, many will be familiar from data entry into tables. The main new ones are
those in the last section: Data to Text, Data to Fields, Mail Merge, Data Source of Current
Document, Explorer on/off.
Data to Text
The Data to Text function is available as soon as a record is selected.
If you now choose Data to Text, a Wizard appears to carry out the necessary formatting.
Figure 55: Insert data as Fields – corresponds also to the dialog for Insert data as Text
The fields inserted into the text in this way can subsequently be deleted singly or used for a mail
merge.
If you choose Insert data as Text, the only difference from using fields is that fields remain linked
to the database. When you insert as text, only the content of the specified fields is transferred and
not the link to the actual database. That explains why the dialog for this option is the same as for
the previous one.
The fields have a gray background. If the mouse is hovered over the fields, it shows that the fields
are linked to the Media database, to the table Reader and, within this table, to the field ID.
So, for example, a double-click on the field ID opens the following overview. This makes it clear
which field was created through the Insert Data as Fields procedure. It is the same field type that is
shown by Insert > Fields > Other > Database.
Figure 57: Double-click on an inserted field to show the properties of the Mail Merge fields
It is simpler to create such a field by selecting the column header of the table in the data source
browser and dragging it into the document with the mouse. You can create a form letter directly in
this way.
Data to Fields
Data as Fields, as described in the previous section, is used to create mail merge fields in a Writer
document. If now you select a different record in the data source browser and then choose Data as
Fields, the previously inserted data are replaced by the new data.
Mail merge
The Mail Merge button launches the Mail Merge Wizard. As the form letter in the above example
assembles its data from different tables, you need first to launch the database. In the database,
you then create a new query to make the required data available.
The database is launched through a right-click on the database itself or on one of its tables or
queries, which immediately refreshes the display in the data source browser. After that the Mail
Merge Wizard can be called up by using the corresponding button.
Explorer on/off
Toggling the Explorer On/Off button shows or hides the directory tree to the left of the table view.
This allows more space, if necessary, for a display of the data. To access another table, you will
need to switch the Explorer back on.
The Mail Merge Wizard can produce either letters or emails using records from the database.
Up to now all the documents have been identical except for the different content of the fields read
from the database. This can be changed in Step 7.
Label printing
Files > New > Labels launches the Label Printing Wizard. It opens a dialog, which includes all
questions of formating and content for labels, before the labels themselves are produced. The
settings in this dialog are saved in the personal settings for the user.
In versions 3.4.x to 3.5.2, due to a change in the basic settings in the label wizard,
display errors occurred when the labels were the same width as the page width.
Note Under these conditions, the last label simply slides down one line.
In version 3.5.3 page settings were added in the Format tab.
The Format tab allows you to set the label size accurately. The settings are only significant when
the make and type of the labels is not known. It is noteworthy that, to print labels 7.00 cm wide, you
need a page width a little bigger than 3*7.00 cm = 21.00 cm. Only then will three labels be printed
in a row on the page.
Choose Yes to fill the address database fields with the corresponding content.
Here all tables and queries in the selected database are available. Using the 'Insert' button, the
various fields can be inserted one after another directly into the text at the current cursor position.
If you want to create a salutation, which is usual in form letters, you can use a hidden paragraph or
hidden text: Insert > Fields > Other > Functions > Hidden paragraph. For both variants take
care that the condition you formulate will not be fulfilled, since you want the paragraph to be
visible.
For the formula Dear Mrs <Surname>, to appear only when the person is female, a sufficient
condition is:
[Addresses.Mailmergequery.Gender] != "f"
Now the only remaining problem is that there may be no surname. Under these circumstances,
"Dear Sir/Madam," should appear so this is the condition you must insert. The overall condition is:
[Addresses.MailMergeQuery.Gender] != "w" OR NOT
[Addresses.MailMergeQuery.Surname]
That excludes the possibility of this paragraph appearing when the person is not female or there is
no entered surname.
In the same way you can create entries for the masculine gender and for missing entries for the
two remaining types of salutation.
External forms
If simple form properties available in LibreOffice are to be used in other program modules such as
Writer and Calc, you only need to display the form design toolbar, using View > Toolbars > Form
design, then open the Form navigator. You can build a form or, as described in the Forms chapter,
create a form field. The Data tab of the Form Properties dialog looks a little different from the one
you see when forms are built directly in an ODB database file:
Data dragged into Calc in this way shows the following properties:
Not only the data are imported, but the field properties too are read and acted on during the import.
Fields such as house numbers, which were declared as text fields, are formatted as text after
insertion into Calc.
The import becomes a Calc range, which by default is assigned the name Import1. The data can
later be accessed using this range. Data > Refresh range allows the range, where appropriate, to
be supplied with new data from the database.
At this point you can create a new additional field for a primary key. The name of this database
field must not be one that already exists as a column header in the Calc sheet. Otherwise you get
the error message:
The following fields are already set as primary key: ID
Unfortunately this message does not describe the problem quite correctly.
If you want an existing field to be used as the key, do not check the Create primary key box. In
such cases the primary key is set using the third dialog in the Wizard.
Here the ID field, which is to be the primary key, is formatted. The primary key must be set by
using the context menu of its field name, in cases where it has not been created by the Wizard in
the Copy Table dialog as an additional field. After you click the Finish button, the table is created.
The new primary key is not an Auto-Value key. To create such a key, you must open the database
for editing. There you can carry out further formatting of the table.
Data filtering
Data filtering using the GUI is described in the chapter on data entry into tables. Here we describe
a solution to a problem which many users have raised: how to use listboxes to search for the
content of fields in tables, which then appear filtered in the underlying form section and can be
edited.
The basis for this filtering is an editable query (see the chapter on queries) and an additional table,
in which the data to be filtered are stored. The query shows from its underlying table only the
records that correspond to the filter values. If no filter value is given, the query shows all records.
The following example starts from a MediaExample table that includes, among others, the
following fields: ID (primary key), Title, Category. The field types are INTEGER, VARCHAR, and
VARCHAR respectively.
First we require a FilterExample table. This table contains a primary key and 2 filter fields (of
course you can have more if you want): "ID" (primary key), Filter_1, Filter_2. As the fields
of the MediaExample table, which is to be filtered, are of the type VARCHAR, the fields
Filter_1 and Filter_2 are also of this type. ID can be the smallest numeric type, TINYINT
because the Filter table will never contain more than one record.
You can also filter fields that occur in the MediaExample table only as foreign keys. In that case,
you must give the corresponding fields in the FilterExample table the type appropriate for the
foreign keys, usually INTEGER.
The following query is certainly editable:
SELECT * FROM "MediaExample"
All records from the MediaExample table are displayed, including the primary key.
SELECT * FROM "MediaExample" WHERE "Title" = IFNULL( ( SELECT
"Filter_1" FROM "FilterExample" ), "Title" )
If the field Filter_1 is not NULL, those records are displayed for which the Title is the same as
Filter_1. If the field Filter_1 is NULL, the value of the Title field is used instead. As Title
is the same as "Title", all records are displayed. This assumption does not hold however if the
Title field of any record is empty (contains NULL). That means that those records will never be
displayed that have no title entry. Therefore we need to improve the query:
SELECT * , IFNULL( "Title", '' ) AS "T" FROM "MediaExample" WHERE "T"
= IFNULL( ( SELECT "Filter_1" FROM "FilterExample" ), "T" )
IFNULL(expression, value) requires the expression has the same field type
as the value.
• If the expression has the field type VARCHAR, use two single quotes '' as
the value.
Tip • If it has DATE as its field type, enter a date as the value that is not contained
in the field of the table to be filtered. Use this format: {D 'YYYY-MM-DD'}.
• If it is any of the numerical field types, use the NUMERIC field type for the
value. Enter a number that does not appear in the field of the table to be
filtered.
Code snippets
These code snippets come from queries to mailing lists. Particular problems arise that might
perhaps be useful as solutions for your own database experiments.
Line numbering
Automatically incrementing fields are fine. However, they do not tell you definitely how many
records are present in the database or are actually available to be queried. Records are often
deleted and many users try in vain to determine which numbers are no longer present in order to
make the running number match up.
SELECT "ID", ( SELECT COUNT( "ID" ) FROM "Table" WHERE "ID" <=
"a"."ID" ) AS "Nr." FROM "Table" AS "a"
The ID field is read, and the second field is determined by a correlating sub-query, which seeks to
determine how many field values in ID are smaller than or equal to the current field value. From
this a running line number is created.
Each record to which you want to apply this query contains fields. To apply this query to the
records, you must first add these fields to the query. You can place them in whatever order you
desire in the SELECT clause. If you have the records in a form, you need to modify the form so that
the data for the form comes from this query.
For example the record contains field1, field2, and field3. The complete query would be:
SELECT "ID", "field1", "field2", "field3", ( SELECT COUNT( "ID" ) FROM
"Table" WHERE "ID" <= "a"."ID" ) AS "Nr." FROM "Table" AS "a"
A numbering for a corresponding grouping is also possible:
SELECT "ID", "Calculation", ( SELECT COUNT( "ID" ) FROM "Table" WHERE
"ID" <= "a"."ID" AND "Calculation" = "a"."Calculation" ) AS "Nr." FROM
"Table" AS "a" ORDER BY "ID" ASC, "Nr." ASC
Here one table contains different calculated numbers. ("Calculation"). For each calculated number,
"Nr." is separately expressed in ascending order after sorting on the ID field. This produces a
numbering from 1 upwards.
If the actual sort order within the query is to agree with the line numbers, an appropriate type of
sorting must be mapped out. For this purpose the sort field must have a unique value in all records.
Otherwise two place numbers will have the same value. This can actually be useful if, for example,
the place order in a competition is to be depicted, since identical results will then lead to a joint
position. In order for the place order to be expressed in such a way that, in case of joint positions,
the next value is omitted, the query needs to be be constructed somewhat differently:
SELECT "ID", ( SELECT COUNT( "ID" ) + 1 FROM "Table" WHERE "Time" <
"a"."Time" ) AS "Place" FROM "Table" AS "a"
All entries are evaluated for which the "Time" field has a smaller value. That covers all athletes who
reached the winning post before the current athlete. To this value is added the number 1. This
determines the place of the current athlete. If the time is identical with that of another athlete, they
are placed jointly. This makes possible place orders such as 1st Place, 2nd Place, 2nd Place, 4.
Place.
It would be more problematic, if line numbers were required as well as a place order. That might be
useful if several records needed to be combined in one line.
SELECT "ID", ( SELECT COUNT( "ID" ) + 1 FROM "Table" WHERE "Time" <
"a"."Time" ) AS "Place",
CASE WHEN
( SELECT COUNT( "ID" ) + 1 FROM "Table" WHERE "Time" = "a"."Time" ) = 1
This procedure can, within limits, be expressed in HSQLDB. The following example refers to a
table called Name with the fields ID, Firstname and Surname. The following query is first run on the
table and saved as a view called View_Group.
The New button in the LibreOffice Basic Macros dialog opens the New Module dialog, which asks
for the module name (the folder in which the macro will be filed). The name can be altered later if
desired.
As soon as this is given, the macro editor appears. Its input area already contains the Start and the
End for a subroutine:
REM ***** BASIC *****
Sub Main
End Sub
Macros in the PDF and ODT versions of this chapter are colored according to the
rules of the LibreOffice macro editor:
Macro designation
Macro comment
Note Macro operator
Macro reserved expression
Macro number
Macro character string
Improving usability
For this first category of macro use, we show various possibilities for improving the usability of
Base forms.
Filtering records
The filter itself can function perfectly well in the form described in Chapter 8, Database Tasks. The
variant shown below replaces the Save button and reads the listboxes again, so that a chosen filter
from one listbox can restrict the choices available in the other listbox.
SUB Filter
DIM oDoc AS OBJECT
DIM oDrawpage AS OBJECT
DIM oForm1 AS OBJECT
DIM oForm2 AS OBJECT
DIM oFieldList1 AS OBJECT
DIM oFieldList2 AS OBJECT
oDoc = thisComponent
oDrawpage = oDoc.drawpage
First the variables are defined and set to access the set of forms. This set comprises the two forms
"Filter" and "Display". The listboxes are in the "Filter" form and have the names "List_1" and
"List_2".
oForm1 = oDrawpage.forms.getByName("Filter")
oForm2 = oDrawpage.forms.getByName("Display")
oFieldList1 = oForm1.getByName("List_1")
oFieldList2 = oForm1.getByName("List_2")
First the contents of the listboxes are transferred to the underlying form using commit(). The
transfer is necessary, because otherwise the change in a listbox will not be recognized when
saving. The commit() instruction need only be applied to the listbox that has just been accessed.
After that the record is saved using updateRow(). In principle, our filter table contains only one
record, which is written once at the beginning. This record is therefore overwritten continuously
using an update command.
SQL formulas in macros must first be placed in double quotes like normal character
strings. Field names and table names are already in double quotes inside the SQL
formula. To create final code that transmits the double quotes properly, field names
and table names must be given two sets of these quotes.
Note
stSql = "SELECT ""Name"" FROM ""Table"";"
becomes, when displayed with the command msgbox stSql,
SELECT "Name" FROM "Table"
The index of the array, in which the field names are written is initially set to 0. Then the query
begins to be read out. As the size of the array is unknown, it must be adjusted continuously. That is
why the loop begins with 'ReDim Preserve arContent(inI)' to set the size of the array and
at the same time to preserve its existing contents. Next the fields are read and the array index
incremented by 1. Then the array is dimensioned again and a further value can be stored.
InI = 0
IF NOT ISNULL(oQuery_Result) THEN
WHILE oQuery_result.next
ReDim Preserve arContent(inI)
arContent(inI) = oQuery_Result.getString(1)
inI = inI + 1
WEND
END IF
stSql = "DROP TABLE ""Searchtmp"" IF EXISTS"
oSQL_Statement.executeUpdate (stSql)
Now the query is put together within a loop and subsequently applied to the table defined at the
beginning. All case combinations are allowed for, since the content of the field in the query is
converted to lower case.
The query is constructed such that the results end up in the Searchtmp table. It is assumed that
the primary key is the first field in the table (arContent(0)).
stSql = "SELECT """+arContent(0)+""" INTO ""Searchtmp"" FROM """ + stTable
+ """ WHERE "
FOR inK = 0 TO (inI - 1)
stSql = stSql+"LCase("""+arContent(inK)+""") LIKE '%"+stContent+"%'"
IF inK < (inI - 1) THEN
stSql = stSql+" OR "
END IF
NEXT
oSQL_Statement.executeQuery(stSql)
ELSE
stSql = "DELETE FROM ""Searchtmp"""
oSQL_Statement.executeUpdate (stSql)
END IF
The display form must be reloaded. Its data source is a query, in this example Searchquery.
oForm2 = oDrawpage.forms.getByName("Display")
oForm2.reload()
End Sub
This creates a table that is to be evaluated by the query. As far as possible, the query should be
constructed so that it can subsequently be edited. A sample query is shown:
Sub Toolbar_restore
DIM oFrame AS OBJECT
DIM oLayoutMng AS OBJECT
oFrame = thisComponent.CurrentController.Frame
oLayoutMng = oFrame.LayoutManager
oLayoutMng.visible = true
End Sub
When a toolbar is removed, all bars are affected. However as soon as a form control is clicked, the
menu bar reappears. This is a safety precaution so that the user does not end up in a jam. To
prevent constant toggling, the menu bar reappears.
Database compaction
This is simply a SQL command (SHUTDOWN COMPACT), which should be carried out now and
again, especially after a lot of data has been deleted. The database stores new data, but still
reserves the space for the deleted data. In cases where the data have been substantially altered,
you therefore need to compact the database.
Once compaction is carried out, the tables are no longer accessible. The file must be reopened.
Therefore this macro closes the form from which it is called. Unfortunately you cannot close the
document itself without causing a recovery when it is opened again. Therefore this function is
commented out.
SUB Database_compaction
DIM stMessage AS STRING
oDataSource = ThisComponent.Parent.CurrentController ' Accessible from
the form
IF NOT (oDataSource.isConnected()) THEN
oDataSource.connect()
END IF
oConnection = oDataSource.ActiveConnection()
oSQL_Statement = oConnection.createStatement()
stSql = "SHUTDOWN COMPACT" ' The database is being compacted and shut down
oSQL_Statement.executeQuery(stSql)
stMessage = "The database is being compacted." + CHR(13) + "The form will
now close."
stMessage = stMessage + CHR(13) + "Following this, the database file
should be closed."
stMessage = stMessage + CHR(13) + "The database can only be accessed after
reopening the database file."
msgbox stMessage
ThisDatabaseDocument.FormDocuments.getByName( "Maintenance" ).close
REM The closing of the database file causes a recovery operation when you
open it again.
' ThisDatabaseDocument.close(True)
END SUB
Dialogs
Input errors in fields are often only noticed later. Often it is necessary to modify identical entries in
several records at the same time. It is awkward to have to do this in normal table view, especially
when several records must be edited, as each record requires an individual entry to be made.
Forms can use macros to do this kind of thing, but to do it for several tables, you would need
identically constructed forms. Dialogs can do the job. A dialog can be supplied at the beginning
with the necessary data for appropriate tables and can be called up by several different forms.
The appearance of dialog controls is determined by the settings for the graphical user interface.
The dialog shown above serves in the example database to edit tables which are not used directly
as the basis of a form. So, for example, the media type is accessible only through a listbox (in the
macro version it becomes a combobox). In the macro version, the field contents can be expanded
by new content but an alteration of existing content is not possible. In the version without macros,
alterations are carried out using a separate table control.
While alterations in this case are easy to carry out without macros, it is quite difficult to change the
media type of many media at once. Suppose the following types are available: "Book, bound",
"Book, hard-cover", "Paperback" and "Ringfile". Now it turns out, after the database has been in
use for a long time, that more active contemporaries foresaw similar additional media types for
printed works. The task of differentiating them has become excessive. We therefore wish to reduce
them, preferably to a single term. Without macros, the records in the media table would have to be
found (using a filter) and individually altered. If you know SQL, you can do it much better using a
SQL command. You can change all the records in the Media table with a single entry. A second
SQL command then removes the now surplus media types which no longer have any link to the
Compacting a database
The behavior of HSQLDB is to preserve storage space for deleted records. Databases that are
filled with test data, especially if this includes images, retain the same size even if all these records
are subsequently deleted.
To free this storage space, the database records must be rewritten (tables, table descriptions, etc).
On the main Base interface, using Tools > SQL, you can directly enter a simple command (which
on server databases is only available to the system administrator):
SHUTDOWN COMPACT
The database is taken down and freed from all accumulated waste space. After this is done, Base
must be restarted in order to access the database.
Resetting autovalues
A database is created, all possible functions tested with examples, and corrections made until
everything works. By this time, on average, many primary key values will have risen to over 100.
Bad luck if the primary key has been set to auto-increment, as is commonplace! If the tables are
emptied in preparation for normal usage or prior to handing the database on to another person, the
primary key continues to increment from its current position instead of resetting itself to zero.
The following SQL command, again entered using Tools > SQL, lets you reset the initial value:
ALTER TABLE "Table_name" ALTER COLUMN "ID" RESTART WITH 'New value'
This assumes that the primary key field has the name "ID" and has been defined as an autovalue
field. The new value should be the one that you want to be automatically created for the next new
record. So, for example, if current records go up to 4, the new value should be 5.
Here the tables Address and Street are considered. All specified actions apply to the Address
table, which contains the foreign key Street_ID. Update options refer to an update of the ID field in
the Street table. If the numeric key in the "Street"."ID" field is altered, "No action" means that the
database resists this change if a "Street"."ID" with that key number occurs as a foreign key in the
Address table.
"Update cascade" means that the key number is simply carried over. If the street 'Burgring' in the
Street table has the ID '3' and is also represented in "Address"."Street_ID", the ID can be safely
In the form there is a built-in filter whose activation can tell you which categories are not needed in
the Media table. In the case just described, almost all the example authors are in use. Only the
Erich Kästner record can be deleted without any consequences for any other record in Media.
The filter is hard-coded in this case. It is found in the form properties. Such a filter is activated
automatically when the form is launched. It can be switched off and on. If it is deleted, it can be
accessed again by a complete reload of the form. This means more than just updating the data;
the whole form document must be closed and then reopened.
Effect of queries
It is just these queries, used in the previous section to filter data, that prove unsatisfactory in regard
to the maximum speed of searching a database. The problem is that in large databases, the
subquery retrieves a correspondingly large amount of data with which each single displayable
record must be compared. Only comparisons with the relationship IN make it possible to compare
a single value with a set of values. The query
… WHERE "ID" NOT IN (SELECT "Author_ID“ FROM "rel_Media_Author")
can contain a large number of possible foreign keys from the rel_Media_Author table, which must
first be compared with the primary keys in the table Authors for each record in that table. Such a
query is therefore not suitable for daily use but may be required for database maintenance. For
daily use, search functions need to be constructed differently so that the search for data is not
excessively long and does not damage day-to-day work with the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Number Upper case, A=0 B=1 etc. * Lower case, a=0 b=1 etc. +
Integers
Type Option HSQLDB Range Storage space
Tiny Integer TINYINT TINYINT 28 = 256 | - 128 bis 1 Byte
+ 127
Floating-point numbers
Type Option HSQLDB Range Storage space
Decimal DECIMAL DECIMAL Unlimited, up to 50 variable
places in the GUI,
fixed decimal point,
perfect accuracy
Time
Type Option HSQLDB Range Storage space
Date DATE DATE 4 Byte
Other
Type Option HSQLDB Range Storage space
Yes/No BOOLEAN BOOLEAN | BIT
Appendix 247
Built-in functions and stored procedures
Numeric
As we are dealing here with floating point numbers, be sure to take care with the settings of the
fields in queries. Mostly the display of decimal places is restricted, so that in some cases there may
be unexpected results. For example, column 1 might show 0.00 but actually contain 0.001, and
column 2, 1000. If column 3 is set to show Column 1 * Column 2, it would actually show 1.
BITAND(a,b) Both the binary form of a and the binary form of b must have 1 at the
same position to yield 1 in the result.
BITAND(3,5) yields 1; 0011 AND 0101 = 0001
BITOR(a,b) Either the binary form of a or the binary form of b must have 1 at the
same position to yield 1 in the result.
BITAND(3,5) yields 7; 0011 OR 0101 = 0111
CEILING(d) Returns the smallest whole number that is not smaller than d.
FLOOR(d) Returns the largest whole number that is not greater than d.
RAND() Returns a random number greater than or equal to 0.0 and less than
1.0.
ROUNDMAGIC(d) Solves rounding problems, that arise from using floating point
numbers. 3.11-3.1-0.01 is not exactly 0, but is shown as 0 in the GUI.
ROUNDMAGIC makes it an actual zero value.
Text
ASCII(s) Returns the ASCII code of the first letter of the string.
DIFFERENCE(s1,s2) Returns the sound difference between s1 and s2. Only a whole
number is output. 0 means they sound the same. So 'for' and 'four'
yield 0, ‘king’ and ‘wing’ yield 1, ‘see’ and ‘sea’ yield 0.
INSERT(s,start,len,s2) Returns a text string, with part of the text replaced. Beginning with
start, a length len is cut out of the text s and replaced by the text s2.
INSERT(Bundesbahn, 3, 4, mmel ) converts Bundesbahn into
Bummelbahn, where the length of the inserted text can be greater
than that of the deleted text without causing any problems. So
INSERT(Bundesbahn, 3, 5, s und B ) yields 'Bus und Bahn'.
LEFT(s,count) Returns the first count characters from the beginning of the text s.
LOCATE(search,s,[start]) Returns the first match for the term search in the text s. The match is
given as an offset number: (1=left, 0=not found)
Setting a starting point within the text string is optional.
Appendix 249
OCTET_LENGTH(str) Returns the length of a text string in bytes. This corresponds to twice
the length in characters.
REPLACE(s,replace,s2) Replaces all existing occurrences of replace in the text string s by the
text s2.
RIGHT(s,count) Opposite of LEFT; returns the last count characters at the end of a
text string.
RTRIM(s) Removes all spaces and non-printing characters from the end of a
text string.
SUBSTRING(s,start[,len]) Returns the text s from the start position (1=left). If length is left out,
the whole string is returned.
LOWER(s) As LCASE(s)
UPPER(s) As UCASE(s)
Date/Time
CURDATE() Returns the current date.
DAYOFMONTH(date) Returns the day of the month (1-31). Synonym for DAY()
NOW() Returns the current date and the current time together as a
timestamp. Alternatively CURRENT_TIMESTAMP can be used.
Database connection
Except for IDENTITY(), which has no meaning in Base, all these can be carried out using Direct
SQL Command.
DATABASE() Returns the name of the database to which this connection belongs.
IDENTITY() Returns the last value for an autovalue field, which was created in the
current connection. This is used in macro coding to transfer a primary
key in one table to become a foreign key for another table.
System
IFNULL(exp,value) If exp is NULL, value is returned, otherwise exp. Alternatively as an
extension COALESCE() can be used. Exp and value must have the
same data type.
COALESCE(expr1,expr2, If expr1 is not NULL, returns expr1, otherwise expr2 is checked, then
expr3,...) expr3 and so on.
Appendix 251
CASE WHEN expr1 THEN If expr1 is true, v1 is returned [optionally further conditions can be
v1[WHEN expr2 THEN v2] set]. Otherwise v4 is returned or NULL if there is no ELSE condition.
[ELSE v4] END
EXTRACT ({YEAR | Can replace many of the date and time functions. Returns the year,
MONTH | DAY | HOUR | the month, the day, etc. from a date or date/time value.
MINUTE | SECOND}
FROM <date or time>)
POSITION(<string If the first string is contained in the second one, the offset of the first
expression> IN <string string is given, otherwise 0 is returned.
expression>)
SUBSTRING(<string Yields part of a text string from the position specified in FROM,
expression> FROM optionally up to the length given in FOR.
<numeric expression>
[FOR <numeric
expression>])
Appendix 253
4. The database file must be decompressed. The most important information, as far as the
data is concerned, are in the subfolder database in the files data and script.
5. It may be necessary to look at the script file and test it for contradictions. This step can,
however, be left for the testing stage. The script file contains above all the description of
the table structure.
6. Create a new empty database file and open this file with the archiving program.
7. Replace the files data and script in the new database file with the files unpacked in step
4.
8. Close the archiving program. If it was necessary to rename the file to *.zip before opening it
in the archiving program (this depends on your operating system), now rename it again to
*.odb.
9. Open the database file in LibreOffice. You should be able to access your tables again.
10. How far your queries, forms, and reports can be recovered in a similar way must be the
subject of further testing.
See also: http://forum.openoffice.org/en/forum/viewtopic.php?f=83&t=17125
If, as described in the following pages, you are using external HSQLDB, there may be a further
problem with the *.odb file connected with some LibreOffice versions. If external HSQLDB is used,
the safest way is through the hsqldb.jar-archive, which is supplied with LibreOffice. If a different
archive is used, it can lead to the internal database suddenly becoming inaccessible. This is
because LibreOffice 3.x has difficulty distinguishing between internal and external HSQLDB and
produces warnings of an incompatibility between versions.
If internal databases can no longer be opened, you must use as your external database the
supplied hsqldb.jar file. In addition, you must extract from the *.odb file the database folder.
The properties file in this case has an entry that leads to the above error in LibreOffice:
version=1.8.1 on line 11
This line should be changed to:
version=1.8.0
Afterwards the database folder is put back into the *.odb package and the database can once more
be opened in LibreOffice.
If the database driver does not lie on the Java-Runtime path, it must be entered as a Class Path
under Tools > Options > Java.
The connection to the external database uses JDBC. The database file should be stored in a
particular directory. This directory can be freely chosen. In the following example it is in the home
folder. The rest of the directory path and the name of the database are not given here.
It is important, if data in the database are to be written using the GUI, that next to the database
name the words ";default_schema=true" are written.
So:
jdbc:hsqldb:file:/home/PathToDatabase/Databasename;default_schema=true
In the folder you will find the files:
Databasename.backup
Databasename.data
Databasename.properties
Databasename.script
Databasename.log
Appendix 255
The next step is to give the default user, if nothing in the HSQLDB configuration is to be changed:
server.database.0 file:data/db0
server.dbname.0 firstdb
server.urlid.0 db0-url
Appendix 257
server.database.1 file:data/union
server.dbname.1 union
server.urlid.1 union-url
server.silent true
server.trace false
server.port 9001
server.no_system_exit true
The database 0 is addressed with the name firstdb, although the individual files in the data
directory begin with db0. I added my own database as Database 1. Here the database name
and file begin identically.
The two databases are addressed in the following way:
jdbc:hsqldb:hsql://localhost/firstdb;default_schema=true
username sa
password
jdbc:hsqldb:hsql://localhost/union;default_schema=true
username sa
password
The suffix ;default_schema=true to the URL, which is necessary for write access using the
graphical user interface of LibreOffice, is permanently included.
If you actually need to work on the server, you will want to consider if the database needs to be
password-protected for security reasons.
Now you can connect to the server using LibreOffice.
With this access data, the server can be loaded on its own computer. On a network with other
computers, you must give either the host name or the IP address to the server, which in this case
is running on my computer.
Example: My computer has the IP 192.168.0.20 and is known on the network by the name
lin_serv. Now suppose there is another computer to be entered for connection to the database:
jdbc:hsqldb:hsql://192.168.0.20/union;default_schema=true
or:
jdbc:hsqldb:hsql://lin_serv/union;default_schema=true
The database is now connected and we can write into it. Quickly, however, an additional problem
appears. The previously automatically generated values are suddenly no longer incremented. For
this purpose we need an additional setting.
In LibreOffice the entry of autovalues using the GUI is not possible for this reason.
Users of these versions should first create a table with a primary key field that
does not auto-increment and then enter directly using Tools > SQL:
Note ALTER TABLE "Table_name" ALTER COLUMN "ID" INT GENERATED BY
DEFAULT AS IDENTITY(START WITH 0)
This assumes that the primary key field has the name ID.
Appendix 259
260 Base Handbook