646 CHAPTER 28 FROM DATABASES TO DATATYPES (Web site traffic)

646 CHAPTER 28 FROM DATABASES TO DATATYPES this sounds complicated, it isn t especially, and domains can be quite useful when applied properly. One good example is handling phone numbers. Many databases have a phone number column in several of their tables, which then requires each table to set up its own constraints to handle the data. Rather than go through that hassle, you could instead create a domain to handle phone numbers and then use that in all of your tables. Creating Domains Domains are created by using the CREATEDOMAIN command. Domains generally comprise a set of attributes, CHECK, DEFAULT, NOTNULL, or NULL, that behave like other datatype attributes within PostgreSQL. In this example, we set up a domain to match a valid U.S. phone number, which we define as starting with 1, followed by a dash, three numbers, another dash, three more numbers, a third dash, and then four numbers: CREATE DOMAIN us_phone_number AS TEXT CONSTRAINT “valid_phone_number” CHECK (VALUE ~ ‘^1-\d{3}-\d{3}-\d{4}$’); CREATE TABLE us_contact_info ( fullname TEXT NOT NULL, email TEXT NOT NULL, phone us_phone_number NOT NULL ); As you can see, writing the regular expression once in the domain is much simpler than writing this expression several times in multiple tables. This also gives us one place to change should we need to modify our phone number definition. Altering Domains You can use the ALTERDOMAIN command to modify any aspect of a domain s definition. Each form of the ALTERDOMAINcommand takes the form of ALTERDOMAINdomain_name followed by one of the following subforms: { SET DEFAULT expression | DROP DEFAULT }: Sets expression as the default value or drops the existing default value. { SET | DROP } NOT NULL: Controls whether or not the domain allows NULL values. ADD domain_constraint: Adds a new constraint to the domain using the same syntax as the CREATEDOMAIN command. It will succeed only if all values in an existing column satisfy the new constraint. DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ]: Drops constraints on a domain. OWNER TO new_owner: Changes the ownership of the domain. Using these commands should be fairly straightforward, but just to make sure, let s walk through a few examples. This command would forbid someone from entering NULL values into our DOMAIN:
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Leave a Reply