Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 1 Designing Tables for a Database System

2 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 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 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 –hdbcourse public This will give you access to “your” database

5 5 A few useful commands \q exit psql \h [command]help about ‘command’ \d [name] describe table/index/… called ‘name’ \dtlist tables \di list indexes \dv list views \df list functions Postgresql Documentation can be found at: http://www.postgresql.org/docs/8.4/interactive/index.html

6 6 Reminder DISK sailors Reserves Main Memory CPU The database is kept on the disk, so anything you create will be there next time you log on.

7 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 8 Creating Tables in the SQL DDL DDL = Data Definition Language IdNameDept.Age 0345EyalSales28 0965YairTransport34 7665OriWarehouse31

9 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 10Example CREATE TABLE Employee( ID INTEGER NOT NULL, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, Dept INTEGER );

11 11 An Example (cont.) If you type \d Employee you get Column Type Modifiers ----------- ------------ ------------ idinteger not null fnamecharacter varying(20) lnamecharacter varying(20) gender character(1) salary integer not null deptinteger Note: Databases are case insensitive in Table and Column names!

12 12 Examples of Data Types NameAliasesDescription bigintint8 signed eight-byte integer booleanbool 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 precisionfloat8 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 variable-length character string timestamp [ (p) ] date and time See also: http://www.postgresql.org/docs/7.4/interactive/datatype.html

13 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 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 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 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 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 18 Unique Constraint (Another Example) What does this mean? Can this be written differently? 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) );

19 19 CREATE TABLE Employee( IDINTEGER NOT NULL, Fname VARCHAR(20), LnameVARCHAR(20), GenderCHAR(1) DEFAULT(‘F’), Salary INTEGER NOT NULL, DeptINTEGER, UNIQUE(Fname, Lname) ); CREATE TABLE Employee( IDINTEGER NOT NULL, Fname VARCHAR(20) UNIQUE, LnameVARCHAR(20) UNIQUE, GenderCHAR(1) DEFAULT(‘F’), SalaryINTEGER NOT NULL, DeptINTEGER, ); Which is a stronger constraint?

20 20 Primary Key Constraint Primary Key implies: * NOT NULL * UNIQUE. There can only be one primary key. The primary key is used for efficient access to the table 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) );

21 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 22 Shouldn’t all department numbers in Employee appear in Department ? CREATE TABLE Department( DeptNumber INTEGER PRIMARY KEY, Name VARCHAR(20), ManagerId INTEGER ); CREATE TABLE Employee( ID INTEGER primary key, Fname VARCHAR(20), Lname VARCHAR(20), Gender CHAR(1), Salary INTEGER NOT NULL, DeptNumber INTEGER );

23 23 Foreign Key Constraint CREATE TABLE Employee( IDINTEGER PRIMARY KEY, Fname VARCHAR(20), LnameVARCHAR(20), GenderCHAR(1) DEFAULT(‘F’), SalaryINTEGER NOT NULL, DeptNumberINTEGER, FOREIGN KEY (DeptNumber) REFERENCES Department(DeptNumber) ); DeptNumber must be unique (or primary key) in Department

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

25 25 Foreign Key Constraint (Syntax 3) CREATE TABLE Employee( IDINTEGER PRIMARY KEY, Fname VARCHAR(20), LnameVARCHAR(20), GenderCHAR(1) DEFAULT(‘F’), SalaryINTEGER NOT NULL, DeptNumberINTEGER REFERENCES Department );

26 26 Foreign Key IDFNameLNameGenderSallary DeptNum ber 02334LarryBirdM23000012 04556MagicJohnsonM27000045 Foreign Key DeptNumberNameManID 12Sales988 45Repair876 Employee Department

27 27 Understanding Foreign Keys The constraint on the last table should be read as: “The field DeptNumber in Employee is a foreign key that references the field DeptNumber in Department ” Meaning: Every non-null value in the field DeptNumber of Employee must appear in the field DeptNumber of Department. What happens to Employee s in department 312 when Department 312 is removed from the Department table?

28 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 (DeptNumber) 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 29 Foreign Keys CREATE TABLE Department( DeptNumber INTEGER PRIMARY KEY, Name VARCHAR(20), ManagerId INTEGER, ); Do you see a problem in defining these tables and in inserting data now? Should we also revise the department table?

30 30 Cyclic Foreign Key Constraints IDFNameLNameGenderSalaryDeptNum NameManagerID

31 31 One Solution to Cyclic Constraints Add one of the constraints later on (after insertion): CREATE TABLE Department( DeptNumber 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 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 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 34 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;

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; 35

36 36 Inserting, deleting, and updating data in a table

37 37 The Employee Table Column Type Modifiers ----------- ------------ ------------ idinteger not null fnamecharacter varying(20) gender character(1) deptnumberinteger

38 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 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 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 41 Deleting Rows (cont.) To remove all employees having a salary greater than 100,000: DELETE FROM Employee WHERE Salary > 100000; To remove all employees: DELETE FROM Employee;

42 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 = 100000 WHERE Salary > 100000;


Download ppt "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."

Similar presentations


Ads by Google