Designing Tables for a postgreSQL Database System
From theory to practice The Entity-Relationship model: a convenient way of representing the world. The Relational model: a model for organizing data using tables. postgreSQL: a database infrastructure which implements the relational model. Converting ER->Relational model is important! SQL(Structured Query Language): A language used to get information from a database.
psql In order to connect to the postgreSQL database, we use the psql terminal In order to connect to it, print the following command in your shell: psql –hdbserver public This will give you access to “your” database
A few useful commands \q exit psql \h [command] help about ‘command’ \d [name] describe table/index/… called ‘name’ \dt list tables \di list indexes \dv list views \df list functions
Reminder The database is kept on the disk, so anything you create will be there next time you log on. sailors Reserves Main Memory DISK CPU
Running Commands from an .sql File Instead of typing commands into the psql terminal, you can load commands from a file (no special format is required). The file name should end with “.sql” Invoke by: \i fileName
Tables The basic element in postgreSQL is a table. A table has columns (attributes), and rows (tuples). Every column has a Name and Type (of the data it stores), and some columns have constraints. Some tables may have additional constraints.
Creating Tables in SQL Id Name Dept. Age 0345 Eyal Sales 28 0965 Yair Transport 34 7665 Ori Warehouse 31
Creating a Table The basic format of the CREATE TABLE command is: CREATE TABLE TableName( Column1 DataType1 ColConstraint, … ColumnN DataTypeN ColConstraint, TableConstraint1, … TableConstraintM );
Example CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER );
Note: postgreSQL is case insensitive in Column names! An Example (cont.) If you type \d Employee you get: Column Type Modifiers ----------- ------------ ------------ id integer not null fname character varying(20) lname character varying(20) gender character(1) salary integer not null dept integer Note: postgreSQL is case insensitive in Column names!
Examples of Data Types Name Aliases Description bigint int8 signed eight-byte integer boolean bool logical Boolean (true/false) box rectangular box in the plane bytea binary data ("byte array") character varying [ (n) ] varchar [ (n) ] variable-length character string character [ (n) ] char [ (n) ] fixed-length character string circle circle in the plane date calendar date (year, month, day) double precision float8 double precision floating-point number integer int, int4 signed four-byte integer line infinite line in the plane point geometric point in the plane text timestamp [ (p) ] date and time
Constraints in Create Table Adding constraints to a table enables the database system to enforce data integrity. However, adding constraints also makes inserting data slower. Different types of constraints: * Not Null * Default Values * Unique * Primary Key * Foreign Key * Check Condition
Not Null Constraint CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER );
Default Values CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) default(‘F’), Salary INTEGER NOT NULL, Dept INTEGER );
Unique Constraint (Syntax 1) CREATE TABLE Employee( ID INTEGER UNIQUE NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) default(‘F’), Salary INTEGER NOT NULL, Dept INTEGER );
Unique Constraint (Syntax 2) CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) default(‘F’), Salary INTEGER NOT NULL, Dept INTEGER, UNIQUE(ID) );
Unique Constraint (Another Example) CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) default(‘F’), Salary INTEGER NOT NULL, Dept INTEGER, UNIQUE(FNAME,LNAME) ); Can this be written differently?
Primary Key Constraint CREATE TABLE Employee( ID INTEGER PRIMARY KEY, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER, UNIQUE(FNAME,LNAME) ); Primary Key implies: * NOT NULL * UNIQUE. There can only be one primary key.
Primary Key Constraint (Syntax 2) CREATE TABLE Employee( ID INTEGER, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER, PRIMARY KEY(FNAME,LNAME) );
Shouldn’t all department numbers in Employee appear in Department? CREATE TABLE Employee( ID INTEGER primary key, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER ); CREATE TABLE Department( DeptNumber INTEGER PRIMARY KEY, Name VARCHAR(20), ManagerId INTEGER ); Shouldn’t all department numbers in Employee appear in Department?
Foreign Key Employee Dept Name ManID 12 Sales 988 45 Repair 876 FName LName Gender Sallary Dept 02334 Larry Bird M 230000 12 04556 Magic Johnson 270000 45 Foreign Key Dept Name ManID 12 Sales 988 45 Repair 876 Department
Foreign Key Constraint CREATE TABLE Employee ( ID INTEGER primary key, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, DeptNumber INTEGER REFERENCES Department ); Note 1: DeptNumber must be unique (or primary key) in Department Note 2:You can use this syntax only if the name of the fields in both tables are identical Note 3: The referencing attribute (DeptNumber) can be null
Foreign Key Constraint (different names of attributes) CREATE TABLE Employee( ID INTEGER primary key, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER REFERENCES Department(DeptNumber) );
Foreign Key Constraint CREATE TABLE Employee( ID INTEGER primary key, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, DeptNumber INTEGER, FOREIGN KEY (DeptNumber) REFERENCES Department ); Using this syntax allows a pair or more of attributes to be a foreign key
Deleting referenced values What happens to Employees in department 312 when Department 312 is removed from the Department table?
Deleting a Referenced Value If nothing additional is specified, then postgreSQL will not allow Department 312 to be deleted if there are Employees working in (referencing to) this department. You can also specify this explicitly: FOREIGN KEY (Dept) REFERENCES Department ON DELETE RESTRICT Alternatively, if the constraint is written as Department ON DELETE CASCADE then Employees working in 312 will be deleted automatically from the Employee table, when 312 is deleted from Departments
Check Conditions A check condition is a Boolean expression: “And”s and “Or”s of conditions of the type X > 5… On a column: it can refer only to the column On a table: it can refer only to multiple columns in the table
Check Constraints CREATE TABLE Employee( ID INTEGER primary key, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) check(gender=‘F’ or gender=‘M’), Salary INTEGER NOT NULL, DeptNumber INTEGER );
Deleting a Table To delete the table Employee : DROP TABLE Employee; Mind the order of dropping when there are foreign key constraints.
Converting ER-Diagrams to Table Definitions
General Principals When converting ER diagrams to Relations, we should try to: Reduce duplicate information Constrain as tightly as possible Note: Some scenarios can be represented in different ways. Sometimes we will not be able to fully represent constraints, or will be forced to represent information more than once.
Relation definition vs. Table definition We show how to translate ER-Diagrams to table definitions Sometimes, people translate ER-Diagrams to relation definitions, which are more abstract than table definitions. e.g., Employee(ID, Fname, Lname, Gender, Salary, Dept); table definitions contain, in addition, constraints and datatypes
Simple entity translation birthday id Actor name address General Rule: Create a table with the name of the Entity. There is a column for each attribute The key in the diagram is the primary key of the table
Student id name address name address student id
Simple entity translation birthday id Actor name address Relation: Actor (id, name, birthday, address) create table Actor(id varchar(20) primary key, name varchar(40), birthday date, address varchar(100));
Translating Entities with Relationships (without constraints) birthday title id Actor Film Acted In year name salary address type Create tables for the entities as before Create a table with the name of the relationship Relationship table attributes: its own attributes (salary) + all keys of the relating entities (title, id). Q: What is the primary key of the table? A: A composite of both entity keys Q: What foreign keys are needed? A: From the relationship table to the entities
Translating relationships (without constraints) birthday title id Actor Film Acted In year name salary type address How would you define the table for ActedIn? create table ActedIn(id varchar(20) references actor, title varchar(20) references film, salary integer, primary key(id,title));
How would we represent this diagram in tables? תאריך שם קורס שם מס' זהות סטודנט נבחן קורס מס' קורס בחינה מס' בחינה
Answer קורס בחינה סטודנט נבחן מס' קורס שם קורס מס' בחינה מס' זהות שם תאריך
Translating Recursive Relationships (without constraints) manager id Employee Manages worker name address Relation: Manages (Wid, Mid) What would be the table definition? create table Manages( Eid varchar(20) references Employee(id), Mid varchar(20) references Employee(id), Primary key(Eid, Mid)); How would you prevent someone from being his own manager?
Translating relationships (key constraints): Option 1 id Director Film Directed title name salary year Option 1: Same as without key constraints (3 tables), except that the relationship primary key is…? title.
Translating relationships (key constraints): Option 1 id Director Film Directed title name salary year create table Directed( id varchar(20) references Director, title varchar(40) references Film, salary integer, primary key (title));
Translating relationships (key constraints): Option 2 id Director Film Directed title name salary year Option 2: Do not create a table for the relationship Add information columns that would have been in the relationship's table to the table of the entity with the key constraint
Translating relationships (key constraints): Option 2 id Director Film Directed title name salary year create table Film( title varchar(40) primary key, year integer, salary integer, id varchar(20) references Director); Why couldn’t we do this when there were no constraints?
Translating relationships (participation constraints) id Director Film Directed title name salary year General Rule: If both participation and key constraint exist, use Option 2 from before (only 2 tables), AND: Add the not null constraint on the referncing attribute to ensure that there will always be values for the key of the other entity
Translating relationships (participation constraints) id Director Film Directed title name salary year create table Film( title varchar(40) primary key, year integer, id varchar(20), salary integer, foreign key (id) references Director); Where should we add NOT NULL?
Translating relationships (participation constraints) id Actor Film Acted In title name salary year How would we translate this?
Translating Weak Entity Sets A regular table for Organization, and.. phone number name create table award( name varchar(40), year integer, money integer, o_name varchar(40) references Organization(name), primary key(name, year, o_name), ); Organization Gives Award money year name
Translating Aggregation phone number Oname Translating Aggregation Organization picture Director ID Gives salary Acted In Won year Award Film Broad- casted year name title type Won(title, year, name, Oname, Broadcasted);
Summary Tables Primary key Remarks Simple Entity Single table The entity key a column for each attr. Simple Relationship 3 (2 entities +relationship) For the relation: Both entity keys Foreign keys from rel. Table Key constraint 3 as before or 2 (one for each entity) Key of constrained ent. Foreign key from constr. Entity Key and Participation constr. 2 Regular Constrained entity has a non-null f. key
Tables Primary key Remarks Weak Entity 2: parent and weak entities Weak: its own and parent keys Foreign keys from weak ent. ISA: covers and disjoint 2: only child entities Parent key ISA: otherwise 3: parent and child entities Foreign keys from child ent. Aggregation 3: 2 aggregates and relationship For relationship: keys of both aggregates Foreign keys from relationship table