I have two fields "zipfrom" and "zipto" in one table. I want to compare another two fields (user-entered) with...
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
these fields to validate that the user-entered zip range is unique in the table. For example,
Table zipfrom zipto 51000 52000
If the user enters 51150-51175 then we should return error that this range is already entered.
In the example you've given, the codes 51150-51175 represent a range of numbers that lie completely within the range 51000-52000. I shall assume that you also want to issue an error if the user-entered range overlaps an existing range at either end. These three conditions are illustrated below, where X------X is an existing range already in the database, and A----A, B----B, and C----C are ranges for which you want to issue an error --
X----------X A----A B-------B C------C
You can check all three of these conditions by noting that at least one of the endpoints of a "bad" user-entered range is within the existing range --
create table zipranges ( zipfrom char(5) , zipto char(5) , constraint rangecheck1 check ( not exists ( select * from zipranges XX where zipfrom between XX.zipfrom and XX.zipto or zipto between XX.zipfrom and XX.zipto ) ) );
However, not every database is going to let you declare a constraint that way, with a subquery. At worst you would have to write some programming logic to perform the NOT EXISTS test before deciding to insert. Another problem with this type of check constraint, as pointed out by Joe Celko on page 160 of SQL Puzzles & Answers (ISBN 1-55860-453-7), is that you will have trouble inserting an initial row into an empty table.
There's one more problem, too. What if the user enters a range that spans an existing range?
This, too, can be covered by a check constraint --
, constraint rangecheck2 check ( not exists ( select * from zipranges YY where zipfrom < YY.zipfrom and zipto > YY.zipto ) )
For More Information
- What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.