Application Users. Application Programs. Some Reasons for Using a DBMS (Database Management System)

Size: px
Start display at page:

Download "Application Users. Application Programs. Some Reasons for Using a DBMS (Database Management System)"

Transcription

1 Brief Introduction to DATABASE 1. What is a Database System? Application Users Application Programs Database Management System Database Management System database Some Reasons for Using a DBMS (Database Management System) Persistence of data Sharing of data between programs Handle concurrent requests for data access Transactions that can be committed or rolled back Report generation Sometimes database means a program for managing data Example: Oracle Corporation is a database company. MySQL is a database. Sometimes database means a collection of data Example: I keep a database of my CD collection on 3 by 5 cards Sometimes database means a set of tables, indexes, and views Example: My program needs to connect to the Airline Reservation database, which uses MySQL 2. Types of Databases Relational: Data is stored in tables 1

2 Object-Oriented: Tables can be classed and/or sub-classed, and Programmer can define methods on tables Object: Objects are stored in the database 3. Relational, Object-Relational, O-O Databases and SQL Database consists of a number of tables. Table is a collection of records. Each column of data has a type Firstname Lastname Phone Code Bill Clinton George Bush John Kelly Use SQL (Structured Query Language) to access data in the database Some Available DBMS systems Oracle, MySQL, DB2, SQL Server, Access, Sybase, etc. Some Open Source DBMS Systems Postgres, MySQL community server (??) 4. Rational Database and Relational Data Model Most of today s database systems are relational database systems, based on the relational data model. A relational data model has three key components: structure, integrity and languages. Structure defines the representation of the data. Integrity imposes constraints on the data. Language provides the means for accessing and manipulating data. Relational Structure A relational database consists of a set of relations. A relation has two things in one: a schema and an instance of the schema. The schema defines the relation and an instance is the content of the relation at a given time. An instance of a relation is nothing more than a table with rows and named columns. For convenience with no confusion, we refer instances of relations as just relations or tables. 2

3 Course Table Relation/Table Name Columns/Attributes Course Table Tuples/ Rows courseid subjectid coursenumber title numofcredits CSCI 1301 Introduction to Java I CSCI 1302 Introduction to Java II CSCI 3720 Database Systems CSCI 4750 Rapid Java Application MATH 2750 Calculus I MATH 3750 Calculus II EDUC 1111 Reading ITEC 1344 Database Administration 3 Student Table Student Table ssn firstname mi lastname phone birthdate street zipcode deptid Jacob R Smith Kingston Street BIOL John K Stevenson null 100 Main Street BIOL George K Smith Abercorn St CS Frank E Jones Main Street BIOL Jean K Smith Main Street CHEM Josh R Woo Franklin St CHEM Josh R Smith Main Street BIOL Joy P Kennedy Bay Street CS Toni R Peterson Bay Street MATH Patrick R Stoneman Washington St MATH Rick R Carter West Ford St BIOL 3

4 Enrollment Table Enrollment Table ssn courseid dateregistered grade A B C D F A B C D A A B F F D D A D B Table vs. File NOTE: A table or a relation is not same as a file. Most of the relational database systems store multiple tables in a file. Integrity Constraints An integrity constraint imposes a condition that all legal instances of the relations must satisfy. In general, there are three types of constraints: domain constraint, primary key constraint, and foreign key constraint. Domain constraints and primary key constraints are known as intra-relational constraints, meaning that a constraint involves only one relation. The foreign key constraint is known as inter-relational, meaning that a constraint involves more than one relation. 4

5 Domain Constraints, Primary Key Constraints, Foreign Key Constraints Enrollment Table ssn courseid dateregistered grade A B C... Course Table Each value in courseid in the Enrollment table must match a value in courseid in the Course table courseid subjectid coursenumber title numofcredits CSCI 1301 Introduction to Java I CSCI 1302 Introduction to Java II CSCI 3720 Database Systems 3... Each row must have a value for couserid, and the value must be unique Each value in the numofcredits column must be greater than 0 and less than 5 Domain Constraints Domain constraints specify the permissible values for an attribute. Domains can be specified using standard data types such as integers, floating-point numbers, fixed-length strings, and variant-length strings. The standard data type specifies a broad range of values. Additional constraints can be specified to narrow the ranges. You can also specify whether an attribute can be null. Example create table Course( subjectcode char(4) not null, coursenumber int not null, title varchar(50) not null, numofcredits int not null constraint greaterthanone check (numofcredits >= 1)); Superkey A superkey is an attribute or a set of attributes that uniquely identify the relation. That is, no two tuples have the same values on the superkey. By definition, a relation consists of a set of distinct tuples. The set of all attributes in the relation forms a superkey. Key and Candidate Key 5

6 A key K is a minimal superkey, meaning that any proper subset of K is not a superkey. It is possible that a relation has several keys. In this case, each of the keys is called a candidate key. Primary Key The primary key is one of the candidate keys designated by the database designer. The primary key is often used to identify tuples in a relation. create table Course( subjectcode char(4), coursenumber int, title varchar(50), numofcredits int constraint greaterthanone check (numofcredits >= 1), primary key (subjectcode, coursenumber)); Primary Key Constraints The primary key constraint specifies that the primary key value of a tuple cannot be null and no two tuples in the relation can have the same value on the primary key. The DBMS enforces the primary key constraint. For example, if you attempt to insert a record with the same primary key as an existing record in the table, the DBMS would report an error and reject the operation. Foreign Key Constraints In a relational database, data are related. Tuples in a relation are related and tuples in different relations are related through their common attributes. Informally speaking, the common attributes are foreign keys. The foreign key constraints define the relationships among relations. Formally, a set of attributes FK is a foreign key in a relation R that references relation T if it satisfies the following two rules: 1. The attributes in FK have the same domain as the primary key in T. 2. A non-null value on FK in R must match a primary key value in T. R FK T create table Enrollment ( ssn char(9), courseid char(5), dateregistered date, 6

7 grade char(1), primary key (ssn, courseid), foreign key (ssn) references Student, foreign key (courseid) references Course ); A foreign key is not necessarily the primary key or part of the primary in the relation. For example, subjectcode is a foreign key in the Course table that references the Subject table, but it is not the primary key in Course. departmentcode is a foreign key in the Subject table that references Department, but it is not the primary key in Subject. The referencing relation and the referenced relation may be the same table. For example, supervisorid is a foreign key in Faculty that references facultyid in Faculty. The foreign key is not necessary to have the same name as its referenced primary key as long as they have the same domain. For example, headid is a foreign key in Department that references facultyid in Faculty. A relation may have more than one foreign key. For example, headid and collegecode are both foreign keys in Department. 5. SQL History Evolution of the SQL Standard o First standard approved in 1989 (called SQL-89 or SQL1) o Comprehensive revision in 1992 (SQL-92 or SQL2) o Third big revision in 1999 (SQL-99 known as SQL3) o Other revisions known as SQL:2003, SQL:2006 (XML features), SQL:2008 (more object DB features) Origins of SQL o Originally called SEQUEL (Structured English Query Language), then SQL (Structured Query Language) o Developed at IBM Research for experimental relational DBMS called System-R in the 1970s 6. SQL Data Definition and Data Types CREATE statement can be used to: o Create a named database schema o Create individual database tables and specify data types for the table attributes, as well as key, referential integrity, and NOT NULL constraints o Create named constraints Other commands can modify the tables and constraints o DROP and ALTER statements (e.g., Example: ALTER TABLE EMPLOYEE ADD COLUMN JOB VARCHAR(12); The database users must enter values for the new attribute JOB for each EMPLOYEE tuple. 7

8 7. Schema and Catalog Concepts in SQL An SQL schema is identified by a schema name, and includes an authorization identifier to indicate the user or account who owns the schema, as well as descriptors for each element in the schema. Schema elements include tables, constraints, views, domains, and other constructs (such as authorization grants) that describe the schema. Example: CREATE SCHEMA COMPANY AUTHORIZATION JSmith ; Catalog a named collection of schemas in an SQL environment. SQL environment is an installation of an SQL-compliant RDBMS in a computer system. A catalog always contains a special schema called INFORMATION-SCHEMA The CREATE SCHEMA Statement A DBMS can manage multiple databases DBA (or authorized users) can use CREATE SCHEMA to have distinct databases; for example: CREATE SCHEMA COMPANY AUTHORIZATION 'JSmith'; Each database has a schema name (e.g. COMPANY) User 'Smith' will be owner of schema, can create tables, other constructs in that schema Table names can be prefixed by schema name if multiple schemas exist (e.g. COMPANY.EMPLOYEE) Prefix not needed if there is a default schema for the user The CREATE TABLE Command in SQL In its simplest form, specifies a new base relation by giving it a name, and specifying each of its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n), VARCHAR(n), DATE, and other data types) A constraint NOT NULL may be specified on an attribute CREATE TABLE DEPARTMENT ( DNAME VARCHAR(15) NOT NULL, DNUMBER INT NOT NULL, MGRSSN CHAR(9) NOT NULL, MGRSTARTDATE DATE ); CREATE TABLE can also specify the primary key, UNIQUE keys, and referential integrity constraints (foreign keys) Via the PRIMARY KEY, UNIQUE, and FOREIGN KEY phrases CREATE TABLE DEPARTMENT ( DNAME VARCHAR(15) NOT NULL, DNUMBER INT NOT NULL, MGRSSN CHAR(9) NOT NULL, MGRSTARTDATE DATE, PRIMARY KEY (DNUMBER), UNIQUE (DNAME), FOREIGN KEY(MGRSSN) REFERENCES EMPLOYEE (SSN)); 8

9 Indices Indices make accessing faster Primary keys automatically have an index The CREATE INDEX command creates indices CREATE INDEX dname_index on DEPARTMENT (DNAME); 8.Understanding Database based on MySQL Connecting to the Database Can be done with: Mysql command line tool - mysql GUI clients Program Examples (by MySQL command line tool) You can choose mysqld as a service, or mysqld as a standalone daemon. mysqld --standalone C:\mysql\bin\mysqld --standalone debug mysqladmin" p -u root shutdown $mysql h localhost u user p GUI Clients MySQL Workbench SQL Syntax Names Databases, table columns & indexes have names Legal Characters Alphanumeric characters, '_', '$' Names can start with: Letter Underscore Letter with diacritical marks and some non-latin letters Name length 64 characters - MySQL Names are not case sensitive 9

10 Data Types Numeric Values Integer: decimal or hexadecimal Floating-point: scientific, real number (e.g., ) String Values MySQL example: this is a string or this is a string Escape Sequence \' Single quote \b Backspace \n Newline \r Tab \\ Backslash Comments (MySQL example) -- this is a comment /* this is a comment */ #this is a comment Numeric Data Types Numeric(10, 2) defines a number with maximum of 10 digits with 2 of the 10 to the right of the decimal point (e.g., ) Decimal and numeric are different names for the same type. 10

11 String Types Type char(n) varchar(n) text Blob (MySQL) Description Fixed-length blank padded Variable-length with limit Variable unlimited length Variable (not specifically limited) length binary string char & varchar are the most common string types char is fixed-width: shorter strings are padded (with blanks) text can be of any size MySQL limits char and varchar to 255 characters Dates DATETIME YYYY-MM-DD HH:MM DATE YYYY-MM-DD format TIMESTAMP Basically now is same as DATETIME Common SQL Statements SELECT INSERT UPDATE DELETE CREATE TABLE DROP TABLE ALTER TABLE CREATE INDEX DROP INDEX CREATE VIEW DROP VIEW Retrieves data from table(s) Adds row(s) to a table Change field(s) in record(s) Removes row(s) from a table Data Definition Define a table and its columns (fields) Deletes a table Adds a new column, add/drop primary key Create an index Delete an index Define a logical table from other table(s) view(s) Deletes a view CREATE DATABASE General Form CREATE DATABASE [IF NOT EXISTS] db_name [create_specification [, create_specification]...] create_specification: [DEFAULT] CHARACTER SET charset_name [DEFAULT] COLLATE collation_name (Example) mysql> create database DBMSExamples; Query OK, 1 row affected (0.00 sec) 11

12 USE Sets a default database for subsequent queries General Form USE db_name (Example) mysql> use DBMSExamples; Database changed CREATE TABLE General Form CREATE TABLE table_name ( col_name col_type [ NOT NULL PRIMARY KEY] [, col_name col_type [ NOT NULL PRIMARY KEY]]* ) mysql> use DBMSExamples; Database changed (Example) Mysql> CREATE TABLE students -> ( -> firstname CHAR(20) NOT NULL, -> lastname CHAR(20), -> phone CHAR(10), -> code INTEGER -> ); Query OK, 0 rows affected (0.61 sec) mysql> CREATE TABLE codes -> ( -> code INTEGER, -> name CHAR(20) -> ); Query OK, 0 rows affected (0.63 sec) mysql> DESCRIBE students -> ; Field Type Null Key Default Extra firstname char(20) NO lastname char(20) YES NULL phone char(10) YES NULL code int(11) YES NULL

13 4 rows in set (0.11 sec) mysql> desc students; Field Type Null Key Default Extra firstname char(20) NO lastname char(20) YES NULL phone char(10) YES NULL code int(11) YES NULL rows in set (0.00 sec) mysql> explain students -> \g Field Type Null Key Default Extra firstname char(20) NO lastname char(20) YES NULL phone char(10) YES NULL code int(11) YES NULL rows in set (0.00 sec) mysql> show columns from students -> ; Field Type Null Key Default Extra firstname char(20) NO lastname char(20) YES NULL phone char(10) YES NULL code int(11) YES NULL rows in set (0.02 sec) mysql> show fields from students \g Field Type Null Key Default Extra firstname char(20) NO lastname char(20) YES NULL phone char(10) YES NULL code int(11) YES NULL rows in set (0.00 sec) SELECT Gets the data from one or more tables 13

14 General Form SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY] [DISTINCT DISTINCTROW ALL] select_expression,... [INTO {OUTFILE DUMPFILE} 'file_name' export_options] [FROM table_references [WHERE where_definition] [GROUP BY {unsigned_integer col_name formula} [ASC DESC],... [WITH ROLLUP]] [HAVING where_definition] [ORDER BY {unsigned_integer col_name formula} [ASC DESC],...] [LIMIT [offset,] row_count row_count OFFSET offset] [PROCEDURE procedure_name(argument_list)] [FOR UPDATE LOCK IN SHARE MODE]] mysql> SELECT * FROM students; Empty set (0.00 sec) INSERT Add data to a table General Form INSERT [LOW_PRIORITY DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ((expression DEFAULT),...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expression,... ] (Example) mysql> INSERT -> INTO students (firstname, lastname, phone. Code) -> VALUES ('bill', 'clinton', ' ,2000); Query OK, 1 row affected (0.50 sec) mysql> INSERT -> INTO codes (code, name) -> VALUES (2000, 'marginal' ); Query OK, 1 row affected (0.48 sec) mysql> SELECT firstname, phone FROM students; firstname phone bill row in set (0.00 sec) 14

15 mysql> SELECT lastname, name -> FROM students, codes -> WHERE students.code = codes.code; lastname name clinton marginal row in set (0.01 sec) mysql> SELECT students.lastname, codes.name -> FROM students, codes -> WHERE students.code = codes.code; lastname name clinton marginal row in set (0.44 sec) mysql> Update Modify existing data in a database General Form UPDATE [LOW_PRIORITY] [IGNORE] tbl_name [, tbl_name...] SET col_name1=expr1 [, col_name2=expr2...] [WHERE where_definition] Example mysql> update students -> set firstname='hilary' -> where lastname="clinton"; Query OK, 1 row affected (0.52 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from students; firstname lastname phone code Hilary clinton row in set (0.00 sec) mysql> ALTER TABLE students ADD column foo CHAR(40); Query OK, 1 row affected (0.03 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> DROP TABLE students; 15

16 Query OK, 0 rows affected (0.01 sec) mysql> DROP DATABASE databaseexamples; Query OK, 0 rows affected (0.00 sec) 9. JDBC (Java Database Connectivity-- Connecting to DBMS) Oracle JDBC Tutorial & Documentation Connector-J, MySql JDBC Driver Documentation, JDBC Drivers Java supports four types of JDBC drivers JDBC-ODBC bridge plus ODBC driver: Java code access ODBC native binary drivers, ODBC driver accesses databases, ODBC drivers must be installed on each client Native-API partly-java driver: Java code accesses database specific native binary drivers JDBC-Net pure Java driver: Java code accesses database via DBMS-independent net protocol Pure Java driver In a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. 16

17 This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically. MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. The JDBC API is comprised of two packages: java.sql javax.sql The JDBC Interfaces Driver Connection Connection Statement Statement Statement Statement ResultSet ResultSet ResultSet ResultSet 17

18 Developing JDBC Programs Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Driver Class Source Access sun.jdbc.odbc.jdbcodbcdriver Already in JDK MySQL com.mysql.jdbc.driver Oracle oracle.jdbc.driver.oracledriver Connection connection = DriverManager.getConnection(databaseURL); Database Access MySQL Oracle URL Pattern jdbc:odbc:datasource jdbc:mysql://hostname/dbname jdbc:oracle:thin:@hostname:port#:oracledbsid Examples: For Access: Connection connection = DriverManager.getConnection ("jdbc:odbc:examplemdbdatasource"); For MySQL: Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); For Oracle: Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@company.com:1521:orcl", "bob", "feiner"); Creating statement: Statement statement = connection.createstatement(); Executing statement (for update, delete, insert): statement.executeupdate ("create table Temp (col1 char(5), col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = statement.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = stmt.executequery 18

19 ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Processing ResultSet (for select): // Iterate through the result and print the student names while (resultset.next()) System.out.println(resultSet.getString(1) + " " + resultset.getstring(2) + ". " + resultset.getstring(3)); Queries executeupdate Use for INSERT, UPDATE, DELETE or SQL that return nothing executequery Use for SQL (SELECT) that return a result set execute Use for SQL that return multiple result sets Uncommon ResultSet ResultSet - Result of a Query - JDBC returns a ResultSet as a result of a query - A ResultSet contains all the rows and columns that satisfy the SQL statement - A cursor is maintained to the current row of the data 19

20 - The cursor is valid until the ResultSet object or its Statement object is closed - next() method advances the cursor to the next row - You can access columns of the current row by index or name ResultSet has getxxx methods that: has either a column name or column index as argument returns the data in that column converted to type XXX getobject - An alternative to the getxxx method Rather than ResultSet tablelist = gettables.executequery("select * FROM name"); String firstname = tablelist.getstring( 1); - Can use ResultSet tablelist = gettables.executequery("select * FROM name"); String firstname = (String) tablelist.getobject( 1); getobject( int k) returns the object in the k th column of the current row getobject( String columnname) returns the object in the named column PreparedStatement The PreparedStatement interface is designed to execute dynamic SQL statements and SQL-stored procedures with IN parameters. These SQL statements and stored procedures are precompiled for efficient use when repeatedly executed. Statement pstmt = connection.preparestatement ("insert into Student (firstname, mi, lastname) + values (?,?,?)"); Retrieving Database Metadata Database metadata is the information that describes database itself. JDBC provides the DatabaseMetaData interface for obtaining database wide information and the ResultSetMetaData interface for obtaining the information on the specific ResultSet. The DatabaseMetaData interface provides more than 100 methods for getting database metadata concerning the database as a whole. These methods can be divided into three groups: for retrieving general information, for finding database capabilities, and for getting object descriptions. The general information includes the URL, username, product name, product version, driver name, driver version, available functions, available data types and so on. Example: DatabaseMetaData dbmetadata = connection.getmetadata(); 20

21 System.out.println("database URL: " + dbmetadata.geturl()); System.out.println("database username: " + dbmetadata.getusername()); System.out.println("database product name: " + dbmetadata.getdatabaseproductname()); System.out.println("database product version: " + dbmetadata.getdatabaseproductversion()); System.out.println("JDBC driver name: " + dbmetadata.getdrivername()); System.out.println("JDBC driver version: " + dbmetadata.getdriverversion()); System.out.println("JDBC driver major version: " + new Integer(dbMetaData.getDriverMajorVersion())); System.out.println("JDBC driver minor version: " + new Integer(dbMetaData.getDriverMinorVersion())); System.out.println("Max number of connections: " + new Integer(dbMetaData.getMaxConnections())); System.out.println("MaxTableNameLentgh: " + new Integer(dbMetaData.getMaxTableNameLength())); System.out.println("MaxColumnsInTable: " + new Integer(dbMetaData.getMaxColumnsInTable())); connection.close(); CallableStatement The CallableStatement interface is used to execute SQL-stored procedure/function. Example: drop function if exists studentfound; delimiter // create function studentfound(first VARCHAR(20), last VARCHAR(20)) returns int begin declare result int; select count(*) into result from Student where Student.firstName = first and Student.lastName = last; return result; end; // 21

22 delimiter ; mysql> select studentfound('king', 'Smith'); CallableStatement callablestatement = conn.preparecall( "{? = call studentfound(?,?)}"); java.util.scanner input = new java.util.scanner(system.in); String firstname = "Jacob"; String lastname = "Smith"; callablestatement.setstring(2, firstname); callablestatement.setstring(3, lastname); callablestatement.registeroutparameter(1, Types.INTEGER); callablestatement.execute(); if (callablestatement.getint(1) >= 1) { out.println(firstname + " " + lastname + " is in the database" + "<br>"); } else { out.println(firstname + " " + lastname + " is not in the database" + "<br>"); Data Conversion 22

23 Some Cautions Mixing ResultSets Can't have two active result sets on same statement Connection rugby; rugby = DriverManager.getConnection( dburl, user, password); Statement gettables = rugby.createstatement(); ResultSet count = gettables.executequery("select COUNT(*) FROM name"); ResultSet tablelist = gettables.executequery("select * FROM name"); while (tablelist.next() ) System.out.println("Last Name: " + tablelist.getobject(1) + '\t' + "First Name: " + tablelist.getobject( "first_name")); // Raises java.sql.sqlexception count.getobject(1); rugby.close(); this can happen when two threads have access to the same statement Two Statements on one Connection work Connection rugby; rugby = DriverManager.getConnection( dburl, user, password); Statement gettables = rugby.createstatement(); Statement tablesize = rugby.createstatement(); ResultSet count = gettables.executequery("select COUNT(*) FROM name"); ResultSet tablelist = tablesize.executequery("select * FROM name"); while (tablelist.next() ) System.out.println("Last Name: " + tablelist.getobject(1) + '\t' + "First Name: " + tablelist.getobject( "first_name")); count.next(); System.out.println("Count: " + count.getobject(1) ); count.close(); tablelist.close(); rugby.close(); Threads & Connections - Some JDBC drivers are not thread safe - If two threads access the same connection results may get mixed up MySql driver is thread safe - When two threads make a request on the same connection - The second thread blocks until the first thread get it its results - Can use more than one connection but - Each connection requires a process on the database 23

24 10. Some Data Modeling Terms and JOIN operations Entity: a distinct class of things about which something is known Entity Occurrence: particular instance of an entity class. In a database entity occurrences are records in a table Attribute: an abstraction belonging to or characteristic of an entity Primary Key (unique identifier): an attribute (or set of attributes) that uniquely defines an entity Relationship: an abstraction belonging to or characteristic of two entities or parts together Foreign Key: a unique identifier in a record representing another record Entity Relationship (ER) Diagram Crow s Foot ERD Entity (car) with: Attributes (Color, make, model, serial number) Primary key (serial number) Relationship between Car and Person entities. Car must have one and only one owner. Person may own zero, one or more cars. Person can own many cars 24

25 25

26 ER to Relational mapping ER-to-Relational Mapping Algorithm COMPANY database example Assume that the mapping will create tables with simple single-valued attributes Step 1: Mapping of Regular Entity Types For each regular entity type, create a relation R that includes all the simple attributes of E Called entity relations Each tuple represents an entity instance Step 2: Mapping of Weak Entity Types For each weak entity type, create a relation R and include all simple attributes of the entity type as attributes of R Include primary key attribute of owner as foreign key attributes of R Step 3: Mapping of Binary 1:1 Relationship Types For each binary 1:1 relationship type Identify relations that correspond to entity types participating in R Possible approaches: Foreign key approach Merged relationship approach Crossreference or relationship relation approach 26

27 Step 4: Mapping of Binary 1:N Relationship Types For each regular binary 1:N relationship type Identify relation that represents participating entity type at N-side of relationship type Include primary key of other entity type as foreign key in S Include simple attributes of 1:N relationship type as attributes of S Alternative approach Use the relationship relation (cross-reference) option as in the third option for binary 1:1 relationships Step 5: Mapping of Binary M:N Relationship Types For each binary M:N relationship type Create a new relation S Include primary key of participating entity types as foreign key attributes in S Include any simple attributes of M:N relationship type Step 6: Mapping of Multivalued Attributes For each multivalued attribute Create a new relation Primary key of R is the combination of A and K If the multivalued attribute is composite, include its simple components Step 7: Mapping of N-ary Relationship Types For each n-ary relationship type R Create a new relation S to represent R Include primary keys of participating entity types as foreign keys Include any simple attributes as attributes 27

28 JOIN Operations Primary Key A primary key is one that uniquely identifies a row in a table. A Simple Faculty Table name Brown 1 Clinton 2 Bush 3 faculty_id CREATE TABLE faculty ( name CHAR(20) NOT NULL, faculty_id INTEGER AUTO_INCREMENT PRIMARY KEY ); Adding Values INSERT INTO faculty ( name) VALUES ('White'); INSERT INTO faculty ( name) VALUES ('Beck'); INSERT INTO faculty ( name) VALUES ('Anantha'); INSERT INTO faculty ( name) VALUES ('Vinge'); select * from faculty; 28

29 Result name faculty_id White 1 Beck 2 Anantha 3 Vinge 4 (4 rows) CREATE TABLE office_hours ( start_time TIME NOT NULL, end_time TIME NOT NULL, day CHAR(3) NOT NULL, faculty_id INTEGER REFERENCES faculty, office_hour_id INTEGER AUTO_INCREMENT PRIMARY KEY ); faculty_id is a foreign key REFERENCES faculty insures that only valid references are made start_time end_time day faculty_id office_hour_id 10:00 11:00 Wed 1 1 8:00 12:00 Mon :00 18:30 Tue 1 3 9:00 10:30 Tue 3 4 9:00 10:30 Thu :00 16:00 Fri 1 6 INSERT INTO office_hours ( start_time, end_time, day, faculty_id ) VALUES ( '10:00:00', '11:00:00', 'Wed', 1 ); The problem is that we need to know the id for the faculty Using Select INSERT INTO office_hours (start_time, end_time, day, faculty_id ) SELECT '8:00:00' AS start_time, '12:00:00' AS end_time, 'Fri' AS day, faculty_id AS faculty_id FROM 29

30 faculty WHERE name = 'Beck'; Getting Office Hours SELECT name, start_time, end_time, day FROM office_hours, faculty WHERE faculty.faculty_id = office_hours.faculty_id; mysql> SELECT -> name, start_time, end_time, day -> FROM -> office_hours, faculty -> WHERE -> faculty.faculty_id = office_hours.faculty_id; name start_time end_time day White 10:00:00 11:00:00 Wed Beck 08:00:00 12:00:00 Mon White 17:00:00 12:30:00 Tue Anantha 09:00:00 10:30:00 Tue Anantha 09:00:00 10:30:00 Thu White 15:00:00 16:00:00 Fri rows in set (0.00 sec) mysql> name start_time end_time day Whitney 10:00:00 11:00:00 Wed Beck 08:00:00 12:00:00 Mon Whitney 17:00:00 18:30:00 Tue Whitney 15:00:00 16:00:00 Fri Anantha 09:00:00 10:30:00 Tue Anantha 09:00:00 10:30:00 Thu Some Selection SELECT name, start_time, end_time, day FROM office_hours, faculty WHERE 30

31 faculty.faculty_id = office_hours.faculty_id AND start_time > '09:00:00' AND end_time < '16:30:00' ORDER BY Name; name start_time end_time day white 10:00:00 11:00:00 Wed white 15:00:00 16:00:00 Fri Joins People id first_name last_name 1 Roger Whitte 2 Leland Beck 3 Carl Eckberg _Addresses id user_name host person_id 1 beck cs.lehman.edu 2 2 white cs.lehman.edu 1 3 white cs2.lehman.edu 1 4 foo cs2.lehman.edu The tables have a column in common as _addresses.person_id refers to people.id. So we can create a new table by joining the two tables together on that column Inner Join (or just Join) Only uses entries linked in two tables first_name last_name user_name host Leland Beck beck cs.sdsu.edu Roger white white cs.sdsu.edu Roger White white rohan.sdsu.edu select first_name, last_name, user_name, host from people, _address where 31

32 Outer Join people.id = _address.person_id; or equivalently select first_name, last_name, user_name, host from people inner join _address on (people.id = _address.person_id); mysql> select -> first_name, last_name, user_name, host -> from -> people, _address -> where -> people.id = _address.person_id; first_name last_name user_name host Leland Beck beck cs.lehman.edu Roger White white cs.lehman.edu Roger White white cs2.lehman.edu rows in set (0.00 sec) mysql> select -> first_name, last_name, user_name, host -> from -> people inner join _address -> on -> (people.id = _address.person_id); first_name last_name user_name host Leland Beck beck cs.lehman.edu Roger White white cs.lehman.edu Roger White white cs2.lehman.edu rows in set (0.00 sec) mysql> Uses all entries from a table Left Outer Join Use all entries from the left table 32

33 first_name last_name user_name host Leland Beck beck cs.lehman.edu Roger White white cs.lehman.edu Roger White white cs2.lehman.edu Carl Eckberg select first_name, last_name, user_name, host from people left outer join _address on (people.id = _address.person_id); Right Outer Join first_name last_name user_name host Leland Beck beck cs.lehman.edu Roger white white cs.lehman.edu Roger Whitney whitney cs2.lehman.edu foo cs2..lehman.edu Use all entries from the right table select first_name, last_name, user_name, host from people right outer join _address on (people.id = _address.person_id); A right outer join B & B left outer join A The following two statements are equivalent select first_name, last_name, user_name, host from people right outer join _address on (people.id = _address.person_id); select first_name, last_name, user_name, host 33

34 from _address left outer join people on (people.id = _address.person_id); 11. Normalization The normal forms defined in relational database theory represent guidelines for record design. The guidelines corresponding to first through fifth normal forms are presented here, in terms that do not require an understanding of relational theory. The design guidelines are meaningful even if one is not using a relational database system. We present the guidelines without referring to the concepts of the relational model in order to emphasize their generality, and also to make them easier to understand. Our presentation conveys an intuitive sense of the intended constraints on record design, although in its informality it may be imprecise in some technical details. The normalization rules are designed to prevent update anomalies and data inconsistencies. With respect to performance tradeoffs, these guidelines are biased toward the assumption that all nonkey fields will be updated frequently. They tend to penalize retrieval, since data which may have been retrievable from one record in an un-normalized design may have to be retrieved from several records in the normalized form. There is no obligation to fully normalize all records when actual performance requirements are taken into account. 1 st, 2 nd, 3 rd, BCNF will be discussed. 12. Object relational Mapping (ORM) Will be updated 13. Views, Stored Procedures(Functions), Trigger Examples will be added if necessary 34

Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS)

Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS) Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS) Oracle JDBC Tutorial & Documentation http://docs.oracle.com/javase/tutorial/jdbc/basics/ Connector-J, MySql JDBC Driver Documentation,

More information

Pagina 1 di 7 13.1.7. SELECT Syntax 13.1.7.1. JOIN Syntax 13.1.7.2. UNION Syntax SELECT [ALL DISTINCT DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]

More information

SELECT WHERE JOIN. DBMS - Select. Robert Lowe. Division of Mathematics and Computer Science Maryville College. February 16, 2016

SELECT WHERE JOIN. DBMS - Select. Robert Lowe. Division of Mathematics and Computer Science Maryville College. February 16, 2016 Division of Mathematics and Computer Science Maryville College February 16, 2016 Outline 1 2 3 Syntax [ALL DISTINCT DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]

More information

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul 1 EGCI 321: Database Systems Dr. Tanasanee Phienthrakul 2 Chapter 10 Data Definition Language (DDL) 3 Basic SQL SQL language Considered one of the major reasons for the commercial success of relational

More information

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

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 6 Basic SQL Slide 6-2 Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features

More information

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Database Access with JDBC Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@ase.au.dk Overview Overview of JDBC technology JDBC drivers Seven basic steps in using JDBC Retrieving

More information

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

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement Chapter 4 Basic SQL Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries,

More information

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

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210 SQL: Concepts Todd Bacastow IST 210: Organization of Data 2/17/2004 1 Design questions How many entities are there? What are the major entities? What are the attributes of each entity? Is there a unique

More information

SQL Introduction. CS 377: Database Systems

SQL Introduction. CS 377: Database Systems SQL Introduction CS 377: Database Systems Recap: Last Two Weeks Requirement analysis Conceptual design Logical design Physical dependence Requirement specification Conceptual data model (ER Model) Representation

More information

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features of SQL Textbook Chapter 6 CSIE30600/CSIEB0290

More information

CSIE30600 Database Systems Basic SQL 2. Outline

CSIE30600 Database Systems Basic SQL 2. Outline Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features of SQL CSIE30600 Database Systems

More information

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

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL DDL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Overview Structured Query Language or SQL is the standard query language

More information

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

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra Relational Data Model and Relational Constraints Part 1 A simplified diagram to illustrate the main

More information

PERSİSTENCE OBJECT RELATİON MAPPİNG

PERSİSTENCE OBJECT RELATİON MAPPİNG PERSİSTENCE Most of the applications require storing and retrieving objects in a persistent storage mechanism. This chapter introduces how to store and retrieve information in a persistent storage with

More information

Relational Database Systems Part 01. Karine Reis Ferreira

Relational Database Systems Part 01. Karine Reis Ferreira Relational Database Systems Part 01 Karine Reis Ferreira karine@dpi.inpe.br Aula da disciplina Computação Aplicada I (CAP 241) 2016 Database System Database: is a collection of related data. represents

More information

Working with Databases and Java

Working with Databases and Java Working with Databases and Java Pedro Contreras Department of Computer Science Royal Holloway, University of London January 30, 2008 Outline Introduction to relational databases Introduction to Structured

More information

The Relational Model. Chapter 3

The Relational Model. Chapter 3 The Relational Model Chapter 3 Why Study the Relational Model? Most widely used model. Systems: IBM DB2, Informix, Microsoft (Access and SQL Server), Oracle, Sybase, MySQL, etc. Legacy systems in older

More information

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

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. JDBC Drivers Type 1 What is JDBC Driver? JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. For example, using JDBC drivers enable you to open database

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval

More information

Chapter 16: Databases

Chapter 16: Databases Chapter 16: Databases Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 16 discusses the following main topics: Introduction to Database

More information

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall The Relational Model Chapter 3 Comp 521 Files and Databases Fall 2014 1 Why the Relational Model? Most widely used model by industry. IBM, Informix, Microsoft, Oracle, Sybase, MySQL, Postgres, Sqlite,

More information

Introduction to Data Management. Lecture #4 (E-R Relational Translation)

Introduction to Data Management. Lecture #4 (E-R Relational Translation) Introduction to Data Management Lecture #4 (E-R Relational Translation) Instructor: Mike Carey mjcarey@ics.uci.edu Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Announcements v Today

More information

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1 The Relational Model Chapter 3 Database Management Systems, R. Ramakrishnan and J. Gehrke 1 Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc.

More information

Model Question Paper. Credits: 4 Marks: 140

Model Question Paper. Credits: 4 Marks: 140 Model Question Paper Subject Code: BT0075 Subject Name: RDBMS and MySQL Credits: 4 Marks: 140 Part A (One mark questions) 1. MySQL Server works in A. client/server B. specification gap embedded systems

More information

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

The Relational Model. Why Study the Relational Model? Relational Database: Definitions The Relational Model Database Management Systems, R. Ramakrishnan and J. Gehrke 1 Why Study the Relational Model? Most widely used model. Vendors: IBM, Microsoft, Oracle, Sybase, etc. Legacy systems in

More information

Relational Model. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Relational Model. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011 Relational Model IT 5101 Introduction to Database Systems J.G. Zheng Fall 2011 Overview What is the relational model? What are the most important practical elements of the relational model? 2 Introduction

More information

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal Introduction JDBC is a Java standard that provides the interface for connecting from Java to relational databases. The JDBC standard is defined by Sun Microsystems and implemented through the standard

More information

Lab # 4. Data Definition Language (DDL)

Lab # 4. Data Definition Language (DDL) Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 4 Data Definition Language (DDL) Eng. Haneen El-Masry November, 2014 2 Objective To be familiar with

More information

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall The Relational Model Chapter 3 Comp 521 Files and Databases Fall 2012 1 Why Study the Relational Model? Most widely used model by industry. IBM, Informix, Microsoft, Oracle, Sybase, etc. It is simple,

More information

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

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data. Managing Data Data storage tool must provide the following features: Data definition (data structuring) Data entry (to add new data) Data editing (to change existing data) Querying (a means of extracting

More information

CSE 308. Database Issues. Goals. Separate the application code from the database

CSE 308. Database Issues. Goals. Separate the application code from the database CSE 308 Database Issues The following databases are created with password as changeit anticyber cyber cedar dogwood elm clan Goals Separate the application code from the database Encourages you to think

More information

Module 3 MySQL Database. Database Management System

Module 3 MySQL Database. Database Management System Module 3 MySQL Database Module 3 Contains 2 components Individual Assignment Group Assignment BOTH are due on Mon, Feb 19th Read the WIKI before attempting the lab Extensible Networking Platform 1 1 -

More information

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

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model The Relational Model CMU SCS 15-415 C. Faloutsos Lecture #3 R & G, Chap. 3 Outline Introduction Integrity constraints (IC) Enforcing IC Querying Relational Data ER to tables Intro to Views Destroying/altering

More information

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley CSCI/CMPE 3326 Object-Oriented Programming in Java JDBC Dongchul Kim Department of Computer Science University of Texas Rio Grande Valley Introduction to Database Management Systems Storing data in traditional

More information

CSC 453 Database Technologies. Tanu Malik DePaul University

CSC 453 Database Technologies. Tanu Malik DePaul University CSC 453 Database Technologies Tanu Malik DePaul University A Data Model A notation for describing data or information. Consists of mostly 3 parts: Structure of the data Data structures and relationships

More information

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

CISC 3140 (CIS 20.2) Design & Implementation of Software Application II CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Email Address: meyer@sci.brooklyn.cuny.edu Course Page: http://www.sci.brooklyn.cuny.edu/~meyer/ CISC3140-Meyer-lec4

More information

Top 50 JDBC Interview Questions and Answers

Top 50 JDBC Interview Questions and Answers Top 50 JDBC Interview Questions and Answers 1) What is the JDBC? JDBC stands for Java Database Connectivity. JDBC is a Java API that communicates with the database and execute SQLquery. 2) What is a JDBC

More information

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

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition) ACS-3902 Fall 2016 Ron McFadyen 3D21 ron.mcfadyen@acs.uwinnipeg.ca Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition) 1 The Relational Data Model and Relational Database Constraints

More information

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures) CSCU9Q5 Introduction to MySQL Data Definition & Manipulation (Over ~two Lectures) 1 Contents Introduction to MySQL Create a table Specify keys and relations Empty and Drop tables 2 Introduction SQL is

More information

Introduction to Relational Database Management Systems

Introduction to Relational Database Management Systems 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

More information

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Introduction to SQL ECE 650 Systems Programming & Engineering Duke University, Spring 2018 SQL Structured Query Language Major reason for commercial success of relational DBs Became a standard for relational

More information

Database Applications (15-415)

Database Applications (15-415) Database Applications (15-415) The Relational Model Lecture 3, January 18, 2015 Mohammad Hammoud Today Last Session: The entity relationship (ER) model Today s Session: ER model (Cont d): conceptual design

More information

CS143: Relational Model

CS143: Relational Model CS143: Relational Model Book Chapters (4th) Chapters 1.3-5, 3.1, 4.11 (5th) Chapters 1.3-7, 2.1, 3.1-2, 4.1 (6th) Chapters 1.3-6, 2.105, 3.1-2, 4.5 Things to Learn Data model Relational model Database

More information

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615 Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU 15-415/615 Roadmap 3 Introduction Integrity constraints (IC) Enforcing IC Querying Relational Data ER to tables Intro

More information

The Relational Model 2. Week 3

The Relational Model 2. Week 3 The Relational Model 2 Week 3 1 We have seen how to create a database schema, how do we create an actual database on our computers? professor(pid : string, name : string) course(pid : string, number :

More information

The Relational Model

The Relational Model The Relational Model UVic C SC 370, Fall 2002 Daniel M. German Department of Computer Science University of Victoria 3 1 The Relational Model CSC 370 dmgerman@uvic.ca Overview How is data represented in

More information

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

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c) SQL language Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c) 2011-2016 SQL - Structured Query Language SQL is a computer language for communicating with DBSM Nonprocedural (declarative) language What

More information

Pagina 1 di 5 13.1.4. INSERT Syntax 13.1.4.1. INSERT... SELECT Syntax 13.1.4.2. INSERT DELAYED Syntax INSERT [LOW_PRIORITY DELAYED HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ({expr

More information

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

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Application Programming for Relational Databases

Application Programming for Relational Databases Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Principles of Data Management

Principles of Data Management Principles of Data Management Alvin Lin August 2018 - December 2018 Structured Query Language Structured Query Language (SQL) was created at IBM in the 80s: SQL-86 (first standard) SQL-89 SQL-92 (what

More information

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

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1 COSC344 Database Theory and Applications Lecture 5 SQL - Data Definition Language COSC344 Lecture 5 1 Overview Last Lecture Relational algebra This Lecture Relational algebra (continued) SQL - DDL CREATE

More information

Review for Exam 1 CS474 (Norton)

Review for Exam 1 CS474 (Norton) Review for Exam 1 CS474 (Norton) What is a Database? Properties of a database Stores data to derive information Data in a database is, in general: Integrated Shared Persistent Uses of Databases The Integrated

More information

The Relational Model. Week 2

The Relational Model. Week 2 The Relational Model Week 2 1 Relations A relation is a more concrete construction, of something we have seen before, the ER diagram. name S.S.N students street city A relation is (just!) a table! We will

More information

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT ) Topics Relational Model Linda Wu Relational model SQL language Integrity constraints ER to relational Views (CMPT 354 2004-2) Chapter 3 CMPT 354 2004-2 2 Why Study the Relational Model? Most widely used

More information

Translating an ER Diagram to a Relational Schema

Translating an ER Diagram to a Relational Schema Translating an ER Diagram to a Relational Schema CS386/586 Introduction to Database Systems, Lois Delcambre 1999-2009 Slide 1 Translate each entity set into a table, with keys. Entity set: represented

More information

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

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations The Relational Model CMU SCS 15-415/615 C. Faloutsos A. Pavlo Lecture #3 R & G, Chap. 3 Roadmap Introduction Integrity constraints (IC) Enforcing IC Querying Relational Data ER to tables Intro to Views

More information

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

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1 SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1 Class 03: SQL Fundamentals 2 SQL SQL (Structured Query Language): A language that is used in relational databases to build and query tables. Earlier

More information

Overview Relational data model

Overview Relational data model Thanks to José and Vaida for most of the slides. Relational databases and MySQL Juha Takkinen juhta@ida.liu.se Outline 1. Introduction: Relational data model and SQL 2. Creating tables in Mysql 3. Simple

More information

Bonus Content. Glossary

Bonus Content. Glossary Bonus Content Glossary ActiveX control: A reusable software component that can be added to an application, reducing development time in the process. ActiveX is a Microsoft technology; ActiveX components

More information

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002 Java and the Java DataBase Connectivity (JDBC) API Todd Kaufman April 25, 2002 Agenda BIO Java JDBC References Q&A Speaker 4 years Java experience 4 years JDBC experience 3 years J2EE experience BS from

More information

Entity Attribute STUDENT TABLE tuples single domain

Entity Attribute STUDENT TABLE tuples single domain Objectives Computer Science 202 Database Systems: Relational Database Model To learn the basic relational database components and concepts. To become familiar with the relational table's components and

More information

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Objectives Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Setting Up JDBC Before you can begin to utilize JDBC, you must

More information

Introduction to SQL & Database Application Development Using Java

Introduction to SQL & Database Application Development Using Java Introduction to SQL & Database Application Development Using Java By Alan Andrea The purpose of this paper is to give an introduction to relational database design and sql with a follow up on how these

More information

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture COGS 121 HCI Programming Studio Week 03 - Tech Lecture Housekeeping Assignment #1 extended to Monday night 11:59pm Assignment #2 to be released on Tuesday during lecture Database Management Systems and

More information

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

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Tenth Edition Chapter 7 Introduction to Structured Query Language (SQL) Objectives In this chapter, students will learn: The basic commands and

More information

CS403- Database Management Systems Solved MCQS From Midterm Papers. CS403- Database Management Systems MIDTERM EXAMINATION - Spring 2010

CS403- Database Management Systems Solved MCQS From Midterm Papers. CS403- Database Management Systems MIDTERM EXAMINATION - Spring 2010 CS403- Database Management Systems Solved MCQS From Midterm Papers April 29,2012 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 CS403- Database Management Systems MIDTERM EXAMINATION - Spring

More information

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017 Introduction to SQL Programming Techniques CSC 375, Fall 2017 The Six Phases of a Project: Enthusiasm Disillusionment Panic Search for the Guilty Punishment of the Innocent Praise for non-participants

More information

SQL STRUCTURED QUERY LANGUAGE

SQL STRUCTURED QUERY LANGUAGE STRUCTURED QUERY LANGUAGE SQL Structured Query Language 4.1 Introduction Originally, SQL was called SEQUEL (for Structured English QUery Language) and implemented at IBM Research as the interface for an

More information

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS 1 INTRODUCTION TO EASIK EASIK is a Java based development tool for database schemas based on EA sketches. EASIK allows graphical modeling of EA sketches and views. Sketches and their views can be converted

More information

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL functions fit into two broad categories: Data definition language Data manipulation language Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 7 Beginning Structured Query Language (SQL) MDM NUR RAZIA BINTI MOHD SURADI 019-3932846 razia@unisel.edu.my

More information

Full file at

Full file at ch2 True/False Indicate whether the statement is true or false. 1. The SQL command to create a database table is an example of DML. 2. A user schema contains all database objects created by a user. 3.

More information

SQL Interview Questions

SQL Interview Questions SQL Interview Questions SQL stands for Structured Query Language. It is used as a programming language for querying Relational Database Management Systems. In this tutorial, we shall go through the basic

More information

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

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation MIDTERM EXAM 2 Basic

More information

Why Study the Relational Model? The Relational Model. Relational Database: Definitions. The SQL Query Language. Relational Query Languages

Why Study the Relational Model? The Relational Model. Relational Database: Definitions. The SQL Query Language. Relational Query Languages Why Study the Relational Model? The Relational Model Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. Legacy systems in older models E.G., IBM s IMS Recent competitor: object-oriented

More information

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 1 BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 2 LECTURE OUTLINE SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL Set Operations in SQL 3 BASIC SQL Structured

More information

Environment Settings on SIT

Environment Settings on SIT Environment Settings on SIT ~/jhuang/website: The root directory of the jhuang/website web application. Store here HTML, Servlet and JSP files ~/jhuang/website/web-inf: All resources for the web application

More information

EE221 Databases Practicals Manual

EE221 Databases Practicals Manual EE221 Databases Practicals Manual Lab 1 An Introduction to SQL Lab 2 Database Creation and Querying using SQL Assignment Data Analysis, Database Design, Implementation and Relation Normalisation School

More information

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 1 BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 2 CHAPTER 4 OUTLINE SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL Set Operations in SQL 3 BASIC SQL Structured

More information

Java application using JDBC to connect to a database.

Java application using JDBC to connect to a database. JDBC(JAVA DATABASE CONNECTIVITY) The Java JDBC API enables Java applications to connect to relational databases via a standard API, so your Java applications become independent (almost) of the database

More information

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

II B.Sc(IT) [ BATCH] IV SEMESTER CORE: RELATIONAL DATABASE MANAGEMENT SYSTEM - 412A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Re-accredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated

More information

The Relational Model of Data (ii)

The Relational Model of Data (ii) ICS 321 Fall 2013 The Relational Model of Data (ii) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 1 Defining Relational Schema in SQL Two aspects: Data

More information

The Entity-Relationship Model (ER Model) - Part 2

The Entity-Relationship Model (ER Model) - Part 2 Lecture 4 The Entity-Relationship Model (ER Model) - Part 2 By Michael Hahsler Based on slides for CS145 Introduction to Databases (Stanford) Lecture 4 > Section 2 What you will learn about in this section

More information

The Relational Model

The Relational Model The Relational Model What is the Relational Model Relations Domain Constraints SQL Integrity Constraints Translating an ER diagram to the Relational Model and SQL Views A relational database consists

More information

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

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama The Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Database Lab Lab # 2 Data Definition Language (DDL) Eng. Alaa O Shama October, 2015 Objective To be familiar

More information

Basic SQL. Basic SQL. Basic SQL

Basic SQL. Basic SQL. Basic SQL Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Structured

More information

Data Manipulation Language (DML)

Data Manipulation Language (DML) In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department ECOM 4113 DataBase Lab Lab # 3 Data Manipulation Language (DML) El-masry 2013 Objective To be familiar

More information

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

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) The Relational Model Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) Why Study the Relational Model? Most widely used model in Commercial DBMSs: Vendors: IBM, Microsoft,

More information

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

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity COSC 416 NoSQL Databases Relational Model (Review) Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Relational Model History The relational model was proposed by E. F. Codd

More information

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. # 5 Structured Query Language Hello and greetings. In the ongoing

More information

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas SQL SQL Functionality stands for Structured Query Language sometimes pronounced sequel a very-high-level (declarative) language user specifies what is wanted, not how to find it number of standards original

More information

Relational terminology. Databases - Sets & Relations. Sets. Membership

Relational terminology. Databases - Sets & Relations. Sets. Membership Relational terminology Databases - & Much of the power of relational databases comes from the fact that they can be described analysed mathematically. In particular, queries can be expressed with absolute

More information

Accessing databases in Java using JDBC

Accessing databases in Java using JDBC Accessing databases in Java using JDBC Introduction JDBC is an API for Java that allows working with relational databases. JDBC offers the possibility to use SQL statements for DDL and DML statements.

More information

CS403- Database Management Systems Solved Objective Midterm Papers For Preparation of Midterm Exam

CS403- Database Management Systems Solved Objective Midterm Papers For Preparation of Midterm Exam CS403- Database Management Systems Solved Objective Midterm Papers For Preparation of Midterm Exam Question No: 1 ( Marks: 1 ) - Please choose one Which of the following is NOT a feature of Context DFD?

More information

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

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2 CMPT 354 Constraints Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers John Edgar 2 firstname type balance city customerid lastname accnumber rate branchname phone

More information

The Relational Model Constraints and SQL DDL

The Relational Model Constraints and SQL DDL The Relational Model Constraints and SQL DDL Week 2-3 Weeks 2-3 MIE253-Consens 1 Schedule Week Date Lecture Topic 1 Jan 9 Introduction to Data Management 2 Jan 16 The Relational Model 3 Jan. 23 Constraints

More information

Database Fundamentals

Database Fundamentals Database Fundamentals presented to NYPHP May 22, 2007 by Kenneth Downs Secure Data Software, Inc. ken@secdat.com www.secdat.com www.andromeda project.org Pre Relational In the bad old days, every program

More information

Introduction to Data Management. Lecture #5 Relational Model (Cont.) & E-Rà Relational Mapping

Introduction to Data Management. Lecture #5 Relational Model (Cont.) & E-Rà Relational Mapping Introduction to Data Management Lecture #5 Relational Model (Cont.) & E-Rà Relational Mapping Instructor: Mike Carey mjcarey@ics.uci.edu Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

More information