Presentation is loading. Please wait.

Presentation is loading. Please wait.

Designing Tables for a Database System

Similar presentations


Presentation on theme: "Designing Tables for a Database System"— Presentation transcript:

1 Designing Tables for a Database System

2 Where we were, and where we’re going
The Entity-Relationship model: Used to model the world The Relational model: An abstract definition of tables. Includes table names, column names, and key constraints A relational databases system: A database infrastructure which implements the relational model. Allows for complex definitions of tables, including data types and constraints. By converting an ER diagram to the relational model, we get abstract definitions that we can reason about By converting an ER diagram to a set of tables, we define the logical schema used to actually store the data

3 Tables The basic element in a relational database 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.

4 postgresQL In this course, we will use the postgreSQL DBMS
In order to issue commands to the DBMS we use the psql terminal In order to connect to it, print the following command in your shell: psql –hpgserver public This will give you access to “your” database

5 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 Postgresql Documentation can be found at:

6 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

7 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

8 Creating Tables in the SQL DDL DDL = Data Definition Language
Id Name Dept. Age 0345 Eyal Sales 28 0965 Yair Transport 34 7665 Ori Warehouse 31

9 Creating a Table The basic format of the CREATE TABLE command is:
CREATE TABLE TableName( Column1 DataType1 ColConstraint, … ColumnN DataTypeN ColConstraint, TableConstraint1, … TableConstraintM );

10 Example CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20),
Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER );

11 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: Databases are case insensitive in Table and Column names!

12 See also: http://www.postgresql.org/docs/7.4/interactive/datatype.html
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 See also:

13 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. Rule of thumb: add constraints, unless you know that they are affecting the runtime. Different types of constraints: * Not Null * Default Values * Unique * Primary Key * Foreign Key * Check Constraints

14 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 );

15 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 );

16 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 );

17 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) );

18 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) ); Pairs of Fname and Lname together form a key. This cannot be written differently. Since this is a constraint that deals with 2 attributes it must be written as a table constraint What does this mean? Can this be written differently?

19 Which is a stronger constraint?
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) ); Which is a stronger constraint? CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20) UNIQUE, Lname VARCHAR(20) UNIQUE, Gender CHAR(1) DEFAULT(‘F’), Salary INTEGER NOT NULL, Dept INTEGER, ); The bottom constraint is stronger. For example, in the top table there can be 2 people with the same first name, but different last names. In the bottom this would not be allowed.

20 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. The primary key is used for efficient access to the table

21 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(ID) );

22 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 ); Yes, they should. Next slide explains how to ensure this. Shouldn’t all department numbers in Employee appear in Department?

23 Foreign Key Constraint
CREATE TABLE Employee( ID INTEGER PRIMARY KEY, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) DEFAULT(‘F’), Salary INTEGER NOT NULL, DeptNumber INTEGER, FOREIGN KEY (DeptNumber) REFERENCES Department(DeptNumber) ); DeptNumber must be unique (or primary key) in Department

24 Foreign Key Constraint (Syntax 2)
CREATE TABLE Employee( ID INTEGER PRIMARY KEY, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) DEFAULT(‘F’), Salary INTEGER NOT NULL, DeptNumber INTEGER, FOREIGN KEY (DeptNumber) REFERENCES Department ); NOTE: You can use this syntax only if the name of the fields in both tables are identical

25 Foreign Key Constraint (Syntax 3)
CREATE TABLE Employee( ID INTEGER PRIMARY KEY, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1) DEFAULT(‘F’), Salary INTEGER NOT NULL, DeptNumber INTEGER REFERENCES Department ); Same constraint, written as a column constraint

26 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

27 Understanding Foreign Keys
The constraint on the last table should be read as: “The field Dept in Employee is a foreign key that references the field Dept in Department” Meaning: Every non-null value in the field Dept of Employee must appear in the field Dept of Department. Nothing happens. This removal will not be allowed as currently defined What happens to Employees in department 312 when Department 312 is removed from the Department table?

28 Deleting a Referenced Value
If nothing additional is specified, then a database system will not allow Department 312 to be deleted if there are Employees working in (referencing to) this department. This a general rule for constraints! A database system rejects any change to the database that causes a constraint to be violated! If the constraint is written as FOREIGN KEY (Dept) REFERENCES Department ON DELETE CASCADE then Employees working in 312 will be deleted automatically from the Employee table, when 312 is deleted from Departments

29 Foreign Keys Should we also revise the department table?
CREATE TABLE Department( DeptNumber INTEGER PRIMARY KEY, Name VARCHAR(20), ManagerId INTEGER, ); Cyclic constraints will prevent any rows from being inserted Do you see a problem in defining these tables and in inserting data now?

30 Cyclic Foreign Key Constraints
ID FName LName Gender Salary DeptNum DeptNum Name ManagerID

31 One Solution to Cyclic Constraints
Add one of the constraints later on (after insertion): CREATE TABLE Department( Dept INTEGER PRIMARY KEY, Name VARCHAR(20), ManagerId INTEGER); Insert data here… ALTER TABLE Department ADD(FOREIGN KEY (ManagerId) REFERENCES Employee(ID)); Transactions can also be used to solve this problem… Discussed (much) later in the course

32 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 Cannot refer to content of other rows!

33 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 CHECK (Gender = ‘M’ or Salary > 10000) );

34 DROP TABLE Employee cascade constraints;
Deleting a Table To delete the table Employee : DROP TABLE Employee; Mind the order of dropping when there are foreign key constraints. Why? Can use: DROP TABLE Employee cascade constraints; We will not be able to drop a table if doing so will cause foreign key constraints to be violated. The command at the bottom “cascades” the deletion and causes rows “dependent” on those being deleted, to also be deleted.

35 Modifying Tables Done with ALTER TABLE statement Usually:
ADD followed by an attribute name and type or DROP followed by an attribute name ALTER TABLE Actor ADD phone CHAR(16); ALTER TABLE Actor DROP bdate;

36 Inserting, deleting, and updating data in a table

37 The Employee Table Column Type Modifiers
id integer not null fname character varying(20) gender character(1) deptnumber integer

38 Inserting a Row To insert a row into the Employee table:
insert into employee (id,fname,gender,deptnumber) values(122,'Goldman','M',12); insert into employee (id,deptnumber) values(123,13);

39 Some More Details… The fields don’t have to be specified if values are specified for all columns and in the order defined by the table Example: insert into employee values(33,'David','F',11);

40 Deleting Rows General format:
DELETE FROM Table WHERE Condition; Deletes all rows satisfying Condition from Table For example, to remove the employee with id 121 from the Employee table: DELETE FROM Employee WHERE id = 121;

41 Deleting Rows (cont.) To remove all employees having a salary greater than 100,000: DELETE FROM Employee WHERE Salary > ; To remove all employees: DELETE FROM Employee;

42 Updating Rows We can update rows in a table General format:
UPDATE Table SET Field1=value1,…,FieldN=valueN WHERE Condition Now we can reduce salaries instead of firing employees: UPDATE Employee SET Salary = WHERE Salary > ;


Download ppt "Designing Tables for a Database System"

Similar presentations


Ads by Google