Database table model advice - database

I am making a Django web app and need help designing the a table within the DB.
I am to insert into the table an employee with a specific employee ID. Lets say there are three employees with the IDs (15039, 98443, 29234). Would the employee ID be the primary key or do I have to make some arbitrary column starting from 1 the primary id with employee id as a standalone column?
In a sense what I am i asking is if the 15039, 98443, and 29234 employees were inserted into the table with empl ID being primary key which order would the DMBS order them?

You did not specify which database you will use, but most likely the primary key will be the clustered index, in which case the database will order the rows by that id.
Many argue you should always create an auto-increment artifical primary key, and that usually saves you a lot of pain in the long run.
However, if you know the value will always be unique and you won't ever need to change the value, you can opt to use it as the PK for the table.

Related

Should primary key be used on a table that has only 2 columns, both are unique

If I have a table like the Following
CustomerAddress(CustomerId, AddressId)
Would I still need an additional primary key, e.g., int auto increment? Or would setting both the columns as primary keys be sufficient?
ASSUMPTION: When deleting, I will only delete by customerId, never by both customerId and AddressId
I suggest you to keep a primary key. Though it is not useful for now, it might be useful in future. May be the combination customerid and addressid could have new field like current_address_flag. And its just about creating a field that is almost manipulated by the DB system.
It seems this is a join table. In this case, I'd have a cascading delete between the dependent objects, e.g. when a customer is deleted, all customerAddresses belonging to said customer are also deleted.

How do I properly created a 1 to many relationship in my database?

If I have the following tables (with PKs in brackets)...
Store { [StoreCode], PhoneNumber, Address, ...}
StoreHours { [id], DayofWeek, Open, Close, ClosedDate }
Now my thinking is every store wont have the same hours & they wont have the same hours everyday, and instead of making multiple columns in the Store table such as, "OpenTimeA, OpenTimeB, OpenTimeC, CloseTimeA, CloseTimeB, ...", then I could create a relationship table. However, I'm not used to doing them and want to go ahead and get it right the first time. Here's what I was thinking of adding to the above tables...
Has_a { [StoreCode, id ] }
My questions are if I do it this way...
Is there a better way to name the table than Has_a or can I name it that and use it for multiple different types of relationships for the store. For instance, add another table Managers and add a column to the Has_a table for manager ids.
like...
StoreInformation { [StoreCode], TimeId, ManagerId, ...}
For the first question, one possible solution is (standard 1-to-many relationship):
Store
StoreCode
PhoneNumber
Address
...
PRIMARY KEY (StoreCode)
StoreHours
StoreCode
DayOfWeek
OpenTime
CloseTime
PRIMARY KEY (StoreCode, DayOfWeek)
FOREIGN KEY (StoreCode)
REFERENCES Store(StoreCode)
If you notice that you have many Stores that open and close at the same times, all days of the week, you can add a Schedule table, so multiple Stores can share the same Schedule.
Store
StoreCode
ScheduleId
PhoneNumber
Address
...
PRIMARY KEY (StoreCode)
FOREIGN KEY (ScheduleId)
REFERENCES Schedule(ScheduleId)
Schedule
ScheduleId
ScheduleTitle
PRIMARY KEY (ScheduleId)
ScheduleHours
ScheduleId
DayOfWeek
OpenTime
CloseTime
PRIMARY KEY (ScheduleId, DayOfWeek)
FOREIGN KEY (ScheduleId)
REFERENCES Schedule(ScheduleId)
The biggest problem with creating a generic Has_a table for tracking these sorts of relationships is the fact that you will not be able to use a foreign key relationship between your tables, since you can only relate a single source table to a single destination table. In addition to that, unless your using GUIDs for your keys, there is no way to know which table a particular key belongs to, so you are likely to get bogus results.
Also, for a one to many relationship this sort of intermediate table is not needed. You can add a StoreCode column to your StoreHours table with the appropriate foreign keys. The only case where you need the intermediate tables are many-to-many relationships, which is probably not needed in this case (unless you want to have multiple stores share the same StoreHours record).

When Developing the database then compolsury to define the primary key or forign key in each tables of the database?

When Developing the database then compolsury to define the primary key or forign key in each tables of the databse if any tables that do not contain any unique field that time how can we connect the table with other table.
Suppose i have three tabe.
table1 Personel Detail
Emai_Address (PK)
Name
City
ContactNo
Land_Line_No
D_O_B
Gender
Marital_Status
Language_Known
Table2 Professiona_Detail
Total_Experiance
Annual_Salary
Functional_Area
Current_Industry
Key_Skill
Resume_HeadLine
Table3 WorkPreference
Specify Your Preference
Start Working
Prefered Location
Job Type
The Obove Table1 contain the PK but Table2 or Table 3 does not contain any Pk Or FK then how can connect this three table.
No. It's not compulsory. But HIGHLY recommended!
Some SQL guru once said:
If it doesn't have a primary key, it's not a table!
Live by that statement!
And foreign keys will make your database more secure, and avoid "zombie" rows. Again: it's not compulsory or technically necessary by all means, but you'll get yourself into trouble if you don't know it right from the start! Trust me.... been there, cleaned up that mess......
Table2 and Table3 should have a FK to Table1. Otherwise you will not know what person the records in those tables are for. Each table should also have a PK defined for it. This is so that you can uniquely identify a row when doing UPDATES or DELETES.
There is nothing that will enforce primary/foreign keys apart from you as a developer.
They are not compulsary, but are best practice and should be created.
When Developing modelling the database then compolsury to define the primary key or forign key in each tables of the databse if any tables that do not contain any unique field that time how can we connect the table with other table.
(1) Yes.
You are experiencing complications and difficulties at step 6 because you have not completed step 5. The steps have to be followed in sequence.
A Relational Database requires that the rows (not the identity column) in each table are unique. It is compulsory. If the rows are not unique, it is not a Relational table, it is something else, a bucket of fish.
After that FKs, etc will be easy. before that, FKs etc will be impossible.
(2) You already have a very good, stable unique Identifier for Person. The Professional and WorkPreference tables are missing a column or two. They do not sit out their on their own. Who or what does Professional and WorkPreference apply to ?
They belong to a Person. The only Person Identifier you have so far is EmailAddress. So EmailAddress needs to be added to Professional and WorkPreference.
EmailAddress is the PK in Professional and WorkPreference.
EmailAddress is also the FK in Professional and WorkPreference to Person. (So far the cardinality is 1::1.)
(3) Now you may also need an Unique Constraint on Person.Name, but then you have to deal with two "Bob Smith" and "Bob Smith" vs "Smith, Bob" vs "Robert Smith". So there is still some work to do there. If it is a simple database it may not matter Person.Name may be good enough.
That is it, the task is complete at the logical level.
(4) Now at the physical level (elements that the user does not see), you may decide that carrying the CHAR(30) EmailAddress in the child tables is not sensible for performance reasons, so you may add a narrow Surrogate Key to Person, such as PersonId INT. A Surrogate Key is always an additional column and index; it is not a substitution for the natural keys; you still need EmailAddress UNIQUE as the natural key that maintains uniqueness of rows.
Then you can use PersonId as the PK in Person.
Then you migrate PersonId as the FK and PK to Professional and WorkPreference; instead of EmailAddress.
But you cannot give up Person.EmailAddress UNIQUE, because that is the basis of maintaining unique rows in Person.

Creating relationships between tables

My question specifically about sql-server, but probably can be answered by anyone with any database background
If I want table A to have a 1:1 relationship with table B on a certain column, should I somehow modify the CREATE TABLE statement to identify this relationship or is this something that is not done at all (and rather it is handled by logic)?
EDIT
The second part of my question is: what is the point of embedding this into the code? why not just handle it logically on selects/updates?
All you need to do is have the column in Table A be a foreign key to the primary key of Table B:
create table TableB (
Id int primary key identity(1,1),
Name varchar(255))
create table TableA (
Id int primary key identity(1,1),
Name varchar(255),
TableBRelation int unique,
foreign key (TableBRelation) references TableB (Id))
The SQL may not be perfect but you should be able to get the idea.
As for why you would want to do this in the database rather than just application logic:
Other databases or developers may try to access your database. Do you want them to be able to create invalid data that may break your application? No. That's one of the points of referential integrity.
At some point, somebody is going to have to maintain your application. Defining your keys at the database level will clearly identify relationships between your data rather than requiring the develop to dig through your application code.
To create a 1:1 relationship just make the B table column a foreign key or unique. This will ensure that there can be only one column in table B that matches the PK field in table A and that way you effectively get a 1:1 relationship...
You can setup a foreign key and add a constraint for it to be unique. This would setup a 1:1 relationship between your tables.

How I can make Recycle Bin for Database Application?

I have database application, I want to allow the user to restore the deleted records from the database, like in windows we have Recycle bin for files I want to do the same thing but for database records, Assume that I have a lot of related tables that have a lot of fields.
Edit:
let's say that I have the following structures:
Reports table
RepName primary key
ReportData
Users table
ID primary key
Name
UserReports table
RepName primary key
UserID primary key
IsDeleted
now if I put isdeleted field in UserReports table, the user can't add same record again if it marked as deleted, because the record is already and this will make duplication.
Note: I always use surrogate primary key.
Add a timestamp 'deleted_at' column. When user deletes entry put there current time. Make this key part of your constrain.
In every query remember to search only for records that have null in deleted_at field.
Some frameworks (like ActiveRecord) make it trivial to do.

Resources