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.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Fall 2005 ICS184/EECS116 – Notes 08 1 ICS 184/EECS116: Introduction to Data Management Lecture Note 8 SQL: Structured Query Language -- DDL.
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.
1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
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.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
1 Designing Tables for an Oracle Database System Database Course, Fall 2004.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Introduction to SQL  SQL or sequel  It is a standardised language with thousands of pages in the standard  It can be in database system through GUI,
1 CSE 480: Database Systems Lecture 9: SQL-DDL Reference: Read Chapter of the textbook.
Oracle Data Definition Language (DDL)
SQL Overview Defining a Schema CPSC 315 – Programming Studio Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch Via Yoonsuck Choe.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Database Design lecture 3_1 1 Database Design Lecture 3_1 Data definition in SQL.
Database A collection of related data. Database Applications Banking: all transactions Airlines: reservations, schedules Universities: registration, grades.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
1 The Relational Model Instructor: Mohamed Eltabakh
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.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
SQL: DDL John Ortiz Cs.utsa.edu.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Advanced Database CS-426 Week 1 - Introduction. Database Management System DBMS contains information about a particular enterprise Collection of interrelated.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
CREATE TABLE CREATE TABLE statement is used for creating relations Each column is described with three parts: column name, data type, and optional constraints.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Visual Programing SQL Overview Section 1.
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.
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
SQL constrains and keys. SORTED RESULTS Sort the results by a specified criterion SELECT columns FROM tables WHERE predicates ORDER BY column ASC/DESC;
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
LECTURE FOUR Introduction to SQL DDL with tables DML with tables.
SQL. Internet technologies – Ohad © Database  A database is a collection of data  A database management system (DBMS) is software designed to assist.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
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.
Fundamentals of DBMS Notes-1.
Designing Tables for a Database System
DB Review.
Instructor: Mohamed Eltabakh
لغة قواعد البيانات STRUCTURED QUERY LANGUAGE SQL))
CS4222 Principles of Database System
Designing Tables for a postgreSQL Database System
SQL data definition using Oracle
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
Instructor: Mohamed Eltabakh
Session - 6 Sequence - 1 SQL: The Structured Query Language:
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 –hdbcourse 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’ \dtlist tables \di list indexes \dv list views \df list functions Postgresql Documentation can be found at:

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 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 IdNameDept.Age 0345EyalSales YairTransport OriWarehouse31

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

10Example 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 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 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:

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) 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 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 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 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 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 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 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 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 Foreign Key IDFNameLNameGenderSallary DeptNum ber 02334LarryBirdM MagicJohnsonM Foreign Key DeptNumberNameManID 12Sales988 45Repair876 Employee Department

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 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 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 Cyclic Foreign Key Constraints IDFNameLNameGenderSalaryDeptNum NameManagerID

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

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 Inserting, deleting, and updating data in a table

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

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