473,383 Members | 1,762 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Constraints and primary keys

I am interested in informed feedback on the use of Constraints, Primary Keys
and Unique.
The following SQL statement creates a Bands tables for a database of
bookings Bands into Venues, where the rule of the business is that only band
plays on the one night.
The SQL statement prevents a Band name being repeated (as it is Unique).
Similar statement for the Venues.
CREATE TABLE Bands
(BandID varchar(5) CONSTRAINT BandID PRIMARY KEY,
Band varchar(15) CONSTRAINT BandName UNIQUE,
State varchar(3) NOT NULL);

The SQL statement for the Bookings follows - where a Venue having two bands
on the same day is prevented by the constraint in the last line.
CREATE TABLE Bookings
(VenueID varchar(5),
BandID varchar(5),
BookingsDate datetime,
StartingTime datetime,
CONSTRAINT VenueSameDay UNIQUE (VenueID, BookingsDate);

I am after any feedback on the concepts of primary key, constraints, unique
(and not null). Is a constraint a key? Or am I in the ballpark to suggest
one constraint is a primary key, but there others, i.e. unique. Or does one
call a unique constraint a key/primary key?
And in Microsoft Access, I have for years seen this implemented by having a
multiple field primary key - in this case Venue ID and BookingsDate and no
one seemed to be aware of the Constraint clause - which seems a better
implementation. One reason for so - is that one can also implement another
one, eg.
CONSTRAINT BandSameDay UNIQUE (BandID, BookingsDate)

And composite primary keys? not sure where this fits in.

Peter
Disclaimer: bands and venues would more often have than not have more than
one per night. Sure.
Make it
CONSTRAINT VenueSameDayTime UNIQUE (VenueID, BookingsDate, BookingsTime)
then.

Jun 11 '07 #1
4 3802
On Jun 11, 7:15 am, "Peter" <ptdsmitch...@bigpond.comwrote:
I am interested in informed feedback on the use of Constraints, Primary Keys
and Unique.
The following SQL statement creates a Bands tables for a database of
bookings Bands into Venues, where the rule of the business is that only band
plays on the one night.
The SQL statement prevents a Band name being repeated (as it is Unique).
Similar statement for the Venues.
CREATE TABLE Bands
(BandID varchar(5) CONSTRAINT BandID PRIMARY KEY,
Band varchar(15) CONSTRAINT BandName UNIQUE,
State varchar(3) NOT NULL);

The SQL statement for the Bookings follows - where a Venue having two bands
on the same day is prevented by the constraint in the last line.
CREATE TABLE Bookings
(VenueID varchar(5),
BandID varchar(5),
BookingsDate datetime,
StartingTime datetime,
CONSTRAINT VenueSameDay UNIQUE (VenueID, BookingsDate);

I am after any feedback on the concepts of primary key, constraints, unique
(and not null). Is a constraint a key? Or am I in the ballpark to suggest
one constraint is a primary key, but there others, i.e. unique. Or does one
call a unique constraint a key/primary key?
And in Microsoft Access, I have for years seen this implemented by having a
multiple field primary key - in this case Venue ID and BookingsDate and no
one seemed to be aware of the Constraint clause - which seems a better
implementation. One reason for so - is that one can also implement another
one, eg.
CONSTRAINT BandSameDay UNIQUE (BandID, BookingsDate)

And composite primary keys? not sure where this fits in.

Peter
Disclaimer: bands and venues would more often have than not have more than
one per night. Sure.
Make it
CONSTRAINT VenueSameDayTime UNIQUE (VenueID, BookingsDate, BookingsTime)
then.
I agree that constraints are potentially useful and that they have
been glossed over because Microsoft didn't give them much emphasis.
This idea seems much better than enforcing uniqueness with a composite
primary key. I like it more from a performance and ease of query
creation standpoint because it allows an autonumber primary key to
proxy for a composite one, but I'll try to stay aware of the benefits
afforded by the possibility of multiple constraints. My programming
style is to check for conditions whenever possible rather than use
error handling to detect violations so a composite key or other
enforcement mechanism is required to ensure that something wrong can't
happen while the check is being made. I.e., the constraint becomes my
safety net for rare multiuser situations. I have a very large number
of concurrent users and ended up using many unbound forms. My
approach is definitely not the norm but even from my unique
perspective constraints are potentially useful for protecting data
integrity in a way that doesn't increase the complexity of the SQL I
have to maintain. My usage is a single facet of the topic you
breach. I hope others will address your questions also.

James A. Fortune
CD********@FortuneJames.com

Jun 11 '07 #2
If there is only one unique key on table then I would prefer that it
be defined as a primary key. In most graphical representations,
Access shows primary key field emboldened. It is a useful reminder.

That said, I am not keen on using a composite keys - be they
designated 'primary' or 'unique' - in joins. If I have a choice, I
would add an autonumber field as the primary key to a table which
would otherwise have a composite primary key. The composite key is
then defined using a unique constraint or, more usually for me, by
defining a unique index. Any foreign key referencing the table can
then use the autonumber primary key.

Think about, for example, a new table to list the songs to be
performed at each Booking. As you have it, without the addition of an
autonumber primary key, it would likely have a composite foreign key
reference to the Booking table. Consider next, what happens if a
Booking has to be postponed due to some emergency or other. It will
get a bit tricky doing all the updates, particularly if you have
enforced referential integrity. Doesn't make any difference whether
you have use 'unique' or 'primary key' to define the constraint. Its
the subsequent composite foreign key join that is nasty. With an
additional autonumber primary key on the Booking table, just one row
need be updated. Much easier.
Jun 11 '07 #3
In article <11**********************@p77g2000hsh.googlegroups .com>, breadon101
@yahoo.co.uk says...
If there is only one unique key on table then I would prefer that it
be defined as a primary key. In most graphical representations,
Access shows primary key field emboldened. It is a useful reminder.

That said, I am not keen on using a composite keys - be they
designated 'primary' or 'unique' - in joins. If I have a choice, I
would add an autonumber field as the primary key to a table which
would otherwise have a composite primary key. The composite key is
then defined using a unique constraint or, more usually for me, by
defining a unique index. Any foreign key referencing the table can
then use the autonumber primary key.

Think about, for example, a new table to list the songs to be
performed at each Booking. As you have it, without the addition of an
autonumber primary key, it would likely have a composite foreign key
reference to the Booking table. Consider next, what happens if a
Booking has to be postponed due to some emergency or other. It will
get a bit tricky doing all the updates, particularly if you have
enforced referential integrity. Doesn't make any difference whether
you have use 'unique' or 'primary key' to define the constraint. Its
the subsequent composite foreign key join that is nasty. With an
additional autonumber primary key on the Booking table, just one row
need be updated. Much easier.
Once set up, Access query designer takes care of the joins.

One person's nastiness is another person's beauty.

This is not anything real, but is just to show composite primary keys.
Sub createTables()

With CurrentProject.Connection

'.Execute _
"CREATE TABLE Bands" & _
" (band_nbr VARCHAR (10) NOT NULL," & _
" band_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_Bands" & _
" PRIMARY KEY (band_nbr));"

'.Execute _
"CREATE TABLE Customers" & _
" (customer_nbr VARCHAR (10) NOT NULL," & _
" customer_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_customers" & _
" PRIMARY KEY (customer_nbr));"

'.Execute _
"CREATE TABLE Locations" & _
" (location_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_locations" & _
" PRIMARY KEY (location_name));"

'.Execute _
"CREATE TABLE Bookings" & _
" (band_nbr VARCHAR (10) NOT NULL," & _
" customer_nbr VARCHAR (10) NOT NULL," & _
" booking_date DATETIME NOT NULL," & _
" location_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_bookings" & _
" PRIMARY KEY (band_nbr, customer_nbr, booking_date)," & _
" CONSTRAINT uq_no_duplicate_bookings" & _
" UNIQUE (band_nbr, booking_date)," & _
" CONSTRAINT fk_band_nbr_bookings" & _
" FOREIGN KEY (band_nbr)" & _
" REFERENCES Bands (band_nbr)" & _
" ON DELETE CASCADE ON UPDATE CASCADE," & _
" CONSTRAINT fk_customer_nbr_bookings" & _
" FOREIGN KEY (customer_nbr)" & _
" REFERENCES Customers (customer_nbr)" & _
" ON DELETE CASCADE ON UPDATE CASCADE," & _
" CONSTRAINT fk_location_name_bookings" & _
" FOREIGN KEY (location_name)" & _
" REFERENCES Locations (location_name)" & _
" ON DELETE CASCADE ON UPDATE CASCADE);"

'.Execute _
" CREATE TABLE BookingSongs" & _
" (band_nbr VARCHAR (10) NOT NULL," & _
" customer_nbr VARCHAR (10) NOT NULL," & _
" booking_date DATETIME NOT NULL," & _
" song_title VARCHAR (100) NOT NULL," & _
" play_sequence INTEGER DEFAULT 1 NOT NULL," & _
" CONSTRAINT pk_bookingsongs" & _
" PRIMARY KEY (band_nbr,customer_nbr," & _
" booking_date, song_title, play_sequence)," & _
" CONSTRAINT fk_bookings_bookingsongs" & _
" FOREIGN KEY (band_nbr, customer_nbr, booking_date)" & _
" REFERENCES Bookings (band_nbr, customer_nbr, booking_date)" & _
" ON UPDATE CASCADE);"

End With

End Sub
Jun 12 '07 #4
On Jun 11, 8:17 pm, Mike Gramelspacher <grame...@psci.netwrote:
Sub createTables()

With CurrentProject.Connection

'.Execute _
"CREATE TABLE Bands" & _
" (band_nbr VARCHAR (10) NOT NULL," & _
" band_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_Bands" & _
" PRIMARY KEY (band_nbr));"

'.Execute _
"CREATE TABLE Customers" & _
" (customer_nbr VARCHAR (10) NOT NULL," & _
" customer_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_customers" & _
" PRIMARY KEY (customer_nbr));"

'.Execute _
"CREATE TABLE Locations" & _
" (location_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_locations" & _
" PRIMARY KEY (location_name));"

'.Execute _
"CREATE TABLE Bookings" & _
" (band_nbr VARCHAR (10) NOT NULL," & _
" customer_nbr VARCHAR (10) NOT NULL," & _
" booking_date DATETIME NOT NULL," & _
" location_name VARCHAR (100) NOT NULL," & _
" CONSTRAINT pk_bookings" & _
" PRIMARY KEY (band_nbr, customer_nbr, booking_date)," & _
" CONSTRAINT uq_no_duplicate_bookings" & _
" UNIQUE (band_nbr, booking_date)," & _
" CONSTRAINT fk_band_nbr_bookings" & _
" FOREIGN KEY (band_nbr)" & _
" REFERENCES Bands (band_nbr)" & _
" ON DELETE CASCADE ON UPDATE CASCADE," & _
" CONSTRAINT fk_customer_nbr_bookings" & _
" FOREIGN KEY (customer_nbr)" & _
" REFERENCES Customers (customer_nbr)" & _
" ON DELETE CASCADE ON UPDATE CASCADE," & _
" CONSTRAINT fk_location_name_bookings" & _
" FOREIGN KEY (location_name)" & _
" REFERENCES Locations (location_name)" & _
" ON DELETE CASCADE ON UPDATE CASCADE);"

'.Execute _
" CREATE TABLE BookingSongs" & _
" (band_nbr VARCHAR (10) NOT NULL," & _
" customer_nbr VARCHAR (10) NOT NULL," & _
" booking_date DATETIME NOT NULL," & _
" song_title VARCHAR (100) NOT NULL," & _
" play_sequence INTEGER DEFAULT 1 NOT NULL," & _
" CONSTRAINT pk_bookingsongs" & _
" PRIMARY KEY (band_nbr,customer_nbr," & _
" booking_date, song_title, play_sequence)," & _
" CONSTRAINT fk_bookings_bookingsongs" & _
" FOREIGN KEY (band_nbr, customer_nbr, booking_date)" & _
" REFERENCES Bookings (band_nbr, customer_nbr, booking_date)" & _
" ON UPDATE CASCADE);"

End With

End Sub
Thanks for the detailed example. The joins will indeed be elegant.

James A. Fortune
CD********@FortuneJames.com
Jun 13 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Saqib Ali | last post by:
I have created 2 tables in my MySQL database. A_TAB and B_TAB. They have auto-incrementing integer primary keys respectively named A_ID & B_ID. When I created B_TAB, I declared a field named A_ID...
1
by: jason_s_ford | last post by:
I have several sql server databases that were recently moved to a new server. In the process of migrating the databases, any triggers and constraints attached to tables were removed on accident. ...
10
by: serge | last post by:
I am doing a little research on Google about this topic and I ran into this thread: ...
4
by: Dave D | last post by:
Hi - I would like to know how the following task is accomplished: Updating the Primary Key in the parent table when there are other tables that reference this Key(Foreign Key) Is there a way...
8
by: wespvp | last post by:
I am using PostgreSQL 7.4.1 on RedHat 7.2. The query I am executing is something like (I replaced all the return values with 'count'): db=> explain select count(*) from messages m join (select...
2
by: Benjamin Smith | last post by:
I have two tables like following: create table attendancereport ( id serial unique not null, staff_id integer not null references staff(id), schoolyear varchar not null references...
3
by: Oleg Lebedev | last post by:
Greetings. Is it possible to modify a foreign key constraint and force it to cascade on update? If there is no such SQL command, then is it possible to update some system tables to accomplish...
4
by: srikanthr | last post by:
how do i get the constraints associated with a table. is there any system table which stores the constraint details. Atleast how do I know if a column is nullable or not
6
by: Emin | last post by:
Dear Experts, When I use a single table I can easily use constraints to enforce my business logic, but what do I do when I normalize a single table into multiple tables. For example, imagine...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.