Introduction to Relational Database Management Systems

Similar documents
Introduction to SQL Server. nikos bikakis

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

Database Fundamentals Chapter 1

Basic SQL. Basic SQL. Basic SQL

Chapter 1 An introduction to relational databases and SQL

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Working with Databases and Java

Relational Database Systems Part 01. Karine Reis Ferreira

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

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

ITCS 3160 DATA BASE DESIGN AND IMPLEMENTATION

INFORMATION TECHNOLOGY NOTES

CSC 453 Database Technologies. Tanu Malik DePaul University

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition)

SQL Commands & Mongo DB New Syllabus

Database Management Systems,

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Physical Design of Relational Databases

Chapter 16: Databases

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

Exact Numeric Data Types

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

Part I: Structured Data

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

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

Overview Relational data model

DATABASE MANAGEMENT SYSTEMS. UNIT I Introduction to Database Systems

Chapter 1: Introduction

Overview of Data Management

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

12 Rules Defined by Dr.Codd for a Relational Database Management System

COSC344 Database Theory and Applications. σ a= c (P) Lecture 3 The Relational Data. Model. π A, COSC344 Lecture 3 1

Introduction to Databases CSE 414. Lecture 2: Data Models

A practical introduction to database design

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

CS425 Fall 2016 Boris Glavic Chapter 1: Introduction

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

What is Data? ANSI definition: Volatile vs. persistent data. Data. Our concern is primarily with persistent data

What is Data? Volatile vs. persistent data Our concern is primarily with persistent data

Database Technology Introduction. Heiko Paulheim

Announcements. Using Electronics in Class. Review. Staff Instructor: Alvin Cheung Office hour on Wednesdays, 1-2pm. Class Overview

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

JDBC Programming: Intro

Introduction to Data Management CSE 344. Lecture 2: Data Models

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

DBMS. Relational Model. Module Title?

CPS510 Database System Design Primitive SYSTEM STRUCTURE

CS143: Relational Model

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

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

SQL Server 2008 Tutorial 3: Database Creation

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou

Relational Model History. COSC 304 Introduction to Database Systems. Relational Model and Algebra. Relational Model Definitions.

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

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

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 2: Relations and SQL. September 5, Lecturer: Rasmus Pagh

Outline. Definitions History Basic concepts of DBMS Data Models Relational database Normalization

UNIT-3 Java Database Client/Server

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

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

Review for Exam 1 CS474 (Norton)

SQL Introduction. CS 377: Database Systems

Relational Model. Courses B0B36DBS, A4B33DS, A7B36DBS: Database Systems. Lecture 02: Martin Svoboda

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

PERSİSTENCE OBJECT RELATİON MAPPİNG

Introduction to SQL Server 2005/2008 and Transact SQL

doc. RNDr. Tomáš Skopal, Ph.D. RNDr. Michal Kopecký, Ph.D.

sqoop Automatic database import Aaron Kimball Cloudera Inc. June 18, 2009

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

Chapter 1: Introduction

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

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

Chapter 1 SQL and Data

Introduction to the Structured Query Language [ SQL ] (Significant Concepts)

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Tranquility Publications. Web Edition MAC

CONSTRAINTS AND UPDATES CHAPTER 3 (6/E) CHAPTER 5 (5/E)

The Relational Model

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

Lab # 4. Data Definition Language (DDL)

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Today's Party. Example Database. Faloutsos/Pavlo CMU /615

CISC 3140 (CIS 20.2) Design & Implementation of Software Application II

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

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

CMPT 354: Database System I. Lecture 2. Relational Model

Lecture 1: Relational Databases

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

Introduction to Relational Databases. Introduction to Relational Databases cont: Introduction to Relational Databases cont: Relational Data structure

Introduction to Databases. MySQL Syntax Guide: Day 1

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

CS 377 Database Systems

Overview of Data Management

Slides by: Ms. Shree Jaswal

IT360: Applied Database Systems. Slide Set: #2. Relational Model (Chapter 3 Kroenke) The relational model Relational model terminology

CS317 File and Database Systems

Introduction to Database Systems CSE 414

Transcription:

Introduction to Relational Database Management Systems nikos bikakis bikakis@dblab.ntua.gr dblab NTU Athens Jan 2014

Outline RDBMS History Relational Model Overview RDBMS Overview Integrity Constraints in RDBMS Views Triggers Client/Server Database Model JDBC Microsoft SQL Server 2

RDBMS History The Ancestors Early 1960 s IDS (Integrated Data Store) The first DBMS Network data model (Directed acyclic graph with nodes & edges) Charles Bachman @ Honeywell Information Systems 1973 ACM Turing Award For his outstanding contributions to database technology" Mid 1960 s IMS (Information Management System) The first commercially DBMS IBM Hierarchical model (Tree-based Representation) 3

RDBMS History The Relational Model 1970 Relational Model Edgar (Ted) Codd @ IBM San Jose Lab A Relational Model of Data for Large Shared Data Banks 1981 ACM Turing Award For his fundamental and continuing contributions to the theory and practice of database management systems, esp. relational databases 4

RDBMS History The First RDBMSs Late 1970 s INGRES University of California, Berkeley Michael Stonebraker & Eugene Wong Used QUEL as its query language Similar to System R, but based on different hardware and operating system Became commercial and followed up POSTGRES which was incorporated into Informix. System R IBM San Jose Lab Structured Query Language (SQL) Evolved into SQL/DS which later became DB2 5

(R)DBMS History Important Dates 1976: Peter Chen defined the Entity-Relationship (ER) model 1985: Object-oriented DBMS (OODBMS). 90s: Incorporation of object-orientation in RDBMS 1991: Microsoft Access, a personal DBMS Mid 90s: First Internet database applications Late 90s: XML used in DBMS Early 00s: RDF used in DBMS 6

RDBMS History Today The main players Oracle Oracle Database & MySQL (earlier MySQL AB, Sun) IBM DB2 Microsoft SQL Server 7

Relational Model Basic Concepts Data is represented as mathematical n-ary relations Table is a relation representation Relation (table) basic concepts: Attribute (column) Attributes Names Tupple (row) 8

Relational Model Relations (1/2) Relating Relations Artist Table Primary Key Foreign Key Song Table artist_name artist_id Aaa 1 Bbb 2 Ccc 3 artist_id song_id song_name 2 1 xxx 1 2 www 2 3 zzz Limitations? 9

Relational Model Relations (2/2) Artist Table Artist-Song Table Song Table artist_name Aaa 1 Bbb 2 Ccc 3 Primary Key artist_id Foreign Key artist_id 1 1 2 1 1 2 Primary Key Foreign Key song id Primary Key song_id 1 xxx 2 www 3 zzz song_name 10

RDBMS Overview Basic Objects Tables Views Stored Procedures Functions Rules Defaults Cursors Triggers 11

RDBMS Overview Data Types bit: boolean number int, smallint, bigint, tinyint: Integer number decimal, numeric: Real numbers char, varchar, nchar, nvarchar, text: Strings date, datetime: Date and time money, smallmoney: money values binary: Images and other large objects 12

RDBMS Overview Operators Arithmetic: +, -, *, /, % Assignment: = Comparison: <, >, <=, >= <>, =,!=,!<,!> Logical: AND, OR, NOT, IN, LIKE, BETWEEN, ANY, ALL, EXISTS, SOME String: Concatenation (+) Unary: -, +, ~ Bitwise: &,, ^ 13

RDBMS Overview Operations (1/3) Database Level Defining working database Use <dbname> Creating a database Create database <dbname> Deleting a database Drop database <dbname> 14

RDBMS Overview Operations (2/3) Schema Level Create Table Drop Table Alter Table (Used to modify table structure) Add new column Change data type of existing column Delete a column Add or remove constraints like foreign key, primary key 15

RDBMS Overview Operations (2/3) Create Table Example CREATE TABLE Person( personid integer, FirstName varchar(15) not null, LastName varchar(20), Age demical(3,1), orgid integer, primary key (personid) foreign key orgid references Organization.ID ); 16

RDBMS Overview Operations (2/3) Drop/Alter Table Examples DROP TABLE Person ALTER TABLE Person ADD Email varchar(30); ALTER TABLE Person ADD (Email varchar(30), Telephone varchar(20)); ALTER Table Person DROP COLUMN Age; ALTER TABLE Person ALTER COLUMN LastName varchar(50); ALTER TABLE Person ADD CONSTRAINT const_lastname UNIQUE (LastName); 17

RDBMS Overview Operations (3/3) Data Level Select Insert Update Update data to all/selected columns/rows Delete Delete all/selected rows from table 18

Integrity Constraints in RDBMS Integrity constraints are used to ensure accuracy and consistency of data in a relational database. Types Entity integrity Referential Integrity Domain Integrity User Defined Integrity 19

Integrity Constraints in RDBMS Entity Integrity Primary keys?? 20

Integrity Constraints in RDBMS Entity Integrity Every table must have a primary key Primary key should be unique and not null Used: Insertions and Updates SQL PRIMARY KEY UNIQUE (Candidate Keys) Primary keys Referenced by Foreign keys Indexes 21

Creating Unique Values in RDBMS MS SQL Server Identity (seed, increment) Seed is the initial value Increment is the value by which we need to skip to fetch the next value Identity(1,2) will generate sequence numbers 1,3,5,7 MySQL AUTO_INCREMENT The starting value is 1, and it will increment by 1 for each new record. AUTO_INCREMENT = k (start from k value) 22

Integrity Constraints in RDBMS Referential Integrity The referential integrity constraint, states that a tuple in one relation that refers to another relation must refer to an existing tuple in that relation. Foreign Key value Primary Key value Referential Integrity in SQL pk type PRIMARY KEY FOREIGN KEY fk REFERENCES pk Artist Table Primary Key Foreign Key Song Table artist_name artist_id artist_id song_id song_name Aaa 1 Bbb 2 Ccc 3 2 1 xxx 1 2 www 2 3 zzz 23

Integrity Constraints in RDBMS Referential Integrity Example Artist Table Primary Key Foreign Key Song Table artist_name artist_id artist_id song_id song_name Aaa 1 Bbb 2 Ccc 3 2 1 xxx 1 2 www 2 3 zzz Delete tuple (2, Bbb) Possible scenarios Reject Set Song.artist_id = null Delete Song tuples 24

Integrity Constraints in RDBMS Referential Integrity Constraints in SQL CREATE TABLE a (... FOREIGN KEY fk REFERENCES pk action... ) Where action is: nothing or NO ACTION (deletion/update rejected) ON DELETE SET NULL / ON UPDATE SET NULL ON DELETE CASCADE / ON UPDATE CASCADE 25

Integrity Constraints in RDBMS Domain Integrity Column (attribute) Constraints NOT NULL CHECK (e.g., CHECK( age >= 0) ) Domain Constraints Use Column Constraints Similar to user-defined datatypes Reusability Programmer friendly (gives names) Used: Insertions and Updates 26

Integrity Constraints in RDBMS Domain Integrity Example Define Domain Constraint CREATE DOMAIN validage INT ( CONSTRAINT positive CHECK (VALUE >= 0), CONSTRAINT limit CHECK (VALUE < 150 ), CONSTRAINT not-null-value CHECK( VALUE NOT NULL)); Use Domain Constraint CREATE TABLE Employee (... age validage, ) 27

Views Intro View is a virtual table Create View SQL syntax CREATE VIEW view_name [(view_columns)] AS SQL Query View contents are specified by the View definition View contains rows and columns, just like a real table A View can defined over several tables or other views A View may define different/new attributes If a change occurs in the tables it is reflected into the view Queries over Views are the same as queries over relations Updates under several restrictions 28

Views Examples CREATE VIEW OLD_PERSONS AS select * from Person where Age > 80; CREATE VIEW OLD_PERSONS_NAMES (onoma) AS select FirstName from Person where Age > 80; 29

Views vs. Tables Views can represent a subset (or "superset") of the data contained in a table Views can join & simplify multiple tables Views can act as aggregated tables (sum, average etc.) and present the calculated results Views require very little storing space (only the definition of the view) Views can limit the degree of exposure of data to the outer world (Users groups) Views allow application interoperability through columns renaming/rearranging 30

Triggers Intro A Trigger is procedural code that is automatically executed in response to certain events on a particular table or view Triggers are stored in, and managed by the RDBMS Each trigger is attached to a single specified table/view Triggers Events: insert, update, delete Using triggers, data integrity problems can be eliminated Triggers can access and/or modify other tables Triggers can executed Before a specified event After a specified event 31

Client / Server Database Model 5 Results are presented to the user 1 User Submits Query 2 Query is sent to the server 3 Query is executed on the server Database Client 4 Results are sent back to the client Server 32

JDBC Intro JDBC (Java Database Connectivity) An API for the Java programming language that defines how a client interact with a database. JDBC works with Java on a variety of platforms, e.g., Windows, Mac OS, and the various versions of UNIX. 33

JDBC Architecture Two layers Architecture JDBC API: Java Application to JDBC Driver Manager JDBC Driver API: JDBC Driver Manager to (databasespecific) Driver Ensures that the correct driver is used to access each data source. Multiple concurrent drivers connected to multiple heterogeneous databases. 34

JDBC Basic Steps Seven steps in querying databases 1. Load the JDBC driver 2. Define the connection URL 3. Establish the connection 4. Create a statement object 5. Execute a query or update 6. Process the results 7. Close the connection 35

JDBC vs. Java Data types 36

Basic JDBC Components Connection: connection objects are used to communication with database. Statement: Statement objects used to submit the SQL statements to the database. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. ResultSetMetaData: Info regarding Result set object (e.g., number of columns, columns types, etc.) 37

Statement Methods boolean execute(string SQL) Execute SQL statements. Returns true if a ResultSet object can be retrieved; otherwise, it returns false. ResultSet executequery(string SQL) Use this method when you expect to get a result set, as you would with a SELECT statement. Returns a ResultSet object. int executeupdate(string SQL) Used for executing INSERT, UPDATE, or DELETE SQL statements Returns the numbers of rows affected by the execution of the SQL statement. 38

ResultSet Methods boolean first() Moves the cursor to the first row void last() Moves the cursor to the last row. boolean previous() Moves the cursor to the previous row boolean next() Moves the cursor to the next row int getrow() Returns the row number that the cursor is pointing to. int getxxx(string columnname) Returns the value in the current row in the column named columnname Where XXX is int, float, long, String, etc. int getxxx(int columnindex) Returns the value in the current row in the specified column index. The column index starts at 1 Where XXX is int, float, long, String, etc. 39

ResultSetMetaData Methods Create ResultSetMetadata object of by calling getmetadata() method from ResultSet object. ResultSetMetaData rsmd=res.getmeatadata(); int getcolumncount() Returns the number of columns in this ResultSet object. String getcolumnname(int columnindex) Get the designated column's name. int getcolumntype(int columnindex) Retrieves the designated column's SQL type. String gettablename(int columnindex) Gets the designated column's table name. 40

Database Example CREATE DATABASE dbtest CREATE TABLE Employee ( ID int PRIMARY KEY, Name varchar(40), Salary demical(10,2) ) Use ConnectSQLServer.java to access dbtest Database 41

ConnectSQLServer.java import java.sql.connection; import java.sql.drivermanager; import java.sql.resultset; import java.sql.statement; public class ConnectSQLServer { public static void main(string[] args) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection connection = DriverManager.getConnection( "jdbc:sqlserver://localhost:1433;databasename=dbtest","myusername", "mypassword"); Statement statement = connection.createstatement(); String querystring = Select Name, Salary from Employee"; ResultSet resultset = statement.executequery(querystring); while (resultset.next()) { System.out.println("Employee Name:" + rs.getstring("name") ); System.out.println("Employee Salary:" + rs.getfloat("salary") ) ; } } } } catch (Exception e) { e.printstacktrace(); } 42

Microsoft SQL Server MS SQL Server Database server Product of Microsoft Relational DB From: 1989 (SQL Server 1.0) To: July 2011 (SQL Server 2008 R2) Runs on: Windows 7, Vista, Server (03&08), XP, ME, 98 Platform: 32 & 64 SQL Server & MySQL Installation Guides db1 course @ mycourses.ntua.gr 43

Project Implementation Linux/7/Vista/Win2000/XP/2003/98/ME SQL Server 2000/2005/2008/postgres/mysql JAVA, VB.NET, PYTHON, C++. SQL Server 2005/2008 ΒΙΒΛΙΟΘΗΚΗ ΗΛΕΚΤΡΟΛΟΓΩΝ For more info check installations guides (@ mycourses) 44

Project Requirements Database Design Database Design Database Design Use Integrity Constraints!!! Define meaningful Queries, Views, etc. Graphical User Interface Fully functional View DB Insert DB Query DB etc. User-friendly Drop-down list Radio button Check box etc. 45

Thank you 46