Constraints
We can constrain the type, values, and other forms of the data entered into a field. A special type of constraint, called a key, which was discussed in the previous section. PostgreSQL provides three other types of constrains: 'unique', 'check', and 'exclude'. A unique constraint allows you to specify a set of fields that should contain data where every row has different values and is therefore unique from those same fields in all other rows. This functionality is covered by keys and there are not so many other uses for the unique constraint on an archaeological project. The exclude constraint is more complex and will not often be used by archaeologists. The check constraint is very useful, on the other hand. You can use operators such as < to check the data entered against some predetermined condition.
Here are some common operators:
- < less than
- > greater than
- <= less than or equal to
- >= greater than or equal to
- <> not equal
- = equal
- is not null (this verifies that data exists in a field)
Finally, we go to Libreoffice Base in order to test all of these constraints by entering data into the contexts table. You need to save the row in order to test the constraint, you can do this by leaving the row. If you get completely stuck, you can use the undo button to get yourself out of the situation.
Note that you can add constraints to a table after you have already entered data into that table. However, if any of the existing data violates the constraint, you will not be able to save or apply that constraint. You would first need to change the data in the table and then save the constraint.
Exercise: Add Constraints to your Tables
Add constraints to all three tables. Add the constraints shown above to the contexts table, but also develop them further. We should probably prevent people from entering dates too far in the future. We should also check to make sure that an open date has been entered before a close date is entered (hint: use the 'is not null' operator). We might want to constrain the bottom elevation, and remember that a top elevation should be entered before a bottom elevation since we dig down. Add any additional constraints you can think of to the areas and contexts table. In the samples table, we should probably prevent negative counts and weights. What other constraints can we add?Test all of your constraints by adding at least two rows of data to each table, using the Libreoffice Base interface.
This page has paths:
- Relational Databases for Archaeology Peter Cobb