Questions to the exam Lectures 1: 1. Basic database information A database is an organized collection of data. It is a collection of schemas, tables, queries, reports, views, and other objects.The data is often organized so that it is easily accessible. 2. What is a Database? A database is simply a collection of organized information, usually as a set of related lists of similar entries. The following are examples of databases that we use often: 1) address book; 2) dictionary; 3) telephone book. 3.Database Management System (DBMS) General-aim software system that facilitates the processes of defining, constructing and manipulating databases - DBMS. You can also write your own set of programs to create and maintain the database, i.e. your own Special-aim DBMS software. Database + Software == Database System. 4. Database schema The database schema of a database system is its structure described in a formal language supported by the database management system (DBMS). The term "schema" refers to the organisation of data as a blueprint of how the database is constructed (divided into database tables in the case of relational databases). 5. Basic concepts and definitions: information, data Information is stimuli that has meaning in some context for its receiver. When information is entered into and stored in a computer, it is generally referred to as data. Database concepts: Database – a collection of related tables. Tables – a collection of related records – collection of related entities. Record – collection of fields (table row) –represents an entity. Field – collection of characters (table column) – represents an attribute. Character – single alphabetic, numeric or other symbol. 6. Abstract Concepts: Entity, Attribute 1) Entity – person, place, object or event – stored as a record or a table row. An entity is a real-world item or concept that exists on its own. The set of all possible values for an entity is the entity type. 2) Attribute – characteristic of an entity – stored as field or table column. An attribute of an entity is a particular property that describes the entity. The set of all possible values of an attribute is the attribute domain. Attribute can be simple or composite. 7. Relationship Modelling Entity–relationship modeling was developed for database design by Peter Chen and published in 1976. Some ER modelers show super and subtype entities connected by generalization-specialization relationships, and an ER model can be used also in the specification of domain-specific ontologies. Data Modeling is a technique to document a software system using diagrams and symbols. It is used to represent communication of data. 1) The highest level of abstraction for the data model is called the Entity Relationship Diagram (ERD). It is a graphical representation of data requirements for a database. 2) 8. Entity-Relationship (ER) model The Entity-Relationship (ER) model, a high-level data model that is useful in developing a conceptual design for a database. An ER model is composed of entity types (which classify the things of interest) and specifies relationships that can exist between instances of those entity types. An entity is a real-world item or concept that exists on its own. The set of all possible values for an entity is the entity type There are three components in ERD: 1) Entities: Number of tables you need for your database. 2) Attributes: Information such as property, facts you need to describe each table. 3) Relationships: How tables are linked together. 9. basic concepts in building relationships Primary Key - or identifier is an attribute or a set of attributes that uniquely identifies an instance of the entity. 1) Foreign key - A foreign key+ (sometimes called a referencing key) is a key used to link two tables together. Typically you take the primary key field from one table and insert it into the other table where it becomes a foreign key. We can have more than one foreign key in a table. 2) Primary Key, Foreign key Answer is in question 9. 10. 11. Relationships and Diagramming Relationships Relationships are the associations between the entities. Relationships have: 1) a name ; 2) A set of entities that participate in them ; 3) A degree is the number of entities that participate ; 4) a cardinality ratio 12.3 types of relationship: 1) One to one (1:1) 2) One to many (1:M) 3) Many to many (M:M) Answer: Each entity in a relationship can participate in zero, one, or more than one instances of that relationship This leads to 3 types of relationship: One to one (1:1) - - A single entity instance in one entity class is related to a single entity instance in another entity class. 1) Ex. Each lecturer has his office One to many (1:M) - A single entity instance in one entity class is related to multiple entity instances in another entity class Ex. A lecturer may teach many students, but each student has just one tutor 2) Many to many (M:M) - Each entity instance in one entity class is related to multiple entity instances in another entity class; and vice versa. 3) Ex. Each student can take many classes, and each class can be taken by many students. 13.Essential elements of the database definition * * * * * * * * The database schema Schema objects Tables Fields and columns Records and rows Keys Relationships Data types 14.Components of DBMS Software - this is the set of programs used to control and manage the overall database. It includes DBMS software, the OS, the network software to share the data among users and apps to access the data in DBMS. 1) Hardware - Consists of devices such as computers, I/O devices, storage devices. 3) Data - DBMS exists to collect, store, process and access data. It contains both the actual or operational data and the metadata. 2) Procedures - These are the instructions and rules that assist on how to use the DBMS 4) Database Access Language - This is used to access the data to and from the database, to enter new data, update existing data, or retrieve required data from databases. The user writes a set of appropriate commands in a database access language, submits these to the DBMS, which then processes the data and generates and displays results in a human readable format. 5) Query Processor - This transforms the user queries into a series of low level instructions. 6) Database Engine - The core service for storing, processing, and securing data. It is often used to create relational databases for online transaction processing or online analytical processing data. 7) Report Writer - Also referred to as the report generator, it is a program that extracts information from one or more files and presents the information in a specified format. 8) Lectures 2, 3: 15. Database Design - the main stages Database design is the process of transforming a logical data model into an actual physical database. 1) 2) 3) 4) Requirements Analysis (Problem) Data Analysis, Conceptual Design (Data requirements) Logical Database Design (Conceptual schema) Physical Database Design (Logical schema) 16. What is a Requirements Specification? A data warehouse requirements specification states the project objectives and goals and related data storage, data integration, information delivery, security, quality, usage, functional and non-functional requirements that must be delivered in order to achieve the project objectives. 17. Conceptual Data Model Should provide an appreciation for the overall scope of data storage requirements; Should include definitions of each conceptual entity; Should confirm understanding of the project data storage scope; Logical Data Model (Attributes, three types of attributes) 1) Unique Identifier – uniquely identifies an entity instance 2) Mandatory – its value cannot be null 3) Optional – its value can be null. Answer: 18. 1) 2) 3) 4) Should finalize structure and design requirements; Should involve data modeling sessions with selected stakeholders; Should document entity definitions; Should document entity attributes; 19. Physical Schema A physical data model (or database design) is a representation of a data design as implemented, or intended to be implemented, in a database management system. 20. The Relational Model no duplicate tuples in a relation - a relation is a set of tuples 2) no ordering of tuples in a relation - a relation is a set 3) attributes of a relation have an implied ordering - but used as functions and referenced by name, not position 4) every tuple must have attribute values drawn from all of the domains of the relation or the special value NULL 1) all a domain’s values and hence attribute’s values are atomic. 5) 21. The Evolution of Data Models (Hierarchical, Network, Relational, Entity relationship, Object oriented (OO)) Answer: 1) The Hierarchical Model developed in the 1960s to manage large amounts of data for Hierarchical complex manufacturing projects. * * * Basic logical structure is represented by an upside-down “tree" The hierarchical structure contains levels, or segments Depicts a set of one-to-many (1:M) relationships between a parent and its children segments Disadvantages : 1) Complex to implement 2) Difficult to manage 3) Lacks structural independence 4) Implementatio n limitations 5) Lack of standards 2) The Network Model: Schema: Conceptual organization of entire database as viewed by the database administrator * Subschema: Defines database portion “seen” by the application programs that actually produce the desired information from data contained within the database * Data Management Language (DML): Defines the environment in which data can be managed *DDL: Enables database administrator to define schema components * *Subschema DDL: Allows application programs to define database components that will be used *DML: Works with the data in the database Disadvantages: Too cumbersome ; Any structural change in the database could produce havoc in all application programs that drew data from the database 3) The Relational Model: In 1970, E.F. Codd proposed the relational data model which was widely accepted as the standard data model. At that time, office automation was the major use of data storage systems, which resulted in proposal of many data models. It was conceptually simple and considered ingenious but impractical in 1970 4) The Entity Relationship Model: 1. Widely accepted and adapted graphical tool for data modeling Introduced by Chen in 1976 Graphical representation of entities and their relationships in a database structure 2. 3. Entity relationship diagram (ERD) * Uses graphic representations to model database components * Entity is mapped to a relational table 5. Entity instance (or occurrence) is row in table 4. 22. Keys (Primary Key, Foreign Key, Candidate Key) Key (SuperKey) - a set of attributes whose values together uniquely identify every tuple in a relation. Let t1 and t2 be two tuples on relation r of relation schema R, and sk be a set of attributes whose values are the key for the relation schema R, then t1[superkey] != t2[superkey]. 1) (Candidate) Key a (super)key that is minimal, i.e. has no proper subsets that still uniquely identify every tuple in a relation. There can be several for one relation. 2) Primary Key a candidate key chosen to be the main key for the relation. There is only one for each relation. 3) 4)Foreign Key a candidate key of relation A situated in relation B. 23. Normalization Database normalization - is the process of organizing data into tables in such a way that the results of using the database are always unambiguous and as intended. Database normalization - is the process of organizing non structured data in to structured data. The process eliminates certain types of data redundancy, avoids some update anomalies, and results in a clearer data model. 24. Need of Database Normalization 1) If your database objects are not in structured or normalized way it is difficult to update the database without facing the database loss. 2) Normalization is part of successful database design. 3) Without Database normalization the database system can be slow, inaccurate and inefficient. 25. Levels of Normalization 1. 2. 3. 4. 5. 6. 7. 8. Various levels of normalization are: First Normal Form (1NF) Second Normal Form (2NF) Third Normal Form (3NF) Boyce-Codd Normal Form (BCNF) Fourth Normal Form (4NF) Fifth Normal Form (5NF) Domain Key Normal Form (DKNF) Most databases should be 3NF or BCNF in order to avoid the database anomalies. any relation that is in BCNF, is in 3NF; any relation in 3NF is in 2NF; and any relation in 2NF is in 1NF. 26. First Normal Form (1NF) A relational database is in First Normal Form (1NF) if each attribute is single valued with atomic values. 1NF is considered the weakest 27. Second Normal Form (2NF) A relational database is in Second Normal Form (2NF) if it is in 1NF and each attribute that is not a primary key is fully functionally dependent on the entity's primary key. 2NF is stronger than 1NF 28. Third Normal Form (3NF) A relational database is in Third Normal Form (3NF) if it is in 2NF and no non-primary key attribute is transitively dependent on a candidate key. 3NF is stronger than 2NF 29. Boyce-Codda Normal Form (BCNF) Boyce–Codd normal form (or BCNF or 3.5NF) is a normal form used in database normalization. BCNF is considered the strongest Lectures 4-9: What is SQL? SQL (pronounced sequel) is an acronym for Structured Query Language, a standardized language used to access and manipulate data. 30. CODD’S RULES Answer: later expanded to include additional rules, describe goals for database management systems to cope with ever-challenging and demanding database requirements. 31. Information Rule: All information in a relational database including table names, column names are represented by values in tables. 1) 2) Guaranteed Access Rule: Every piece of data in a relational database, can be accessed by using combination of a table name, a primary key value that identifies the row and column name which identified a cell. 3) Systematic Treatment of Nulls Rule: The RDBMS handles records that have unknown or inapplicable values in a pre-defined fashion. Also, the RDBMS distinguishes between zeros, blanks and nulls in the records. 4) Active On-line catalog based on the relational model: The description of a database and in its contents are database tables and therefore can be queried on-line via the data manipulation language. Comprehensive Data Sublanguage Rule: A RDBMS may support several languages. But at least one of them should allow user to do all of the following: define tables and views, query and update the data, set integrity constraints, set authorizations and define transaction 5) 6) View Updating Rule: Any view that is theoretically updateable can be updated using the RDBMS. 7) High-Level Insert, Update and Delete: The RDBMS supports insertions, updation and deletion at a table level. Physical Data Independence: The execution of adhoc requests and application programs is not affected by changes in the physical data access and storage methods. 8) 9) 9.Logical Data Independence: Logical changes in tables and views such adding/deleting columns or changing fields lengths need not necessitate modifications in the programs or in the format of requests. 10) 10. Integrity Independence: Like table/view definition, integrity constraints are stored in the online catalog and can therefore be changed without necessitating changes in the application programs. 11) 11.Distribution Independence: Application programs and ad hoc requests are not affected by change in the distribution of physical data. 12) No subversion Rule: If the RDBMS has a language that accesses the information of a record at a time, this language should not be used to bypass the integrity constraints. This is necessary for data integrity. 32. Logical Data Independence Logical changes in tables and views such adding/deleting columns or changing fields lengths need not necessitate modifications in the programs or in the format of requests. 33. Basic Elements of Oracle SQL, SQL commands Oracle SQL Developer is a free integrated development environment that simplifies the development and management of Oracle Database in both traditional and Cloud deployments. The standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to accomplish almost everything that one needs to do with a database 34. Data Definition Language commands (DDL) DDL is a standardized language with commands to define the storage groups (stogroups), different structures and objects in a database. DDL statements create, modify and remove database objects, such as tables, indexes and stogroups. DDL is also used in a generic sense to refer to any language that describes data. 1. CREATE 2. ALTER 3. DROP 4. RENAME 5. TRUNCATE 6. COMMENT 35. Data Manipulation Language commands (DML) A data manipulation language (DML) is a family of computer languages including commands permitting users to manipulate data in a database. This manipulation involves inserting data into database tables, retrieving existing data, deleting data from existing tables and modifying existing data. 36. Data Control Language commands (DCL) Data Control Language (or DCL) consists of statements that control security and concurrent access to table data. Instructs the XDB Server to make permanent all data changes resulting from DML statements executed by a transaction. Connects the application process (or user) to a designated XDB Server or DB2 location. 37. Oracle SQL Developer Oracle SQL Developer is a free integrated development environment that simplifies the development and management of Oracle Database in both traditional and Cloud deployments. Oracle SQL Developer offers development of your PL/SQL applications, a worksheet for running queries and scripts, a DBA console for managing the database, a reports interface 38. Oracle SQL Developer Data Modeler Oracle SQL Developer Data Modeler is a free graphical tool that enhances productivity and simplifies data modeling tasks. Using Oracle SQL Developer Data Modeler users can create, browse and edit, logical, relational, physical, multi-dimensional, and data type models. The Data Modeler provides forward and reverse engineering capabilities and supports collaborative development through integrated source code control. The Data Modeler can be used in both traditional and in Cloud environments. SQL Database Data Types Answer: 39. * DATA TYPES represents the type of data an object is holding. Data Types are defined for columns of a table, local/global variables, input/output arguments of procedures etc.. * Each database system (MS SQL Server, MYSQL, DB2, Oracle etc.) have its own long list of data types but several data types are common in most of them. * Data types: 1. Date Time Data Type: datetime: This data type is used to store complete date and time information. The date to be stored has range from 01/01/1753 to 12/31/9999. * date: This data type is used to store only date information. * time: This data type is used to store only time specific information. * 2. String Data Type char(x): This data type is space padded to fill the number of characters specified. Here x is the number of characters to store. * varchar(x), varchar2(x): This type got its name from Varying Characters. This data type doesn’t pad unnecessary space. Here x is the number of characters to store * text: This type is used to store long textual information. * 3. Other data types: *Blob *money *binary 40. Oracle SQL Functions (Number Functions, Character Functions, Aggregate Functions, Date and Time Functions) 1) Number Functions: Number functions accept numeric input and return numeric values. Most of these functions return values that are accurate to 38 decimal digits. * The number functions available in Oracle are: ABS ACOS ASIN ATAN ATAN2 BITAND CEIL COS COSH EXP FLOOR LN LOG MOD POWER ROUND (number) SIGN SIN SINH SQRT TAN TANH TRUNC (number) 2) Character Functions: Character functions operate on values of datatype CHAR or VARCHAR. LOWER() - Returns a given string in lower case. Ex. select LOWER(‘SAMI’) from dual; *UPPER() - Returns a given string in upper case. * Aggregate Functions: Aggregate functions return a single value based on groups of rows, rather than single value for each row. * You can use Aggregate functions in select lists and in ORDER BY and HAVING clauses. * They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle divides the rows of a queried table or view into groups. * Date and Time Functions: * To see the system date and time use the following functions: 1) 2) 3) CURRENT_DATE :returns the current date in the session time zone, in a value in the Gregorian calendar of datatype DATE SYSDATE :Returns the current date and time. SYSTIMESTAMP: The SYSTIMESTAMP function returns the system date, including fractional seconds and time zone of the database. The return type is TIMESTAMP WITH TIME ZONE. 41. SQL Logical Operators There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. * When retrieving data using a SELECT statement, you can use logical operators in the WHERE clause, which allows you to combine more than one condition. OR - For the row to be selected at least one of the conditions must be true. AND - For a row to be selected all the specified conditions must be true. NOT - For a row to be selected the specified condition must be false. 42. Comparison Operators, Logical Operators Comparison operators are used to compare the column data with specific values in a condition. Comparison Operators are also used along with the SELECT statement to filter data based on specific conditions: Comparison Operators & Description: = equal to <>, != is not equal to < less than > greater than >= greater than or equal to <= less than or equal to * * Logical Operators & Description: There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at a time to determine whether a row can be selected for the output. OR For the row to be selected at least one of the conditions must be true. AND For a row to be selected all the specified conditions must be true. NOT For a row to be selected the specified condition must be false. 43. SQL GROUP Functions Group functions are builtin SQL functions that operate on groups of rows and return one value for the entire group. These functions are: * * * * * * COUNT - Returns the number of rows in the query. If you specify the asterisk (*), this function returns all rows, including duplicates and nulls. COUNT never returns null. MAX, MIN, AVG, SUM, DISTINCT The Syntax of SQL SELECT Statement SELECT column_list FROM tablename [WHERE Clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause]; 44. The operators: LIKE, DISTINCT, ORDER BY 1) LIKE - The LIKE command is used in a WHERE clause to search for a specified pattern in a column. 45. The LIKE operator: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’ * * * * s LIKE p: pattern matching on strings p may contain two special symbols: % = any sequence of characters _ = any single character DISTINCT: The SELECT DISTINCT command returns only distinct (different) values in the result set. Ex. 2) The following SQL statement selects only the DISTINCT values from the "Country" column in the " "Customers" table: SELECT DISTINCT Country FROM Customers; 3) * * * ORDER BY Used to sort output of SELECT statement Can sort by one or more columns and use either an ascending or descending order Ordering is ascending, unless you specify the DESC keyword. SELECT PName, Price, Manufacturer FROM Product WHERE Category=‘gizmo’ AND Price > 50 ORDER BY Price, PName 46. Commands: the FROM and WHERE clauses, GROUP BY 1) FROM and WHERE: The WHERE Clause is used when you want to retrieve specific information from a table excluding other irrelevant data. * WHERE {column or expression} comparison-operator SELECT * FROM Customer WHERE ROWNUM <= 3; SYNTAX FOR A WHERE CLAUSE WITH SELECT STATEMENT IS: * SELECT column_list FROM table-name WHERE condition; * column or expression - Is the column of a table or a expression * comparison-operator - operators like = < > etc. * value - Any user value or a column name for comparison 2) GROUP BY: The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns. GROUP BY Syntax SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s); 47. Syntax command [INNER] JOIN ... ON, example [INNER] JOIN ... ON * An INNER JOIN combines data from two tables where there is a match on the joining column(s) in both tables. Example * SELECT d.department_name, * e.employee_name * FROM departments d * JOIN employees e ON d.depart ment_id = e.department_id * WHERE d.department_id >= 30 * ORDER BY d.department_name; 48. Syntax command LEFT [OUTER] JOIN, RIGHT [OUTER] JOIN, example 1) LEFT [OUTER] JOIN A LEFT [OUTER] JOIN returns all valid rows from the table on the left side of the JOIN keyword, along with the values from the table on the right side, or NULLs if a matching row doesn't exist. * Using the previous example, but switching to a LEFT OUTER JOIN means we will see the OPERATIONS department, even though it has no employees. * Example. SELECT d.department_name, e.employee_name FROM departments d LEFT OUTER JOIN employees e ON d.department_id = e.department_id WHERE d.department_id >= 30 ORDER BY d.department_name, e.employee _name; 2) RIGHT [OUTER] JOIN The RIGHT [OUTER] JOIN is the opposite of the LEFT [OUTER] JOIN. It returns all valid rows from the table on the right side of the JOIN keyword, along with the values from the table on the left side, or NULLs if a matching row doesn't exist. * The following example has altered the order of the tables so a RIGHT [OUTER] JOIN is now required. * Example. SELECT d.department_name, e.employee_name FROM employees e RIGHT OUTER JOIN departments d ON e.department_id = d.department_id WHERE d.department_id >= 30 ORDER BY d.department_name, e.employe e_name; 49. Syntax command FULL [OUTER] JOIN, example FULL [OUTER] JOIN A FULL [OUTER] JOIN combines all the rows from the tables on the left and right sides of the join. If there is a conventional match it is made. If either side has missing data, it is replaced by NULLs, rather than throwing the row away. * To see a working example, we need to add another employee who is not assigned to a department. Example. SELECT d.department_name, e.employee_name FROM employees e FULL OUTER JOIN departments d ON e.department_id = d.department_id ORDER BY d.department_name, e.employee_name; 50. Syntax command CROSS JOIN, example CROSS JOIN A CROSS JOIN is the deliberate creation of a Cartesian product. * There are no join columns specified, so every possible combination of rows between the two tables is produced. Example. SELECT e.employee_name, d.department_name FROM employees e CROSS JOIN departments d ORDER BY e.employee_name, d.depar tment_name; 51. Syntax command NATURAL JOIN, example NATURAL JOIN A NATURAL JOIN is a variant on an INNER JOIN. The join columns are determined implicitly, based on the column names. Any columns that share the same name between the two tables are assumed to be join columns. Example. SELECT e.employee_name, d.department_name FROM employees e NATURAL JOIN departments d ORDER BY e.employee_name, d.department_name; 52. Syntax command [INNER] JOIN ... USING, example [INNER] JOIN ... USING The INNER JOIN ... USING is almost a half-way house between a conventional INNER JOIN and a NATURAL JOIN. The join is made using columns with matching names in each table. This allows to join on a subset of the columns common to both tables. Example. SELECT e.employee_name, d.department_name FROM employees e JOIN departments d USING (department_id) ORDER BY e.employee_name; Lectures 10-14: 53. What is Pl/SQL? PL/SQL is a combination of SQL along with the procedural features of programming languages. * PL/SQL Allows using general programming tools with SQL, for example: Loops (a FOR…LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times), 2. Conditions, 3. Functions, etc. 1. This allows a lot more freedom than general SQL *PL/SQL provides a built in, interpreted and OS independent programming environment. * Direct call can also be made from external programming language calls to database. Features: * * * * * * It supports OOP It supports Development of web apps and server pages It offers extensive error checking. It offers numerous data types. It offers a variety of programming structures. It supports structured programming through functions and procedures. 54) PL/SQL blocks, PL/SQL block structure (three sections) ANSWER: PL/SQL blocks can be divided into two groups: Named - Named blocks are used when creating subroutines. These subroutines are procedures, functions, and packages. 1. Anonymous - PL/SQL blocks do not have names. As a result, they cannot be stored in the database and referenced later. 2. DECLARE (optional) /* Here you declare the variables you will use in this block */ BEGIN (mandatory) /* Here you define the executable statements (what the block DOES!)*/ EXCEPTION (optional) /* Here you define the actions that take place if an exception is thrown during the run of this block */ END; (mandatory) / A correct completion of a block will generate the following message: PL/SQL procedure successfully completed PL/SQL blocks contain three sections Declare section - This is the first section of PL/SQL block which is optional and is used to declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution section. 1. Executable section - Block starts with the reserved keyword BEGIN and ends with END. This is a mandatory section and is the section where the program logic is written to perform any task. 2. Exception-handling section. - The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is the last section of the black and it's optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with errors. 3. 55) DBMS_OUTPUT.PUT_LINE The DBMS_OUTPUT is a built in package that enables you to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages and triggers. Three types of loops in PL/SQL (Simple Loop, For... Loop, While Loop) There are three types of loops in PL/SQL: 56) 1) Simple Loop LOOP statements; EXIT; {or EXIT WHEN condition;} END LOOP; 2) While Loop WHILE <condition> LOOP statements; END LOOP; 1) FOR… LOOP A FOR… LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax. FOR counter IN initial_value .. final_value LOOP sequence_of_statements; END LOOP; 2) 57) PL/SQL Placholders Placeholders are temporary storage area. PL/SQL Placeholders can be any of Variables, Constants and Records. Depending on the kind of data you want to store, you can define placeholders with a name and a datatype. Few of the datatypes used to define placeholders are as given below. Number (n,m) , Char (n) , Varchar2 (n) , Date , Large Objects (LOBs) Syntax to declare a variable: variable_name datatype [NOT NULL := value ]; * * * variable_name is the name of the variable. datatype is a valid PL/SQL datatype. * NOT NULL is an optional specification on the variable. value or DEFAULT value is also an optional specification, where you can initialize a variable. * Variables that are accessible to outer block are also accessible to inner blocks. (Global variables) * Local variables - These are declared in a inner block and cannot be referenced by outside Blocks. 58) What are ARRAYS (VARRAY), associative array? The PL/SQL programming language provides a data structure called the ARRAY (VARRAY), which can store a fixed-size sequential collection of elements of the same type. Varray is a collection method in which the size of the array is fixed. The array size cannot be exceeded than its fixed value. The subscript of the Varray is of a numeric value. Syntax for VARRAY: TYPE <type_name> IS VARRAY (<SIZE>) OF <DATA_TYPE All varrays (arrays) consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. A varray type is created with the CREATE TYPE statement. You must specify the maximum size and the type of elements stored in the varray The basic syntax for creating a VARRAY type at the schema level is − CREATE OR REPLACE TYPE varray_type_name IS VARRAY(n) of <element_type> Maximum size of a varray (array) can be changed using the ALTER TYPE statement. Associative array: Associative arrays are single-dimensional, unbounded, sparse collections of homogeneous elements. meaning that it has a predetermined limits number of elements Associative arrays are one-dimensional arrays (has a single column of data in each row) 2) An associative array is sparse because its elements are not sequential. In other words, an associative array may have gaps between elements. 3) An associative array has elements which have the same data type, or we call them homogenous elements. 1) TYPE associative_array_type IS TABLE OF datatype [NOT NULL] INDEX BY index_type; In this syntax: The associative_array_type is the name of the associative array type. The datatype is the data type of the elements in the array. The index_type is the data type of the index used to organize the elements in the array. Optionally, you can specify NOT NULL to force every element in the array must have a value. 59) There are 4 types of modules in PL/SQL (procedures; functions; triggers; packages). Modules in PL/SQL There are 4 types of modules in PL/SQL: 1) Procedures - series of statements may or may not return a value 1.1 1.2 1.3 * * * * * Creation command Variable declarations Body of procedure\ Cannot call in SELECT statement Use OUT parameter to return the value It is not mandatory to return the value RETURN will simply exit the control from subprogram. Return datatype will not be specified at the time of creation The syntax to create a procedure in Oracle is: CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name]; 2) Functions - series of statements must return a single value Almost exactly like creating a procedure, but you supply a return type CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, parameter2 [mode2] datatype2, . . .)] RETURN datatype IS|AS PL/SQL Block; Calling the function. declare paulRate:=9; Begin dbms_output.put_line(ratingMessage(paulRat e)); end; / * * * Used mainly to perform some calculation Use RETURN to return the value and it is mandatory to return the value RETURN will exit the control from subprogram and also returns the value * Return datatype is mandatory at the time of creation 3) Triggers - series of PL/SQL statements (actions) executing after an event has triggered a condition (ECA). Triggers are special procedures which we want activated when someone has performed some action on the DB. Triggers are written to be executed in response to any of the following events: A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). * A database definition (DDL) statement (CREATE, ALTER, or DROP). * A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN) 4) Packages - package is a group of related functions, procedures, types, cursors, etc. PL/SQL package is like a library once written stored in the Oracle database and can be used by many applications. * A PL/SQL package has two parts: package specification - is the public interface of your applications. The public means the stored function, procedures, types, etc., are accessible from other applications. The package specification is required when you create a new package. 1) A package body contains the code that implements the package specification. The CREATE PACKAGE BODY Statement is used for creating the package body. 2) 60) Cursor. How to use Cursors in Oracle/PLSQL? In Oracle, a cursor is a mechanism by which you can assign a name to a SELECT statement and manipulate the information within that SQL statement. Cursors allow more than one set of data to be retrieved and accessed at the same time in loops Cursor attributes - %notfound, %rowcount, %found & %isopen There are two types of cursors: 1) 2) Implicit cursors Explicit cursors How to use Cursors in Oracle/PLSQL? 1. 2. 3. 4. 5. Create Cursor Declare a Cursor OPEN Statement FETCH Statement CLOSE Statement Part III Many-to_many example: CREATE TABLE films ( film_id INT PRIMARY KEY ,title VARCHAR(50) ,director VARCHAR(50) ,year_released DATETIME ); CREATE TABLE category ( category_id INT PRIMARY KEY ,name VARCHAR(50) ); CREATE TABLE film_category ( film_id INT ,category_id INT ,CONSTRAINT film_cat_pk PRIMARY KEY (film_id, category_id) ,CONSTRAINT FK_film FOREIGN KEY (film_id) REFERENCES films (film_id) ,CONSTRAINT FK_category FOREIGN KEY (category_id) REFERENCES category (category_id) ); One-to-One example: CREATE TABLE employee ( id unknown NOT NULL, salary INTEGER NOT NULL, hire_date DATE NOT NULL, title VARCHAR2(20) NOT NULL, faculty_id unknown NOT NULL ); CREATE UNIQUE INDEX employee__idx ON employee ( faculty_id ASC ); ALTER TABLE employee ADD CONSTRAINT employee_pk PRIMARY KEY ( id ); CREATE TABLE faculty ( id unknown NOT NULL, name VARCHAR2(15) NOT NULL, location_id INTEGER NOT NULL, "desc" VARCHAR2(50) ); ALTER TABLE faculty ADD CONSTRAINT faculty_pk PRIMARY KEY ( id ); ALTER TABLE employee ADD CONSTRAINT employee_faculty_fk FOREIGN KEY ( faculty_id ) REFERENCES faculty ( id );