SQL PROGRAMMING STYLE- P35 docx

5 139 0
SQL PROGRAMMING STYLE- P35 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

3.8 Put CHECK() Constraint Near what they Check 47 Exceptions: If your SQL product has a CREATE DOMAIN statement, you will include DEFAULT and CHECK() constraints in the domain declaration, so the use of the DOMAIN is enough. Multicolumn constraints on columns that are far apart should be moved to the end of the table declaration. This will give you one place to look for the more complex constraints, rather than trying to look all over the DDL statement. It can also be argued that none of this really matters, because most of the time we should be going to the schema information tables to retrieve the constraint definitions, not the DDL. Constraints may have been removed or added with subsequent ALTER statements, and the system catalog will have the correct, current state, whereas the DDL may not. 3.8.1 Consider Range Constraints for Numeric Values Rationale: The whole idea of a database is that it is a single trusted repository for all of the data in the enterprise. This is the place where the business rules must be enforced. The most common constraint on numbers in a data model is that they are not less than zero. Now look at actual DDL and see how often you find that constraint. Programmers are lazy and do not bother with this level of details. Exceptions: When the column really can take any value whatsoever. 3.8.2 Consider LIKE and SIMILAR TO Constraints for Character Values Rationale: Again, the whole idea of a database is that it is a single trusted repository for all of the data in the enterprise. This is the place where the business rules must be enforced. An encoding will have a format that can be validated with a LIKE or SIMILAR TO predicate. Now look at actual DDL and see how often you find that constraint. This is not as portable an option as numeric range checking, and many programmers who did not use UNIX in their youth have problems with regular expressions, but it is still important. Exceptions: When the column really can take any value whatsoever. 48 CHAPTER 3: DATA DECLARATION LANGUAGE 3.8.3 Remember That Temporal Values Have Duration There is no such thing as a point in time. You can ask Einstein or go back to the Greek philosopher Zeno and his famous paradoxes. Temporal values have duration, and you need to remember that they have a start and finish time, either explicitly or implicitly, that includes all of the continuum bound by them. The implicit model is a single column and the explicit model uses a pair of temporal values. For example, when you set a due date for a payment, you usually mean any point from the start of that day up to but not including midnight of the following day. When you say an employee worked on a given date, you usually mean the event occurred during an eight-hour duration within that day. Remember that you can use a DEFAULT CURRENT_TIMESTAMP on a temporal column and that a NULL can be used as a marker for “eternity” in the finish time column. A CHECK() constraint can round off time values to the start of the nearest year, month, day, hour, minute, or second as needed. 3.8.4 REAL and FLOAT Data Types Should Be Avoided Most commercial applications do not need floating-point math. SQL has NUMERIC and DECIMAL data types that can be set to a great deal of scale and precision and do not have floating-point numeric rounding errors. There will be exceptions for scientific and statistical data. 3.9 Put Multiple Column Constraints as Near to Both Columns as Possible Rationale: Do not make the reader have to look in multiple physical locations to find all of the columns involved in the constraint. You do not have to indent this constraint, but it is a good idea to split it on two lines: one with the CONSTRAINT clause and one with the CHECK() clause. CREATE TABLE Prizes ( birth_date DATE NOT NULL, prize_date DATE NOT NULL, CONSTRAINT over_18_to_win CHECK (birth_date + INTERVAL 18 YEARS >= prize_date), ); 3.11 Use CREATE ASSERTION for Multi-table Constraints 49 Exceptions: This is not always physically possible, especially when many columns are involved. 3.10 Put Table-Level CHECK() Constraints at the End of the Table Declaration Rationale: These constraints are not yet well supported in SQL products, but they are legal SQL-92 syntax. Their predicates involve the entire table as a whole rather than just single rows. This implies that they will involve aggregate functions. CREATE TABLE Prizes ( CONSTRAINT only_5_prizes_each_winner CHECK (NOT EXISTS (SELECT * FROM Prizes AS P1 GROUP BY P1.contestant_id HAVING COUNT(*) > 5)), CONSTRAINT no_missing_ticket_nbrs CHECK ((SELECT MAX(ticket_nbr) - MIN(ticket_nbr) + 1 FROM Prizes AS P1) = (SELECT COUNT(ticket_nbr) FROM Prizes AS P1)); Exceptions: None 3.11 Use CREATE ASSERTION for Multi-table Constraints Rationale: Put multiple table CHECK() Constraints in CREATE ASSERTION statements rather than on a table declaration. These constraints are not yet well supported in SQL products, but they are legal SQL-92 syntax. Their predicates involve several different tables, not just one table. This implies that they are at a higher level and should be modeled there. The practical consideration is that all constraints are TRUE on an empty table, so the CREATE ASSERTION 50 CHAPTER 3: DATA DECLARATION LANGUAGE statement lets you control that possibility. The assertion name acts as the constraint name. CREATE ASSERTION enough_money_to_pay_prizes AS CHECK ((SELECT SUM(prize_money) FROM Prizes AS P1) <= (SELECT SUM(cash_on_hand) FROM Bank)); Exceptions: If the SQL product does not support CREATE ASSERTION statements, then this cannot be done, but if it were possible, then violation would require a strong reason having to do with the schema design. 3.12 Keep CHECK() Constraints Single Purposed Rationale: Put simple CHECK() constraints in their own clauses rather than writing one long constraint with multiple tests. When you give a constraint a name, that name will appear in error messages and can help the user to correct data. If all of the validation is in one single CHECK() clause, what name would you give it? For example, imagine a single validation for a name that looks for correct capitalization, extra spaces, and a length over five characters. About all you can call it is “bad address line” and hope the user can figure out how to fix it. However, if there were separate checks for capitalization, extra spaces, and a length over five characters, then those constraint names would be obvious and give the user a clue as to the actual problem. Exceptions: If your SQL product supports the SIMILAR TO predicate (a version of grep() based on the POSIX standard in Standard SQL), then you might consider having a longer regular expression with OR-ed patterns that fall under a general constraint name. If you do not want to give details about errors to users for security reasons, then you can use a single constraint with a vague name. This would be a strange situation. 3.13 Every Table Must Have a Key to Be a Table 51 3.13 Every Table Must Have a Key to Be a Table Rationale: This is the very definition of a table. The problem is that many newbies do not understand what a key really is. A key must be a subset of the attributes (columns) in the table. There is no such thing as a universal, one-size-fits-all key. Just as no two sets of entities are the same, the attributes that make them unique have to be found in the reality of the data. God did not put a 17-letter Hebrew number on the bottom of everything in creation. Here is my classification of types of keys (Table 3.1). 1. A natural key is a subset of attributes that occurs in a table and acts as a unique identifier . The user sees them. You can go to the external reality and verify them. You would also like to have some validation rule. Example: UPC codes on consumer goods are easily seen (read the package bar code), and you validate them with a scanner, a manual-check digit calculation, or a manufacturer’s Web site. 2. An artificial key is an extra attribute added to the table that is seen by the user . It does not exist in the external reality but can be Table 3.1 Types of keys Natural Key Artificial Key Exposed Locator System Surrogate Constructed from Reality of the Data Model YesNoNoNo Verifiable in Reality Yes No, trusted source No No Validation in Itself Yes Yes, check digit, syntax | No No Portable to New Platform Yes Yes No No Visible to the User Yes Yes Yes No, and can be changed by engine . Table Declaration Rationale: These constraints are not yet well supported in SQL products, but they are legal SQL- 92 syntax. Their predicates involve the entire table as a whole rather than. rather than on a table declaration. These constraints are not yet well supported in SQL products, but they are legal SQL- 92 syntax. Their predicates involve several different tables, not just one. the actual problem. Exceptions: If your SQL product supports the SIMILAR TO predicate (a version of grep() based on the POSIX standard in Standard SQL) , then you might consider having a longer

Ngày đăng: 06/07/2014, 23:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan