1 SQL Data Types and Schemas

Size: px
Start display at page:

Download "1 SQL Data Types and Schemas"

Transcription

1 COMP 378 Database Systems Notes for Chapters 4 and 5 of Database System Concepts Advanced SQL 1 SQL Data Types and Schemas 1.1 Additional Data Types User Defined Types Idea: in some situations, data with the same internal representation is conceptually different and should not be treated interchangeably. For example, prices in both dollars and euros could be represented by type numeric(12, 2), but a value in dollars should not be directly assigned to an attribute representing a price in euros, and prices in dollars and euros should not be compared directly. We would like the database to report an error in these situations. In SQL, distinct types accomplish this goal. In SQL:1999, these types would be declared as: create type Dollars as numeric(12,2) final create type Euros as numeric(12,2) final DB2 does not use the keyword final, but does encourage the use of the distinct keyword and requires the with comparisons clause to disallow comparison with other numeric types: create distinct type Dollars as numeric(12,2) with comparisons create distinct type Euros as numeric(12,2) with comparisons After such declarations, these types can be used as domains for attributes: create table convert(dols Dollars, eus Euros) Because of the use of distinct types, queries such as: select * from convert where dols < eus and select dols + 20 from convert contain type errors, and these errors are detected and reported before the system attempts to execute the query (static type checking). In SQL:1999, values of distinct types can be cast back to their source types using syntax such as (cast dols to numeric(12,2)). In DB2, this would be written as cast(dols as numeric(12, 2)). Hence, the previous queries can be written as: select * from convert where cast(dols as numeric(12, 2)) < cast(eus as numeric(12, 2)) and select cast(dols as numeric(12,2)) + 20 from convert Distinct types can be removed or modified by name using the drop type or alter type commands. Example: drop type Dollars SQL:92 also includes a create domain command that is used to declare types for attributes. (This command is not supported in DB2.) The create domain command is much like create type, except that constraints on elements of the domain can be specified. Examples: 1

2 A domain for manufacturers, assuming that the flyshop only stocks flyrods by particular manufacturers: create domain manufacturer_type varchar(30) check(value in ( Orvis, G. Loomis, Winston, Sage )) The keyword constraint can be used to give a name to such a constraint. This allows the DBMS to report which constraint was violated (by name) when an error occurs. create domain manufacturer_type varchar(30) constraint legal_manufacturers check(value in ( Orvis, G. Loomis, Winston, Sage )) In either case, the domain manufacturer type would then be used as the domain of manufacturer in the flyrod relation. a domain for customer names (which are not allowed to be null): create domain custname_type varchar(30) check(value not null) If manufacturer is of type manufacturer type in flyrod and name is of custname type in customer, a query such as: select * from customer, flyrod where name = manufacturer would be permitted - unlike distinct types, values of different domains can be compared and assigned as long as the underlying types are compatible. ensuring that the stocknum can t be null: create domain fsntype int constraint fsnkey check(value not null and value >= 0) This kind of constraint is useful for primary key attributes Large-Object Types Large-object types are used for attributes that can be relatively large (pictures, audio clips, large documents,...). ANSI SQL provides two large-object types: clob - character large object, for large text documents blob - binary large object, for binary data (pictures, video clips,...) DB2 supports these and an additional LOB type. Example: creating a database to store movies: create table movie(title varchar(30), year int, content blob(2g)) DB2 does not support LOB types larger than 2 GB. Values of these types are typically only useful for external applications, and so are retrieved using a locater (in DB2, a rowid) that an application program can use to refer to the object. 2

3 1.1.3 Schemas, Catalogs and Environments To help in avoiding name clashes (i.e. two different users choose the same relation name when creating relations) ANSI SQL has a naming hierarchy. At the top level, the user or application program must connect to the desired database. Within each database, there can be any number of catalogs, and within each catalog there can be any number of schemas. A relation or view can be uniquely identified using a three part name: catalog.schema.relation For each database, each user has a default catalog and schema (as part of the SQL environment for the user), so these parts of the name can be omitted if the default is desired. In DB2, the highest level in the hierarchy is an instance. Each instance is a separate installation of DB2. This is useful, for example, for maintaining a development and a production version of the database on the same server. The instance to use can be specified by setting the DB2INSTANCE environment variable or by using the ATTACH command. Within each instance there can be any number of databases, and a user must connect to the desired database. If the DB2DBDFT environment variable is set to a database name, an implicit connection to that database is automatically created. Within each database there can be any number of schemas. The default schema for each user is the user name. The schema must be specified if the default is not desired (i.e. to refer to a table created by another user). The CONNECT RESET command is used to close a database connection. 2 Integrity Constraints An integrity constraint is a predicate that any valid instance of a database must satisfy. These constraints are meant to protect data from accidental damage or any changes that would make the data inconsistent. We ve already seen several forms of integrity constraints: not null check clauses superkeys mapping cardinalities referential integrity As testing integrity constraints can be time consuming, care must be taken when deciding what kinds of integrity constraints to enforce. Many older database systems explicitly limit the constraints that can be enforced, but SQL-92 (and later) do not. 2.1 Constraints on a Single Relation SQL allows many constraints to be expressed in the create table command: not null unique primary key using a check clause For example, a check clause could be used to specify that each stocknum in purchased must also occur in flyrod: create table purchased ( custnum int not null, stocknum int not null, pdate date, primary key (custnum, stocknum, pdate), check (stocknum in (select stocknum from flyrod))) It is better to specify such a constraint as an explicit referential integrity constraint (see Section 2.2.2). 3

4 2.2 Referential Integrity In the relations purchased and flyrod, we expect that any stocknum appearing in a tuple of purchased also appears in a tuple of flyrod. In relational algebra: Π stocknum (purchased) Π stocknum (flyrod) On the other hand, there may well be flyrod models that no one has purchased. That is, we do not require that: Note that if: Π stocknum (flyrod) Π stocknum (purchased) Π stocknum (purchased) Π stocknum (flyrod) then some tuples of flyrod or purchased (or both) will not participate in flyrod purchased. A tuple that does not participate in a natural join is called a dangling tuple. Dangling tuples may indicate a consistency problem in the database. Referential integrity constraints specify exactly when dangling tuples indicate a problem. Recall that a foreign key is a set of attributes in one relation that refer to the primary key attributes of another. Formally, let r 1 (R 1 ) and r 2 (R 2 ), with K R 1 as the primary key for R 1. A set of attributes α R 2 is a foreign key referencing r 1 if for every t 2 r 2, there must exist a tuple t 1 r 1 such that t 1 [K] = t 2 [α]. Equivalently: Π α (r 2 ) Π K (r 1 ). A constraint of this form is called a referential integrity constraint (or a subset dependency). Clearly, either K = α or K and α are compatible. Example: attribute stocknum of purchased is a foreign key referencing the stocknum attribute of flyrod, and Π stocknum (purchased) Π stocknum (flyrod) is a referential integrity constraint. Also, attribute custnum of purchased is a foreign key referencing the custnum attribute of customer, and Π custnum (purchased) Π custnum (customer) is a referential integrity constraint. Example: attribute stocknum of flyrod can NOT be a foreign key referencing the stocknum attribute of purchased, because stocknum is not the primary key of purchased. Sources of referential integrity constraints: any relation derived from an n-ary relationship set (in the E-R model) contains n foreign keys any relation derived from a weak entity set contains a foreign key referencing the relation derived from the identifying entity set if a higher level entity set is explicitly represented by a relation, then the relations for each lower level entity set contain a foreign key referencing that relation Testing Referential Integrity Constraints To ensure that referential integrity constraints are preserved, the constraints must be tested each time the database is modified. Consider a referential integrity constraint of the form: Π α (r 2 ) Π K (r 1 ) insertion: if tuple t 2 is inserted into r 2, the database system must test that: t 2 [α] Π K (r 1 ) i.e. that inserting the tuple won t violate the relationship. 4

5 deletion: if tuple t 1 is deleted from r 1, the system must test that no tuples of r 2 reference t 1 : σ α=t1[k](r 2 ) = { If this condition is not satisfied, then either the deletion must be rejected, or else the offending tuples must be deleted from r 2. If there are more referential integrity constraints involving r 2, this may cause more deletions. update: if a tuple t 2 r 2 is updated on an attribute of α, then the system must test that the new value of t 2 satisfies: t 2 [α] Π K (r 1 ) (same as insert). if a tuple t 1 r 1 is updated on an attribute of K, then the system must test that no tuples of r 2 reference the old value of t 1 : σ α=t1[k](r 2 ) = { (same as delete) Referential Integrity in SQL When a table is created in SQL, foreign keys can be specified as part of the create table statement. By default, a foreign key references the primary key of the foreign relation. For example (creating the purchased relation): create table purchased ( custnum int not null, stocknum int not null, pdate date not null, primary key (custnum, stocknum, pdate), foreign key (custnum) references customer, foreign key (stocknum) references flyrod) The implied referential integrity constraints are exactly those mentioned earlier. If the foreign key contains only one attribute, then it can be declared as part of the attribute declaration, i.e.: custnum int not null references customer, If the attribute names are different in the foreign relation or if the foreign key references a candidate key (declared using unique), the referenced attributes can be listed explicitly in the foreign key clause. When a referential integrity constraint is violated, the default action is for the system to reject the modification that caused the violation by rolling back the transaction that attempted to perform the modification. A foreign key clause can specify that other actions are taken to resolve the violation for a deletion or an update. These actions are modifications to one or more relations. Example: suppose that the purchased relation is created as follows: create table purchased (... foreign key (stocknum) references flyrod on delete cascade, on update cascade) Implications: 5

6 deleting a tuple in flyrod causes all tuples in purchased that mention the deleted flyrod to be deleted as well if the stocknum of a flyrod is updated, all tuples in purchased that referred to the old stocknum are updated to refer to the new one. In addition to cascade, the SQL-92 standard provides the following actions: set null, which causes the foreign key attribute values to be set to null for each tuple that violates the constraint set default, which causes the foreign key attribute values to be set to the default value for the domain for each tuple that violates the constraint (not supported by DB2). Note that foreign key attributes are allowed to contain null, and any such tuple automatically satisfies the associated referential integrity constraint. However, it is usually a good idea to declare foreign key attributes as not null. 2.3 Additional Properties of Constraints Integrity constraints can be added to existing relations using the syntax: alter table table add constraint where table is the name of an existing relation and constraint is any of the constraints we have seen so far. When a constraint is added to a relation: the system checks that the relation satisfies the constraint if so, the constraint is added if not, the alter table command is rejected If a transaction consists of several SQL commands, some constraints may be violated in the middle of the transaction but re-established by the time that the transaction terminates. For example, a bank may have a constraint that the total balance in all accounts is greater than some minimum threshold. (This could be expressed using an assertion as described in Section 2.4.) If a transfer from one account to another is implemented by two SQL update statements and the first statement decreases the balance of an account, the constraint could be violated. However, the constraint would be satisfied after the money is deposited in the second account. The SQL standard allows constraints to be declared as: initially deferred - which means that they are only checked at the end of transactions deferred - which means that transactions can choose to defer checking them until the end of the transaction So, we could avoid the problem described above by including the two update statements in the same transaction (which they should be anyway) and declaring the assertion as initially deferred The default is to check constraints immediately, and many systems (including DB2) do not support deferred constraints. 2.4 Assertions An assertion is an arbitrary predicate that the database should satisfy at all times. Example: we may want to ensure that the flyshop always stocks at least 5 distinct flyrod models. In SQL-92, the syntax for assertions is: create assertion assertion-name check predicate where predicate is a condition much like the where clause of an SQL query. For example, the above assertion can be expressed as: 6

7 create assertion min_flyrods check (select count(distinct stocknum) from flyrod) >= 5 The database system must check that the assertion is satisfied at the time it is created, and must also ensure that any database modification does not cause the assertion to become false. If the assertion is initially valid (when created), then any database modification that would cause it to become false is rejected. Because the testing necessary to ensure that assertions are satisfied can be expensive, they must be used with care. Many commercial products (including DB2) do not support assertions. 3 Triggers A trigger is an action that is taken in response to a modification of the database. To write a trigger, we must specify: 1. what condition should cause the trigger to be executed 2. what action should be taken when the trigger executes Triggers can be used to maintain integrity constraints, detect exceptional conditions, log changes, and so on. The action taken by a trigger can only be an SQL statement or sequence of statements. Triggers are not included in the SQL-92 standard, but most relational database systems have supported some form of triggers for some time. Triggers were added to the SQL:1999 standard, but most systems still use proprietary syntax for them. However, the DB2 syntax for triggers is very similar to the SQL:1999 syntax. Example: suppose we wanted to log all changes to employee salaries. We could add a relation logsal with schema Logsal-schema = (modified by, ssn, oldsal, newsal, modtime) that records who changed the salary, the social security number of the employee whose salary was changed, the old salary, the new salary and the date and time of the modification. Rather than inserting into this table by hand, we would prefer that this table be automatically updated whenever an employee s salary was changed. A relation that records changes to other relations is called a delta or change table, and logging changes is referred to as creating an audit trail. Audit trails are useful for identifying the person who carried out incorrect or fraudulent updates. In DB2, the above trigger would be defined as: create trigger update_log after update of salary on employee referencing old as oldtuple new as newtuple for each row mode db2sql insert into logsal values (USER, oldtuple.ssn, oldtuple.salary, newtuple.salary, CURRENT TIMESTAMP) Notes: USER and CURRENT TIMESTAMP are DB2 specific variables used to access the current user and the current date/time, respectively events/statements that can invoke triggers include: insert, delete, update and select(the SQL:1999 standard does not allow select statements to invoke triggers) a trigger can be invoked before (no cascade before) or after (after) the triggering event actually occurs. SQL:1999 uses before rather than no cascade before triggers can be executed for each row affected by the modification or selection (using for each row mode db2sql or just for each row in SQL:1999), or just once for the entire SQL statement doing the modification (using for each statement). The former are called row triggers, and the later statement triggers. 7

8 for row triggers, the referencing clause is used to provide a way to refer to the value of a tuple being modified both before and after it is actually changed. The variables used to refer to the old and new tuple values are called transition variables. for statement triggers, the referencing clause is used to refer to transition tables, which are temporary tables containing the affected tuples. The syntax referencing old table as and referencing new table as is used for this. Transition tables can not be used with before triggers. In DB2, statement triggers must also be after triggers. an optional when clause can be used so that the trigger is only invoked under certain conditions. Example: we could define a trigger that was invoked only when an employee updated their own salary. the action to be taken is an SQL statement or a sequence of SQL statements inside: begin atomic... end (i.e. a transaction) DB2 includes a signal statement that can be used within triggers. It raises an error condition and rolls back the triggering SQL statement. Thus, the signal statement can be used in a before trigger to prevent the triggering statement from occurring (for example, to prevent an employee from changing their own salary). The same trigger in MySQL syntax: create trigger update_log after update on employee for each row insert into logsal values (user(), new.ssn, old.salary, new.salary, now()) Triggers are much more commonly used than assertions, as they are usually less expensive to test. However, triggers should be used with care: if a trigger contains an error (i.e. violates a referential integrity constraint), then the triggering statement (i.e. the insertion, deletion or update) fails and is rolled back. the action of one trigger could cause another trigger to fire (which could cause another trigger to fire...) 4 Security and Authorization The data stored in a database must be secured against unauthorized access (reading), modification and deletion. Security measures must be taken at several levels: the database system the operating system the network the physical level the human level 4.1 Authorization Each user (or group of users) of a database system can have different levels of authorization on different parts of the database (i.e. relations, views): instance authorization: read authorization 8

9 insert authorization update authorization delete authorization schema authorization: index authorization resource authorization (which allows the creation of new relations) alteration authorization (which allows adding and deleting attributes) drop authorization (which allows the deletion of relations) The user who creates a relation automatically has all authorizations on that relation. Other users can be given combinations of the possible authorizations. The database administrator automatically has all of these authorizations, as well as ability to authorize new users. 4.2 Authorization and Views Recall that views can be used to restrict access to data. In particular, a user may be authorized to read (select) from a view, even though that user does not have read authorization on the relations used in defining the view. In particular, this allows the user to see some attributes of a relation (those included in the result of the view) but not others. Creating a view does not require resource authorization, but a user who creates a view receives only the authorizations on the view that are implied by the user s authorizations on the underlying relations. In particular, if the user does not have read access on all of the underlying relations, then the user can not use the view in a query. The database system will deny the view creation request if the user would have no authorization on the resulting view. 4.3 Authorization in SQL In SQL, authorizations are called privileges. The standard privileges are: delete insert select update references The references privilege on a relation gives the holder the right to declare foreign keys referencing that relation. If there were no references privilege, any user could prevent deletion of tuples from a relation r 1 by creating another relation r 2 with a foreign key referencing r 1, and then inserting appropriate tuples into r 2. Privileges are granted to or revoked from individual users or groups of users (sometimes called roles). Groups are usually operating system groups, and are convenient when some set of users should all have the same privileges. A new user is then granted these privileges just by being added to the group. The syntax of the grant statement is: grant privilege list on relation or view name to user/group list For example: grant select, insert, update on customer to salesperson The update and references privileges can be granted on specific attributes of the relation (or view). For example: 9

10 grant update(name) on customer to salesperson If no attributes are specified, then the privilege is granted on all attributes. The privilege all privileges is a shorthand for all privileges, and public is a shorthand for all users. In DB2, the keywords user and group can be used to disambiguate cases where a user and a group have the same name, and groups are defined by the operating system. In SQL:1999, roles are created using the create role statement, and users are added to roles using the grant statement. For example: create role salesperson grant salesperson to ted grant select on customer to salesperson gives user ted the select privilege on customer. All privileges granted to one role can be granted to another: create role manager grant salesperson to manager Now, all members of the manager role have all privileges of the salesperson role, plus any additional privileges granted to manager. The user who creates a relation, view or role has all privileges on it, including the privilege to grant privileges to others. The keywords with grant option is used to confer grant privileges. For example: grant select on customer to ted with grant option gives the select privilege to user ted, and also allows ted to grant this privilege to others. In DB2, the special privilege dbadm is used to grant database administrator privileges (i.e. all privileges, including the privilege to create and drop relations and to grant privileges to others) on a database. The dbadm privilege can only be granted by a special user called the instance owner (created when the database instance is created), or by users to whom the instance owner has granted the sysadm privilege on the instance. The revoke statement is used to revoke privileges. For example: revoke select on customer from ted cascade revokes the select privilege from ted, from any users or groups that ted has granted the privilege to. This is specified by cascade, but is usually the default. If both ted and some other user have granted the select privilege to user mary (for example), then revoking the privilege from ted does not revoke the privilege from mary. The following revoke statement: revoke select on customer from ted restrict does not revoke the select privilege from those that ted has granted it to (because of the use of restrict). Shortcomings of SQL authorization: privileges can not be granted on individual tuples - only on relations, attributes,... Hence, a user can not be granted only the privilege to view their own (personal) information, for example. privileges based on users and groups (or roles) do not work well for Web database access. Typically, one userid and password is hard coded into the application (CGI script, servlet, applet,...) and is used for all Web access. Any more fine-grained authorization must be done by the application. 5 Application Programming with SQL The ability to use SQL commands in general (Java, C, Cobol) programs is necessary because: not all queries can be expressed in SQL (without recursion) SQL does not include support for GUI s, printing, etc. 10

11 SQL does not permit communication with other programs Techniques: embedded SQL dynamic SQL ODBC JDBC 4GLs 5.1 Embedded SQL Embedded SQL refers to SQL commands that appear directly in host language programs, where the host language may be C, C++, Java, Fortran, Cobol, etc. The Java embedding of SQL is called SQLJ. Special syntax is used to mark embedded SQL statements. Before the program can be compiled, it must be fed through a preprocessor that replaces the embedded SQL statements with system commands. Information is transferred between normal host language commands and embedded SQL commands through host language variables. Any variable used this way must be declared in a special program section. The following syntax is typical when C is the host language: EXEC SQL begin declare section; double len, clen; char manuf[40], n[40], addr[50]; EXEC SQL end declare section; In the embedded SQL statements, these variables are preceded by : to distinguish them from SQL variables or constants. If the embedded SQL is a select statement, the host program must declare a cursor that can be used to step through the result one tuple at a time. For example, if we want to find the names and addresses of everyone who has purchased a flyrod over a particular length, along with the length of that flyrod, we declare a cursor and associate it with the appropriate query: printf("enter the length: "); scanf("%lf", &clen); EXEC SQL declare c1 cursor for select name, address, length from wahlst.customer, wahlst.purchased, wahlst.flyrod where wahlst.customer.custnum = wahlst.purchased.custnum and wahlst.purchased.stocknum = wahlst.flyrod.stocknum and length > :clen; printf("printing names and addresses and\n"); printf("computing average flyrod length.\n"); The ; after clen ends the EXEC SQL section. To use this query, we use an open statement to initialize the cursor, a fetch statement to get the next tuple, and a close statement to close the query, so that it could be reopened if the query were repeated. The fetch statement sets the variable SQLCODE, which can be checked for error conditions. In particular, an SQLCODE value of 0 indicates that the fetch was successful. The complete program follows: 11

12 #include <stdio.h> EXEC SQL INCLUDE SQLCA; main() { int count = 0; double sum = 0.0; EXEC SQL begin declare section; double len, clen; char n[40], addr[50]; EXEC SQL end declare section; /* connect to the database */ EXEC SQL CONNECT TO flyshop; printf("enter the length: "); scanf("%lf", &clen); EXEC SQL declare c1 cursor for select name, address, length from wahlst.customer, wahlst.purchased, wahlst.flyrod where wahlst.customer.custnum = wahlst.purchased.custnum and wahlst.purchased.stocknum = wahlst.flyrod.stocknum and length > :clen; printf("printing names and addresses and\n"); printf("computing average flyrod length.\n"); EXEC SQL open c1; while (1) { /* infinite loop */ EXEC SQL fetch c1 into :n, :addr, :len; if (SQLCODE!= 0) break; printf("name: %-30.30s address: %s\n", n, addr); count++; sum += len; /* close the cursor */ EXEC SQL close c1; /* close the database connection */ EXEC SQL CONNECT RESET; if (count > 0) printf("the average length is: %lf\n", sum/count); else printf("no fly rods selected.\n"); Note that a database connection must be opened, and should be closed when the program is finished. SQL commands that do not return a result (i.e. update, insert, delete) do not require a cursor, and so can simply be executed. Example: an insertion into flyrod: EXEC SQL begin declare section; 12

13 long fsn, lw, inv; double len; char manuf[40]; EXEC SQL end declare section; printf("enter the stock number: "); scanf("%d", &fsn); printf("enter the manufacturer: "); scanf("%s", manuf); printf("enter the length: "); scanf("%lf", &len); printf("enter the line weight: "); scanf("%d", &lw); printf("enter the initial inventory: "); scanf("%d", &inv); /* connect to the database */ EXEC SQL CONNECT TO flyshop; EXEC SQL insert into wahlst.flyrod values (:fsn, :manuf, :len, :lw, :inv); /* close the database connection */ EXEC SQL CONNECT RESET; In embedded SQL, the entire SQL statement must be present in the host language program at the time that the program is preprocessed (statically). Dynamic SQL allows SQL statements to be constructed at runtime (in string variables). This is more flexible, but less efficient because the query evaluation plan for each query must be constructed at runtime. 5.2 JDBC JDBC is a Java Application Programming Interface (API) that provides methods for database interaction. A JDBC program can execute on the database server, or can connect to a database on a remote server over a network. Objects of class Statement are used to execute SQL statements. The executeupdate() method is used for insertions, deletions and updates (which don t return a value). If an error occurs, executeupdate() throws an SQLException. TheexecuteQuery()methodisusedtoexecuteanSQLquery. ItreturnsanobjectoftheclassResultSet (provided by the API), which acts as an iterator over the result of the query. Important instance methods of ResultSet include: next(), which advances the iterator to the next tuple of the result, returning false if the result is exhausted. various get methods (getstring(), getint(), getfloat()), which take either the column name or number as parameters, and return the value in that column for the current tuple as the indicated type. The string passed to executeupdate() or executequery() can be built dynamically (at runtime). /** * basic demonstration of JDBC database connectivity Tim Wahls 2/28/2014 */ 13

14 import java.sql.*; import java.io.*; public class Flyshop { public static void main(string argv[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { // load appropriate database drivers Class.forName("com.mysql.jdbc.Driver"); // connect to the database server and database // a remote connection requires the server name, database name // and a userid and password for connecting System.out.print("Enter your username: "); String user = in.readline(); System.out.print("Enter your password: "); String pass = in.readline(); Connection con = DriverManager.getConnection( "jdbc:mysql://mathcsdev.dickinson.edu/flyshop", user, pass); Statement stmt = con.createstatement(); // the following statements can not be executed without the appropriate // privileges // stmt.executeupdate("delete from flyrod where stocknum = 4"); // stmt.executeupdate("insert into flyrod values (4, St. Croix," + // "8.0, 3, 5)"); System.out.print("Enter the length: "); String len = in.readline(); ResultSet rset = stmt.executequery("select * from customer, " + "purchased, flyrod where customer.custnum = " + "purchased.custnum and purchased.stocknum = " + "flyrod.stocknum and length > " + len); System.out.println("Purchases of all flyrods over " + len + " feet long:"); while (rset.next()) { System.out.println(rset.getString("name") + " " + rset.getstring("manufacturer") + " " +rset.getdouble("length")); // close the database connection con.close(); catch (SQLException e) { System.out.println("SQL Exception: " + e); catch (ClassNotFoundException e) { System.out.println("Class Not Found Exception: " + e); JDBC also includes prepared statements that can be compiled once (i.e. the query evaluation plan is 14

15 constructed once), and then reused many times with different data values. For example (assuming a database connection con has already been established): double len; PreparedStatement pstmt = con.preparestatement( "select * from customer, " + "purchased, flyrod where customer.custnum = " + "purchased.custnum and purchased.stocknum = " + "flyrod.stocknum and length >?"); // the? marks the spot to be replaced by a value System.out.print("Enter the length (0 to quit): "); len = Double.parseDouble(in.readLine()); while (len!= 0) { // replace the first? with the value of len pstmt.setdouble(1, len); ResultSet rset = pstmt.executequery(); System.out.println("All flyrods over " + len + " feet long:"); while (rset.next()) { System.out.println(rset.getString("name") + " " + rset.getstring("manufacturer") + " " + rset.getdouble("length")); System.out.print("Enter the length (0 to quit): "); len = Double.parseDouble(in.readLine()); Prepared statements are the preferred method for database insertions, as the setstring method (analogous to setdouble above) automatically inserts appropriate escape characters. (Imagine inserting a string value containing.) JDBC also includes metadata features that allow programs to examine database schemas dynamically. This is useful, for example, for writing database table browsers and other administrative applications that need to work with all possible schemas. The following example shows how to query a database to get all tables in a particular schema, and how to find all columns of a particular table (again, assuming a database connection con). DatabaseMetaData dbmd = con.getmetadata(); // print the names of all tables // parameters to gettables: catalog, schema pattern, // table name pattern, types ResultSet rs = dbmd.gettables(null, null, "%", null); while (rs.next()) { System.out.println("catalog name"); System.out.println(rs.getString(1)); System.out.println("schema name"); System.out.println(rs.getString(2)); System.out.println("table name"); System.out.println(rs.getString(3)); System.out.println(); // print the names and domains of all columns in the flyrod table // parameters to getcolumns: catalog, schema pattern, // table name pattern, column pattern rs = dbmd.getcolumns(null, null, "flyrod", "%"); while (rs.next()) { System.out.println("column"); 15

16 System.out.println(rs.getString("COLUMN_NAME")); System.out.println(rs.getString("TYPE_NAME")); The default in JDBC is for each SQL statement to execute as a separate transaction. This behavior is not appropriate for sequences of SQL statements that should execute as a single atomic action, such as a transfer from one bank account to another. To change this default behavior, use the setautocommit() method of the Connection class with parameter false (to turn off automatic committing). Then, any changes made to the database must be explicitly committed (using the commit() method) or rolled back (using the rollback() method). For example (again, assuming a database connection con): // turn autocommit off con.setautocommit(false); // sequence of SQL statements forming a transaction here // assume variable success indicates whether the transaction processed // successfully if (success) { // make any updates permanent in the database con.commit(); else { // undo any database updates con.rollback(); // turn autocommit back on if desired con.setautocommit(true); 5.3 Stored Procedures and Procedural Extensions A stored procedure is a user-defined procedure that is installed on the database server and can be called from application programs. In DB2, a stored procedure can be written using static or dynamic embedded SQL (in any programming language that supports the embedding). Stored procedures are used primarily for reducing network traffic. For example, rather than returning the entire result of a query to an application program for further processing, a stored procedure can do the processing directly on the server. SQL:1999 introduces procedures, loops, if statements and user defined types with methods and inheritance (i.e. classes). These extensions are not yet widely supported by commercial products. 5.4 Additional Subquery Features A scalar subquery is a subquery that returns a single value (more precisely, a relation with one column and one row that can be treated as a single value). SQL:2003 (and DB2) allow scalar subqueries to be used wherever a value of the same type can be used. For example, to find all flyrods that are longer than the average flyrod length: select * from flyrod where length > (select avg(length) from flyrod) To find the number of flyrods purchased by each customer (without using group by): select name, (select count(*) from purchased where purchased.custnum = customer.custnum) as numflyrods from customer 16

Database Programming. Week 10-2. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

Database Programming. Week 10-2. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford Database Programming Week 10-2 *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford SQL in Real Programs We have seen only how SQL is used at the generic query

More information

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language: Database Access from a Programming Language Database Access from a Programming Language: Java s JDBC Werner Nutt Introduction to Databases Free University of Bozen-Bolzano 2 Database Access from a Programming Language Two Approaches 1. Embedding

More information

Database Access from a Programming Language:

Database Access from a Programming Language: Database Access from a Programming Language: Java s JDBC Werner Nutt Introduction to Databases Free University of Bozen-Bolzano 2 Database Access from a Programming Language Two Approaches 1. Embedding

More information

COMP 378 Database Systems Notes for Chapter 7 of Database System Concepts Database Design and the Entity-Relationship Model

COMP 378 Database Systems Notes for Chapter 7 of Database System Concepts Database Design and the Entity-Relationship Model COMP 378 Database Systems Notes for Chapter 7 of Database System Concepts Database Design and the Entity-Relationship Model The entity-relationship (E-R) model is a a data model in which information stored

More information

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University CS 377 Database Systems SQL Programming Li Xiong Department of Mathematics and Computer Science Emory University 1 A SQL Query Joke A SQL query walks into a bar and sees two tables. He walks up to them

More information

The JAVA Way: JDBC and SQLJ

The JAVA Way: JDBC and SQLJ The JAVA Way: JDBC and SQLJ David Toman School of Computer Science University of Waterloo Introduction to Databases CS348 David Toman (University of Waterloo) JDBC/SQLJ 1 / 21 The JAVA way to Access RDBMS

More information

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd. Why Is This Important? Database Application Development Chapter 6 So far, accessed DBMS directly through client tools Great for interactive use How can we access the DBMS from a program? Need an interface

More information

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Chapter 9, More SQL: Assertions, Views, and Programming Techniques Chapter 9, More SQL: Assertions, Views, and Programming Techniques 9.2 Embedded SQL SQL statements can be embedded in a general purpose programming language, such as C, C++, COBOL,... 9.2.1 Retrieving

More information

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

COSC344 Database Theory and Applications. Java and SQL. Lecture 12 COSC344 Database Theory and Applications Lecture 12: Java and SQL COSC344 Lecture 12 1 Last Lecture Trigger Overview This Lecture Java & SQL Source: Lecture notes, Textbook: Chapter 12 JDBC documentation

More information

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches Course Objectives Database Applications Design Construction SQL/PSM Embedded SQL JDBC Applications Usage Course Objectives Interfacing When the course is through, you should Know how to connect to and

More information

Programming Database lectures for mathema

Programming Database lectures for mathema Programming Database lectures for mathematics students April 25, 2015 Functions Functions are defined in Postgres with CREATE FUNCTION name(parameter type,...) RETURNS result-type AS $$ function-body $$

More information

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn Chapter 9 Java and SQL Wang Yang wyang@njnet.edu.cn Outline Concern Data - File & IO vs. Database &SQL Database & SQL How Connect Java to SQL - Java Model for Database Java Database Connectivity (JDBC)

More information

Instant SQL Programming

Instant SQL Programming Instant SQL Programming Joe Celko Wrox Press Ltd. INSTANT Table of Contents Introduction 1 What Can SQL Do for Me? 2 Who Should Use This Book? 2 How To Use This Book 3 What You Should Know 3 Conventions

More information

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7 SQL DATA DEFINITION: KEY CONSTRAINTS CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7 Data Definition 2 Covered most of SQL data manipulation operations Continue exploration of SQL

More information

A Brief Introduction to MySQL

A Brief Introduction to MySQL A Brief Introduction to MySQL by Derek Schuurman Introduction to Databases A database is a structured collection of logically related data. One common type of database is the relational database, a term

More information

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS Can Türker Swiss Federal Institute of Technology (ETH) Zurich Institute of Information Systems, ETH Zentrum CH 8092 Zurich, Switzerland

More information

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases Java and Databases COMP514 Distributed Information Systems Java Database Connectivity One of the problems in writing Java, C, C++,, applications is that the programming languages cannot provide persistence

More information

More SQL: Assertions, Views, and Programming Techniques

More SQL: Assertions, Views, and Programming Techniques 9 More SQL: Assertions, Views, and Programming Techniques In the previous chapter, we described several aspects of the SQL language, the standard for relational databases. We described the SQL statements

More information

Database Programming with PL/SQL: Learning Objectives

Database Programming with PL/SQL: Learning Objectives Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs

More information

Database Implementation: SQL Data Definition Language

Database Implementation: SQL Data Definition Language Database Systems Unit 5 Database Implementation: SQL Data Definition Language Learning Goals In this unit you will learn how to transfer a logical data model into a physical database, how to extend or

More information

SQL and Java. Database Systems Lecture 19 Natasha Alechina

SQL and Java. Database Systems Lecture 19 Natasha Alechina Database Systems Lecture 19 Natasha Alechina In this Lecture SQL in Java SQL from within other Languages SQL, Java, and JDBC For More Information Sun Java tutorial: http://java.sun.com/docs/books/tutorial/jdbc

More information

Maintaining Stored Procedures in Database Application

Maintaining Stored Procedures in Database Application Maintaining Stored Procedures in Database Application Santosh Kakade 1, Rohan Thakare 2, Bhushan Sapare 3, Dr. B.B. Meshram 4 Computer Department VJTI, Mumbai 1,2,3. Head of Computer Department VJTI, Mumbai

More information

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today. & & 1 & 2 Lecture #7 2008 3 Terminology Structure & & Database server software referred to as Database Management Systems (DBMS) Database schemas describe database structure Data ordered in tables, rows

More information

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC? What is ODBC? Database Connectivity ODBC, JDBC and SQLJ CS2312 ODBC is (Open Database Connectivity): A standard or open application programming interface (API) for accessing a database. SQL Access Group,

More information

Procedural Extension to SQL using Triggers. SS Chung

Procedural Extension to SQL using Triggers. SS Chung Procedural Extension to SQL using Triggers SS Chung 1 Content 1 Limitations of Relational Data Model for performing Information Processing 2 Database Triggers in SQL 3 Using Database Triggers for Information

More information

SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach TRAINING & REFERENCE murach's SQL Server 2012 for developers Bryan Syverson Joel Murach Mike Murach & Associates, Inc. 4340 N. Knoll Ave. Fresno, CA 93722 www.murach.com murachbooks@murach.com Expanded

More information

Embedded SQL programming

Embedded SQL programming Embedded SQL programming http://www-136.ibm.com/developerworks/db2 Table of contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Before

More information

CS346: Database Programming. http://warwick.ac.uk/cs346

CS346: Database Programming. http://warwick.ac.uk/cs346 CS346: Database Programming http://warwick.ac.uk/cs346 1 Database programming Issue: inclusionofdatabasestatementsinaprogram combination host language (general-purpose programming language, e.g. Java)

More information

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1 The Relational Model Ramakrishnan&Gehrke, Chapter 3 CS4320 1 Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. Legacy systems in older models

More information

Lecture 6. SQL, Logical DB Design

Lecture 6. SQL, Logical DB Design Lecture 6 SQL, Logical DB Design Relational Query Languages A major strength of the relational model: supports simple, powerful querying of data. Queries can be written intuitively, and the DBMS is responsible

More information

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications Chapter 13 SQL Programming Introduction to SQL Programming Techniques Database applications Host language Java, C/C++/C#, COBOL, or some other programming language Data sublanguage SQL SQL standards Continually

More information

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 A feature of Oracle Rdb By Ian Smith Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal SQL:1999 and Oracle Rdb V7.1 The

More information

5.1 Database Schema. 5.1.1 Schema Generation in SQL

5.1 Database Schema. 5.1.1 Schema Generation in SQL 5.1 Database Schema The database schema is the complete model of the structure of the application domain (here: relational schema): relations names of attributes domains of attributes keys additional constraints

More information

JDBC (Java / SQL Programming) CS 377: Database Systems

JDBC (Java / SQL Programming) CS 377: Database Systems JDBC (Java / SQL Programming) CS 377: Database Systems JDBC Acronym for Java Database Connection Provides capability to access a database server through a set of library functions Set of library functions

More information

14 Triggers / Embedded SQL

14 Triggers / Embedded SQL 14 Triggers / Embedded SQL COMS20700 Databases Dr. Essam Ghadafi TRIGGERS A trigger is a procedure that is executed automatically whenever a specific event occurs. You can use triggers to enforce constraints

More information

Chapter 6: Integrity Constraints

Chapter 6: Integrity Constraints Chapter 6: Integrity Constraints Domain Constraints Referential Integrity Assertions Triggers Functional Dependencies Database Systems Concepts 6.1 Silberschatz, Korth and Sudarshan c 1997 Domain Constraints

More information

SQL Server. 1. What is RDBMS?

SQL Server. 1. What is RDBMS? SQL Server 1. What is RDBMS? Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained

More information

public class ResultSetTable implements TabelModel { ResultSet result; ResultSetMetaData metadata; int num cols;

public class ResultSetTable implements TabelModel { ResultSet result; ResultSetMetaData metadata; int num cols; C H A P T E R5 Advanced SQL Practice Exercises 5.1 Describe the circumstances in which you would choose to use embedded SQL rather than SQL alone or only a general-purpose programming language. Writing

More information

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems. Active database systems Database Management Systems Traditional DBMS operation is passive Queries and updates are explicitly requested by users The knowledge of processes operating on data is typically

More information

Oracle Database 10g Express

Oracle Database 10g Express Oracle Database 10g Express This tutorial prepares the Oracle Database 10g Express Edition Developer to perform common development and administrative tasks of Oracle Database 10g Express Edition. Objectives

More information

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Outline More Complex SQL Retrieval Queries

More information

The Relational Model. Why Study the Relational Model?

The Relational Model. Why Study the Relational Model? The Relational Model Chapter 3 Instructor: Vladimir Zadorozhny vladimir@sis.pitt.edu Information Science Program School of Information Sciences, University of Pittsburgh 1 Why Study the Relational Model?

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: 1.800.529.0165 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This course is designed to deliver the fundamentals of SQL and PL/SQL along

More information

1 File Processing Systems

1 File Processing Systems COMP 378 Database Systems Notes for Chapter 1 of Database System Concepts Introduction A database management system (DBMS) is a collection of data and an integrated set of programs that access that data.

More information

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB Mimer SQL Version 8.2 Copyright 2000 Mimer Information Technology AB Second revised edition December, 2000 Copyright 2000 Mimer Information Technology AB. Published by Mimer Information Technology AB,

More information

SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches

SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches SQL and Programming Languages SQL in Programming Languages Read chapter 5 of Atzeni et al. BD: Modelli e Linguaggi di Interrogazione and section 8.4 of Garcia-Molina The user does not want to execute SQL

More information

CS/CE 2336 Computer Science II

CS/CE 2336 Computer Science II CS/CE 2336 Computer Science II UT D Session 23 Database Programming with Java Adapted from D. Liang s Introduction to Java Programming, 8 th Ed. and other sources 2 Database Recap Application Users Application

More information

Guide to the Superbase. ODBC Driver. By Superbase Developers plc

Guide to the Superbase. ODBC Driver. By Superbase Developers plc Guide to the Superbase ODBC Driver By Superbase Developers plc This manual was produced using Doc-To-Help, by WexTech Systems, Inc. WexTech Systems, Inc. 310 Madison Avenue, Suite 905 New York, NY 10017

More information

Data Modeling. Database Systems: The Complete Book Ch. 4.1-4.5, 7.1-7.4

Data Modeling. Database Systems: The Complete Book Ch. 4.1-4.5, 7.1-7.4 Data Modeling Database Systems: The Complete Book Ch. 4.1-4.5, 7.1-7.4 Data Modeling Schema: The structure of the data Structured Data: Relational, XML-DTD, etc Unstructured Data: CSV, JSON But where does

More information

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals Oracle University Contact Us: +966 12 739 894 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training is designed to

More information

There are five fields or columns, with names and types as shown above.

There are five fields or columns, with names and types as shown above. 3 THE RELATIONAL MODEL Exercise 3.1 Define the following terms: relation schema, relational database schema, domain, attribute, attribute domain, relation instance, relation cardinality, andrelation degree.

More information

Database SQL messages and codes

Database SQL messages and codes System i Database SQL messages and codes Version 5 Release 4 System i Database SQL messages and codes Version 5 Release 4 Note Before using this information and the product it supports, read the information

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle University Contact Us: + 38516306373 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the

More information

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5 ERserver iseries DB2 Universal Database for iseries SQL Programming with Host Languages Version 5 ERserver iseries DB2 Universal Database for iseries SQL Programming with Host Languages Version 5 Copyright

More information

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT INTRODUCTION: Course Objectives I-2 About PL/SQL I-3 PL/SQL Environment I-4 Benefits of PL/SQL I-5 Benefits of Subprograms I-10 Invoking Stored Procedures

More information

Programming with SQL

Programming with SQL Unit 43: Programming with SQL Learning Outcomes A candidate following a programme of learning leading to this unit will be able to: Create queries to retrieve information from relational databases using

More information

IT2305 Database Systems I (Compulsory)

IT2305 Database Systems I (Compulsory) Database Systems I (Compulsory) INTRODUCTION This is one of the 4 modules designed for Semester 2 of Bachelor of Information Technology Degree program. CREDITS: 04 LEARNING OUTCOMES On completion of this

More information

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

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

More information

EECS 647: Introduction to Database Systems

EECS 647: Introduction to Database Systems EECS 647: Introduction to Database Systems Instructor: Luke Huan Spring 2013 Administrative Take home background survey is due this coming Friday The grader of this course is Ms. Xiaoli Li and her email

More information

IT2304: Database Systems 1 (DBS 1)

IT2304: Database Systems 1 (DBS 1) : Database Systems 1 (DBS 1) (Compulsory) 1. OUTLINE OF SYLLABUS Topic Minimum number of hours Introduction to DBMS 07 Relational Data Model 03 Data manipulation using Relational Algebra 06 Data manipulation

More information

SQL NULL s, Constraints, Triggers

SQL NULL s, Constraints, Triggers CS145 Lecture Notes #9 SQL NULL s, Constraints, Triggers Example schema: CREATE TABLE Student (SID INTEGER PRIMARY KEY, name CHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Take (SID INTEGER, CID CHAR(10),

More information

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala 2.5.30, as well as the version history.

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala 2.5.30, as well as the version history. Cloudera ODBC Driver for Impala 2.5.30 The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala 2.5.30, as well as the version history. The following are highlights

More information

Advanced SQL. Jim Mason. www.ebt-now.com Web solutions for iseries engineer, build, deploy, support, train 508-728-4353. jemason@ebt-now.

Advanced SQL. Jim Mason. www.ebt-now.com Web solutions for iseries engineer, build, deploy, support, train 508-728-4353. jemason@ebt-now. Advanced SQL Jim Mason jemason@ebt-now.com www.ebt-now.com Web solutions for iseries engineer, build, deploy, support, train 508-728-4353 What We ll Cover SQL and Database environments Managing Database

More information

Database Migration from MySQL to RDM Server

Database Migration from MySQL to RDM Server MIGRATION GUIDE Database Migration from MySQL to RDM Server A Birdstep Technology, Inc. Raima Embedded Database Division Migration Guide Published: May, 2009 Author: Daigoro F. Toyama Senior Software Engineer

More information

BCA. Database Management System

BCA. Database Management System BCA IV Sem Database Management System Multiple choice questions 1. A Database Management System (DBMS) is A. Collection of interrelated data B. Collection of programs to access data C. Collection of data

More information

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang Supplement IV.C: Tutorial for Oracle For Introduction to Java Programming By Y. Daniel Liang This supplement covers the following topics: Connecting and Using Oracle Creating User Accounts Accessing Oracle

More information

Oracle Database: Introduction to SQL

Oracle Database: Introduction to SQL Oracle University Contact Us: +381 11 2016811 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn Understanding the basic concepts of relational databases ensure refined code by developers.

More information

Choosing a Data Model for Your Database

Choosing a Data Model for Your Database In This Chapter This chapter describes several issues that a database administrator (DBA) must understand to effectively plan for a database. It discusses the following topics: Choosing a data model for

More information

Oracle Database 12c: Introduction to SQL Ed 1.1

Oracle Database 12c: Introduction to SQL Ed 1.1 Oracle University Contact Us: 1.800.529.0165 Oracle Database 12c: Introduction to SQL Ed 1.1 Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training helps you write subqueries,

More information

Oracle Database: Introduction to SQL

Oracle Database: Introduction to SQL Oracle University Contact Us: 1.800.529.0165 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn View a newer version of this course This Oracle Database: Introduction to SQL training

More information

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database 45 CHAPTER 3 Relational Database Management System: Oracle This chapter introduces the student to the basic utilities used to interact with Oracle DBMS. The chapter also introduces the student to programming

More information

CSC 443 Data Base Management Systems. Basic SQL

CSC 443 Data Base Management Systems. Basic SQL CSC 443 Data Base Management Systems Lecture 6 SQL As A Data Definition Language Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured

More information

Self-test Database application programming with JDBC

Self-test Database application programming with JDBC Self-test Database application programming with JDBC Document: e1216test.fm 18/04/2012 ABIS Training & Consulting P.O. Box 220 B-3000 Leuven Belgium TRAINING & CONSULTING INTRODUCTION TO THE SELF-TEST

More information

Package sjdbc. R topics documented: February 20, 2015

Package sjdbc. R topics documented: February 20, 2015 Package sjdbc February 20, 2015 Version 1.5.0-71 Title JDBC Driver Interface Author TIBCO Software Inc. Maintainer Stephen Kaluzny Provides a database-independent JDBC interface. License

More information

New Security Options in DB2 for z/os Release 9 and 10

New Security Options in DB2 for z/os Release 9 and 10 New Security Options in DB2 for z/os Release 9 and 10 IBM has added several security improvements for DB2 (IBM s mainframe strategic database software) in these releases. Both Data Security Officers and

More information

Oracle Database: Introduction to SQL

Oracle Database: Introduction to SQL Oracle University Contact Us: 1.800.529.0165 Oracle Database: Introduction to SQL Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training teaches you how to write subqueries,

More information

Relational model. Relational model - practice. Relational Database Definitions 9/27/11. Relational model. Relational Database: Terminology

Relational model. Relational model - practice. Relational Database Definitions 9/27/11. Relational model. Relational Database: Terminology COS 597A: Principles of Database and Information Systems elational model elational model A formal (mathematical) model to represent objects (data/information), relationships between objects Constraints

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle University Contact Us: 001-855-844-3881 & 001-800-514-06-97 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals

More information

DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added?

DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added? DBMS Questions 1.) Which type of file is part of the Oracle database? A.) B.) C.) D.) Control file Password file Parameter files Archived log files 2.) Which statements are use to UNLOCK the user? A.)

More information

A basic create statement for a simple student table would look like the following.

A basic create statement for a simple student table would look like the following. Creating Tables A basic create statement for a simple student table would look like the following. create table Student (SID varchar(10), FirstName varchar(30), LastName varchar(30), EmailAddress varchar(30));

More information

Oracle8/ SQLJ Programming

Oracle8/ SQLJ Programming Technisch&AJniversitatDarmstadt Fachbeteich IpfcJrrnatik Fachgebiet PrjN^ische Informattk 7 '64283 Dar ORACLE Oracle Press Oracle8/ SQLJ Programming Tecbnischa UniversMt Osr FACHBEREICH INFORMATiK BIBLIOTHEK

More information

Database Application Development. Overview. SQL in Application Code. Chapter 6

Database Application Development. Overview. SQL in Application Code. Chapter 6 Database Application Development Chapter 6 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Overview Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic

More information

FileMaker 11. ODBC and JDBC Guide

FileMaker 11. ODBC and JDBC Guide FileMaker 11 ODBC and JDBC Guide 2004 2010 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker is a trademark of FileMaker, Inc. registered

More information

Using SQL Server Management Studio

Using SQL Server Management Studio Using SQL Server Management Studio Microsoft SQL Server Management Studio 2005 is a graphical tool for database designer or programmer. With SQL Server Management Studio 2005 you can: Create databases

More information

MOC 20461C: Querying Microsoft SQL Server. Course Overview

MOC 20461C: Querying Microsoft SQL Server. Course Overview MOC 20461C: Querying Microsoft SQL Server Course Overview This course provides students with the knowledge and skills to query Microsoft SQL Server. Students will learn about T-SQL querying, SQL Server

More information

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014 SQL: Programming Introduction to Databases CompSci 316 Fall 2014 2 Announcements (Tue., Oct. 7) Homework #2 due today midnight Sample solution to be posted by tomorrow evening Midterm in class this Thursday

More information

Chapter 5. SQL: Queries, Constraints, Triggers

Chapter 5. SQL: Queries, Constraints, Triggers Chapter 5 SQL: Queries, Constraints, Triggers 1 Overview: aspects of SQL DML: Data Management Language. Pose queries (Ch. 5) and insert, delete, modify rows (Ch. 3) DDL: Data Definition Language. Creation,

More information

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff D80198GC10 Oracle Database 12c SQL and Fundamentals Summary Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff Level Professional Delivery Method Instructor-led

More information

Oracle to MySQL Migration

Oracle to MySQL Migration to Migration Stored Procedures, Packages, Triggers, Scripts and Applications White Paper March 2009, Ispirer Systems Ltd. Copyright 1999-2012. Ispirer Systems Ltd. All Rights Reserved. 1 Introduction The

More information

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

PL/SQL Overview. Basic Structure and Syntax of PL/SQL PL/SQL Overview PL/SQL is Procedural Language extension to SQL. It is loosely based on Ada (a variant of Pascal developed for the US Dept of Defense). PL/SQL was first released in ١٩٩٢ as an optional extension

More information

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables Overview Database Application Development Chapter 6 Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures Database Management Systems 3ed,

More information

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer. Test: Final Exam Semester 1 Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer. Section 6 1. The following code does not violate any constraints and will

More information

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1 Handling Exceptions Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1 Objectives After completing this lesson, you should be able to do the following: Define PL/SQL

More information

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema: CS145 Lecture Notes #10 SQL Programming Example schema: CREATE TABLE Student (SID INTEGER PRIMARY KEY, name CHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Take (SID INTEGER, CID CHAR(10), PRIMARY KEY(SID,

More information

SQL Server Database Coding Standards and Guidelines

SQL Server Database Coding Standards and Guidelines SQL Server Database Coding Standards and Guidelines http://www.sqlauthority.com Naming Tables: Stored Procs: Triggers: Indexes: Primary Keys: Foreign Keys: Defaults: Columns: General Rules: Rules: Pascal

More information

www.gr8ambitionz.com

www.gr8ambitionz.com Data Base Management Systems (DBMS) Study Material (Objective Type questions with Answers) Shared by Akhil Arora Powered by www. your A to Z competitive exam guide Database Objective type questions Q.1

More information

Information Systems SQL. Nikolaj Popov

Information Systems SQL. Nikolaj Popov Information Systems SQL Nikolaj Popov Research Institute for Symbolic Computation Johannes Kepler University of Linz, Austria popov@risc.uni-linz.ac.at Outline SQL Table Creation Populating and Modifying

More information

Embedded SQL. Unit 5.1. Dr Gordon Russell, Copyright @ Napier University

Embedded SQL. Unit 5.1. Dr Gordon Russell, Copyright @ Napier University Embedded SQL Unit 5.1 Unit 5.1 - Embedde SQL - V2.0 1 Interactive SQL So far in the module we have considered only the SQL queries which you can type in at the SQL prompt. We refer to this as interactive

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

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems CSC 74 Database Management Systems Topic #0: SQL Part A: Data Definition Language (DDL) Spring 00 CSC 74: DBMS by Dr. Peng Ning Spring 00 CSC 74: DBMS by Dr. Peng Ning Schema and Catalog Schema A collection

More information