Content: How to transform the relational model into a database schema DDL: create table students(studentnr int, name varchar);

Similar documents
How to define a relational schema for a data base?

Data modeling. Excerpt of the Real World. Manual/intellectual Modeling. Conceptual Schema (E/R- or UML-Schema) Transformation

SQL (structured query language)

Chapter 4: Relational Model

1. SQL definition SQL is a declarative query language 2. Components DRL: Data Retrieval Language DML: Data Manipulation Language DDL: Data Definition

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Lab # 4. Data Definition Language (DDL)

Chapter 1 SQL and Data

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Full file at

Chapter 2: ER-Diagrams. Content: Learn how to draw ER diagrams Useful to model a database

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

@vmahawar. Agenda Topics Quiz Useful Links

Introduction SQL DRL. Parts of SQL. SQL: Structured Query Language Previous name was SEQUEL Standardized query language for relational DBMS:

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

MTAT Introduction to Databases

SQL Data Definition and Data Manipulation Languages (DDL and DML)

INTRODUCTION TO DATABASE

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

General Overview - rel. model. Carnegie Mellon Univ. Dept. of Computer Science Database Applications. Reminder: our Mini-U db

Daffodil DB. Design Document (Beta) Version 4.0

Principles of Data Management

The Relational Model Constraints and SQL DDL

Database Management System 9

GridDB Advanced Edition SQL reference

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Basic SQL. Basic SQL. Basic SQL

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

SQL: DDL. John Ortiz Cs.utsa.edu

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Chapter 4 SQL. Database Systems p. 121/567

SQL DATA DEFINITION LANGUAGE

Full file at

1) Introduction to SQL

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

The Structured Query Language Get Started

DB Creation with SQL DDL

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

The Relational Model of Data (ii)

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7

In This Lecture. SQL Data Definition SQL SQL. Non-Procedural Programming. Notes. Database Systems Lecture 5 Natasha Alechina

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Deccansoft softwareservices-microsoft Silver Learing Partner. SQL Server Syllabus

Chapter-14 SQL COMMANDS

SQL Commands & Mongo DB New Syllabus

Creating and Managing Tables Schedule: Timing Topic

II B.Sc(IT) [ BATCH] IV SEMESTER CORE: RELATIONAL DATABASE MANAGEMENT SYSTEM - 412A Multiple Choice Questions.

Comp 5311 Database Management Systems. 4b. Structured Query Language 3

Course Outline and Objectives: Database Programming with SQL

SQL: Data Definition Language

Data about data is database Select correct option: True False Partially True None of the Above

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

Solved MCQ on fundamental of DBMS. Set-1

Chapter 4: Intermediate SQL

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #4: SQL---Part 2

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Administrivia. The Relational Model. Review. Review. Review. Some useful terms

Data Manipulation (DML) and Data Definition (DDL)

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Lecture 07. Spring 2018 Borough of Manhattan Community College

SQL Simple Queries. Chapter 3.1 V3.01. Napier University

3.2.4 Enforcing constraints

SQL DATA DEFINITION LANGUAGE

Chapter 9: Working with MySQL

The SQL data-definition language (DDL) allows defining :

Information Systems for Engineers Fall Data Definition with SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

From theory to practice. Designing Tables for an Oracle Database System. Sqlplus. Sqlplus. Technicalities. Add the following to your.

CS2300: File Structures and Introduction to Database Systems

Module 9: Managing Schema Objects

Chapter 3: Introduction to SQL

SQL DATA DEFINITION LANGUAGE

Chapter 3: Introduction to SQL

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations

STRUCTURED QUERY LANGUAGE (SQL)

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

CMP-3440 Database Systems

An Introduction to Structured Query Language

Review. The Relational Model. Glossary. Review. Data Models. Why Study the Relational Model? Why use a DBMS? OS provides RAM and disk

SQL. SQL DDL Statements

An Introduction to Structured Query Language

An Introduction to Structured Query Language

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

An Introduction to Structured Query Language

Business Analytics. SQL PL SQL [Oracle 10 g] P r i n c e S e t h i w w w. x l m a c r o. w e b s. c o m

DB2 Certification DB2. Using SQL. DM CofC DB2CERT.PRZ

Transcription:

Chapter 5: Relational Database Definition Content: How to transform the relational model into a database schema DDL: create table students(studentnr int, name varchar); Next: Query the database 1

How to define a relational schema for a database? 2

Professors PersNr Name Level Room 2125 Sokrates C4 226 2126 Russel C4 232 2127 Kopernikus C3 310 2133 Popper C3 52 2134 Augustinus C3 309 2136 Curie C4 36 2137 Kant C4 7 StudNr attend LectureNr 26120 5001 27550 5001 27550 4052 28106 5041 28106 5052 28106 5216 28106 5259 29120 5001 29120 5041 29120 5049 25403 5022 29555 5022 29555 5001 Students StudNr Name Semester 24002 Xenokrates 18 25403 Jonas 12 26120 Fichte 10 26830 Aristoxenos 8 27550 Schopenhauer 6 28106 Carnap 3 29120 Theophrastos 2 29555 Feuerbach 2 require Predecessor Successor 5001 5041 5001 5043 5001 5049 5041 5216 5043 5052 5041 5052 5052 5259 test StudNr LectureNr PersNr Grade 28106 5001 2126 1 25403 5041 2125 2 27550 4630 2137 2 Lecture Nr Lectures Title Weekly Hours Given_by 5001 Grundzüge 4 2137 5041 Ethik 4 2125 5043 Erkenntnistheorie 3 2126 5049 Mäeutik 2 2125 4052 Logik 4 2125 5052 Wissenschaftstheorie 3 2126 5216 Bioethik 2 2126 5259 Der Wiener Kreis 2 2133 5022 Glaube und Wissen 2 2134 4630 Die 3 Kritiken 4 2137 Assistants PersNr Name Area Boss 3002 Platon Ideenlehre 2125 3003 Aristoteles Syllogistik 2125 3004 Wittgenstein Sprachtheorie 2126 3005 Rhetikus Planetenbewegung 2127 3006 Newton Keplersche Gesetze 2127 3007 Spinoza Gott und Natur 2126

SQL Former name: SEQUEL SQL: Structured Query Language Standardized query language for relational DBMS: SQL-89, SQL-92, SQL-99, SQL:2003 (XML-Extensions) SQL is a declarative query language 4

Parts of SQL Parts: DRL: Data Retrieval Language DML: Data Manipulation Language Mostly only DML DDL: Data Definition Language DCL: Data Control Language TCL: Transaction Control Language 5

DRL: Data Retrieval Language DRL contains statements for queries Simple query consists of the three select, from and where select list of attributes from list of relations where predicate; 6

DML: Data Manipulation Language DML contains statements to Insert data Delete data Change data insert, delete, update 7

DDL: Data Definition Language With the DDL the schema of a database can be defined Also contains statements to control the access path to the database e.g. create table, alter table, create view, create index Correspondingly also delete statements drop.. 8

DCL: Data Control Language Contains statements mostly concerned with rights, permissions and other controls of the database system (authorization) e.g. grant, revoke 9

TCL: Transaction Control Language Contains statements to control transactions A transaction is a set of interactions between application / user and the database Will be dealt with later in the section transaction management e.g. commit, rollback 10

Variants of SQL Database cannot only be used interactively SQL can be embedded in other programming languages Problem: SQL is set oriented, most programming languages aren t 11

Dynamic SQL Is used when queries are not yet known when the program is compiled Standardized Interfaces ODBC (Open Database Connectivity) JDBC (for Java) More flexible, but usually a bit slower than embedded SQL 12

Dynamic SQL: Example String db_url = "jdbc:postgresql://localhost:5432/uni ; Connection connection = DriverManager.getConnection(db_url, alex", 123456"); Statement statement = connection.createstatement(); ResultSet result = statement.executequery( select name from students"); while (result.next()) { System.out.println(result.getString( name"), result.getint( semester")); } 13

Embedded SQL SQL statements are directly embedded in the corresponding host language (e.g. C, C++, Java, etc.) SQL statements are marked with a preceding EXEC SQL SQL statements are then replaced by a pre-processor by constructs of the corresponding language 14

DDL: Create Table Statement Syntax diagram encompasses many pages!! Simple form: create table TableName ( Attribute1 DataType1 [NOT NULL], Attributen DataTypeN [NOT NULL]); 15

DDL: Example Create Table Statement CREATE TABLE Professors (PersNr INTEGER NOT NULL, Name VARCHAR(30) NOT NULL, Level CHAR(2), Room INTEGER); CREATE TABLE Lectures (LectureNr INTEGER NOT NULL, Title VARCHAR(30), WeeklyHours INTEGER, Given_by INTEGER); 16

DDL: Data types in SQL strings and numbers VARCHAR (n) variable length string, length maximal n Byte CHAR[ACTER] (n) fixed length string of n Byte NUMERIC [(p[, s])] signed number with p digits in total, s of them after the decimal place also DEC[IMAL] [(p,s)] (allows storing bigger values) INT[EGER] signed integer SMALLINT like INTEGER, smaller value range FLOAT [(p)] (rounded) floating point number (at least p Bits precision) REAL, DOUBLE PRECISION short cuts for FLOAT(p), values for p dependent on implementation 17

DDL: Data types in SQL date and time DATE valid Date TIME time (from 00:00:00 bis 23:59:59) TIMESTAMP timestamp (combination of date and time) (ORACLE only has DATE and uses this as timestamp) 18

DDL: Data types in SQL strings, binary data LONG variable string with up to 2 GB (TEXT SQL Server) CLOB string with up to 4 GB RAW (n) binary data of length n, n between 1 and 2000 Bytes LONG RAW binary data with up to 2 GB BLOB binary data with up to 4 GB CFILE, BFILE pointer to file (text, binary) (Oracle) DATALINK pointer to file (DB2) MONEY / SMALLMONEY (SQL Server) restricted operations on it! 19

DDL: Integrity constraints One of the tasks of a DBMS: guarantee the consistency of the data Semantical integrity constraints describe the properties of the mini world modelled DBMS can automatically check these constraints once formulated 20

Primary Key Constraint Value of an attribute or a combination of attributes does not occur twice in any instance of the data base 21

DDL: Primary key constraint Value of an attribute or a combination of attributes does not occur twice in any instance of the data base CREATE TABLE Table_Name ( Attribute_1 Data_Type_1 [NOT NULL], Attribute_n Data_Type_n [NOT NULL], [CONSTRAINT constraint_name_pk] PRIMARY KEY (Attribute_i,,Attribute_p)); 22

DDL: Example primary key CREATE TABLE Professors (PersNr INTEGER NOT NULL, Name VARCHAR(30) NOT NULL, Level CHAR(2), Room INTEGER, PRIMARY KEY (PersNr) ); CREATE TABLE Lectures (LectureNr INTEGER NOT NULL, Title VARCHAR(30), WeeklyHours INTEGER, Given_by INTEGER, PRIMARY KEY (LectureNr)); 23

DDL: Primary Key Constraints (short form) CREATE TABLE Professors (PersNr INTEGER NOT NULL PRIMARY KEY, Name VARCHAR(30) NOT NULL, Level CHAR(2), Room INTEGER); CREATE TABLE Lectures (LectureNr INTEGER NOT NULL PRIMARY KEY, Title VARCHAR(30), WeeklyHours INTEGER); 24

DDL: Further integrity constraints Besides primary keys there are some other integrity constraints, such as: NOT NULL Unique Check clauses 25

DDL: NOT NULL Enforces defined attribute values when inserting tuples Mandatory for primary keys Possible to give default value CREATE TABLE defaults ( Id INTEGER NOT NULL PRIMARY KEY, Location VARCHAR(80) DEFAULT GARCHING, VAT SMALLINT DEFAULT 19, Age SMALLINT DEFAULT 20, Height SMALLINT NOT NULL); 26

DDL: UNIQUE Enforces key property (for candidate key) CREATE TABLE Professors (PersNr INTEGER PRIMARY KEY, Name VARCHAR(30) NOT NULL, Level CHAR(2) CHECK (Rang IN ('C2', 'C3', 'C4')), Room INTEGER NOT NULL UNIQUE); 27

DDL: Check clauses With check clauses the range of values for an attribute can be restricted Example: CREATE TABLE Professors ( PersNr INTEGER NOT NULL PRIMARY KEY, Name VARCHAR(80) NOT NULL, Level CHAR(2) CHECK (Level IN ( C2, C3, C4, W1, W2, W3 )), Room INTEGER CHECK (Room > 0 AND Room < 9999)); 28

Referential Integrity Let R and S be two relations with schema R resp. S k is primary key of R Then f ϵ S is foreign key, if for all tuples s ϵ S holds: s.f either only holds only null values or only values not null If s.f has no null values, then there exists a tuple r ϵ R with s.f = r.k The fulfillment of these properties is called referential integrity 29

DDL: Referential integrity CREATE TABLE Table_name ( Attribute_1 Data_type_1 [NOT NULL], Attribute_n Data_type_n [NOT NULL], [CONSTRAINT constraint_name_pk] PRIMARY KEY (Attribute_i,,Attribute_p), CONSTRAINT constraint_name_fk FOREIGN KEY (Attribute_j,, Attribute_l) REFERENCES Parent_table_name (Attribute_t,, Attribute_v)); 30

DDL: Example referential key CREATE TABLE Professors (PersNr INTEGER NOT NULL, Name VARCHAR(30) NOT NULL, Level CHAR(2), Room INTEGER, PRIMARY KEY (PersNr) ); CREATE TABLE Lectures (LectureNr INTEGER NOT NULL, Title VARCHAR(30), WeeklyHours INTEGER, Given_by INTEGER, PRIMARY KEY (LectureNr), CONSTRAINT givenby_fk FOREIGN KEY (Given_by) REFERENCES Professors (PersNr) ); 31

DDL: Example referential key (short form) CREATE TABLE Professors (PersNr INTEGER NOT NULL PRIMARY KEY, Name VARCHAR(30) NOT NULL, Level CHAR(2), Room INTEGER); CREATE TABLE Lectures (LectureNr INTEGER NOT NULL PRIMARY KEY, Title VARCHAR(30), WeeklyHours INTEGER, Given_by INTEGER REFERENCES Professors); 32

DDL: Foreign key variants Changes to key attributes can automatically be propagated: set null: all foreign keys values which reference a key which was altered or deleted are set NULL cascade: all foreign keys values which reference a key which was altered or deleted are likewise altered (to the new value) resp. Deleted 33

DDL: Example foreign key variants Lecture Nr Lectures Title Weekly Hours Given_by 5001 Grundzüge 4 2137 5041 Ethik 4 2125 5043 Erkenntnistheorie 3 2126 5049 Mäeutik 2 2125 4052 Logik 4 2125 5052 Wissenschaftstheorie 3 2126 5216 Bioethik 2 2126 5259 Der Wiener Kreis 2 2133 5022 Glaube und Wissen 2 2134 4630 Die 3 Kritiken 4 2137 Professors PersNr Name Level Room 2125 Sokrates C4 226 2126 Russel C4 232 2127 Kopernikus C3 310 2133 Popper C3 52 2134 Augustinus C3 309 2136 Curie C4 36 2137 Kant C4 7 34

DDL: Example foreign key variants CREATE TABLE Lectures (LectureNr INTEGER NOT NULL PRIMARY KEY, Title VARCHAR(30), WeeklyHours INTEGER, Given_by INTEGER REFERENCES Professors ON DELETE SET NULL); CREATE TABLE attend (StudNr INTEGER REFERENCES Students ON DELETE CASCADE, LectureNr INTEGER REFERENCES Lectures ON DELETE CASCADE, PRIMARY KEY (StudNr, LectureNr)); 35

Discussion: Personal (1) ER-Diagram: Department [0, n] work_in [0, 1] Person Realization in the relational model? 36

Discussion: Personal (2) Additional rule: In every department at least one person has to work in ([1, N]) Realization in the relational model? Additional rule : Every person has to work in exactly one department ([1, 1]) Realization in the relational model? 37

Homework until next lecture Play the game SQL Island, http://www.sql-island.de/ Try the W3Schools SQL Quiz, http://www.w3schools.com/quiztest/quiz test.asp?qtest=sql 38

Generated Values Artificial values, surrogates, no semantic, mostly as keys: Directly in the table definition: create table dept ( deptno serial primary key, deptname varchar(50) not null); insert with: insert into dept values(default, 'I3')or insert into dept values('i3'); 39

Sequences to share CREATE [ TEMPORARY TEMP ] SEQUENCE name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue NO MINVALUE ] [ MAXVALUE maxvalue NO MAXVALUE ] [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ] CREATE SEQUENCE artificial_key START 101; CREATE TABLE Dept (deptno INT DEFAULT nextval('artificial_key') NOT NULL,...) INSERT INTO dept VALUES (nextval('artificial_key'), 'I3'); 40