Designing Tables for a postgreSQL Database System

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
1 Designing Tables for an Oracle Database System Database Course, Fall 2003.
1 Translation of ER-diagram into Relational Schema Prof. Sin-Min Lee Department of Computer Science.
Final Exam Revision 5 Prof. Sin-Min Lee Department of Computer Science.
1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem.
1 Designing Tables for an Oracle Database System Database Course, Fall 2005.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation Adding columns Changing columns’ definition Dropping columns.
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
1 Designing Tables for an Oracle Database System Database Course, Fall 2004.
Oracle Data Definition Language (DDL)
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Database. Basic Definitions Database: A collection of related data. Database Management System (DBMS): A software package/ system to facilitate the creation.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
1 Translation of ER-diagram into Relational Schema Prof. Sin-Min Lee Department of Computer Science.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
10 Copyright © 2009, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Copyright © 2006, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
SQL: DDL John Ortiz Cs.utsa.edu.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
INCLUDING CONSTRAINTS lecture5. Outlines  What are Constraints ?  Constraint Guidelines  Defining Constraint  NOT NULL constraint  Unique constraint.
The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password.
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
SQL. Internet technologies – Ohad © Database  A database is a collection of data  A database management system (DBMS) is software designed to assist.
CDT/1 Creating data tables and Referential Integrity Objective –To learn about the data constraints supported by SQL2 –To be able to relate tables together.
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.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
2 Copyright © 2009, Oracle. All rights reserved. Managing Schema Objects.
Database Constraints Ashima Wadhwa. Database Constraints Database constraints are restrictions on the contents of the database or on database operations.
Fundamental of Database Systems
Logical DB Design: ER to Relational
TABLES AND INDEXES Ashima Wadhwa.
Managing Tables, Data Integrity, Constraints by Adrienne Watt
CS 480: Database Systems Lecture 13 February 13,2013.
Constraints and Triggers
SQL Creating and Managing Tables
Quiz Questions Q.1 An entity set that does not have sufficient attributes to form a primary key is a (A) strong entity set. (B) weak entity set. (C) simple.
Converting ER-Diagrams to Table Definitions
Designing Tables for a Database System
DB Review.
Translation of ER-diagram into Relational Schema
ORACLE SQL Developer & SQLPLUS Statements
SQL Creating and Managing Tables
From ER to Relational Model
Instructor: Mohamed Eltabakh
SQL Creating and Managing Tables
CS4222 Principles of Database System
SQL data definition using Oracle
Translation of ER-diagram into Relational Schema
Defining a Database Schema
Creating Tables & Inserting Values Using SQL
Oracle Data Definition Language (DDL)
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Chapter 2: Creating And Modifying Database Tables
Database Design: Relational Model
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
Instructor: Mohamed Eltabakh
IST 318 Database Administration
SQL – Constraints & Triggers
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Database Instructor: Bei Kang.
Including Constraints
SQL (Structured Query Language)
Presentation transcript:

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