sybullus of dbms

50
Sybullus of DBMS DBMS Introduction • Introduction to database and DBMS • Application development without a database • Advantages of the DBMS approach • Components of a DBMS • Classification of DBMS Database Design • Identifying user requirement • Logical data modeling • Introduction to E-R diagram • Components of E-R diagram (entities, attributes, relationship) • Designing systems with E-R diagram • Components of class diagrams • Designing system with class diagrams • Domains Data Normalization • Introduction • Tables, Classes and Keys • The need of normalization • First, second and third normal forms • Beyond third normal form • Data rules and Integrity • The effect of business rules • Converting class diagram to normalized table • Data dictionary Introduction TO SQL-Simple Queries • Components of a query • Query basics • The SELECT command

Upload: thakuri-bom-suseel

Post on 29-Apr-2015

112 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Sybullus of DBMS

Sybullus of DBMSDBMSIntroduction • Introduction to database and DBMS• Application development without a database• Advantages of the DBMS approach• Components of a DBMS• Classification of DBMSDatabase Design• Identifying user requirement• Logical data modeling • Introduction to E-R diagram• Components of E-R diagram (entities, attributes, relationship)• Designing systems with E-R diagram• Components of class diagrams• Designing system with class diagrams• DomainsData Normalization• Introduction • Tables, Classes and Keys• The need of normalization• First, second and third normal forms• Beyond third normal form• Data rules and Integrity• The effect of business rules• Converting class diagram to normalized table• Data dictionaryIntroduction TO SQL-Simple Queries• Components of a query• Query basics• The SELECT command• Totals and sub-totals-GROUP BY and HAVING• Computation, Aggregation function• Working with multiple table-JOINSAdvances Queries• Advanced queries and sub queries• Sub queries with ANY, ALL, NOT IN etc.

Page 2: Sybullus of DBMS

• Different types of Joints (Inner Join, Outer Joins, Reflexive Joins, Inequality Joins etc.)• UNION, INTERSECT, EXCEPT• SQL DDL command (CREATE TABLE, ALTER TABLE, DROP etc)• SQL DML command (INSERT, DELETE, UPDATE, etc)

Forms and Report• Introduction• Effective design of forms and report• Form Layout• Creating Forms• Reports

Data Manipulation• Introduction• Procedural language• Programming environment • Data on Forms• Using programs to save and retrieve data in the database• Handling errorApplication Development• Why application ?• Application Structure• User interface features• Transactions• Forms to help user• Custom reportsDatabase Administration• Database administration• Database administrator (DBA)• Database tasks by development stages• Backup and recovery issues of database• Security and privacy issued to database

Practical: There shall be lab exercises covering all features of the above syllabusBook: Database Management Systems by Gerald V. Post, McGrawhillPosted by Sujan Kunwar at 8:14 AM 1 commentsEmail This BlogThis! Share to Twitter Share to Facebook

Page 3: Sybullus of DBMS

1.Introduction to DBMSIntroductionData:- Data is a collection of facts, figures and statistics related to an object. Data can be processed to create useful information. It also enables the user to make better decision for future. Data is very useful for generating reports, graphs and statistics.Example:Students fill an admission form when they get admission in college. The form consists of raw facts about the students. These raw facts are student’s name, father name, address, etc. The purpose of collecting this data is to maintain the records of the students during their study period in the college.

Data base:-A data base is a collection of information that is organization so that is can easily be accessed, managed, and updated. In one view, database can be classified according to types of content; bibliographic, full-text, numeric, and images

Database Management System:A database management system (DBMS), sometime just called a database manger, is a program that lets one or more computer users create and access data in a database.

OrDatabase Management System (DBMS) is a software package that allows data to be effectively stored, retrieved and manipulated and the data stores in a DBMS package can be accessed by multiple users and by multiple application programs like (SQL Server, Oracle, and Ms-Access).OrA database management system (DBMS), sometimes just called a database manager, is a program that lets one or more computer users create and access data in a database. The DBMS manages user requests (and requests from other programs) so that users and other programs are free from having to understand where the data is physically located on storage media and, in a multi-user system, who else may also be accessing the data. The most typical DBMS is a relational database management system (RDBMS). A standard user and program interface is the Structured Query Language (SQL). A newer kind of DBMS is the object-oriented database management system (ODBMS). A DBMS can be thought of as a file manager that manages data in databases rather than files in file systems. Some DBMS examples include MySQL, PostgreSQL, Microsoft Access, SQL Server, FileMaker, Oracle, RDBMS, dBASE, Clipper, and FoxPro.

Page 4: Sybullus of DBMS

Application development without a databaseMost programming languages have to ability to create and store data in separate files. COBOL programs make extensive use of basic files. Today many applications are written using traditional files to store data. The basics problems with file approach are :-a. Uncontrolled duplication (Wastes space, hard to update all files), b. Inconsistent data, c. Inflexibility (Hard to change data), d. Limited data sharing, e. Poor programmer productively.For example:-If an application needs customer data, the program must define a customer files and contain all the code to create the files, store the data, and retrieve the data as it is needed and to store data in any format. It is possible to share to across application if all programmers follow the standards.

Advantages of DBMS:1. DBMS Provides "Reduced Application Development Time". No doubt it takes more time for designing a database than making a single application but once a database is created then it becomes very easy to make new application by using facilities provided by DBMS.2. DBMS provides flexibility. To the requirements we have to do changes in database. Using DBMS, we can change the structure of database and advantage is that it will not affect on the existing database.3. Restricting Unauthorized AccessA DBMS provides a security and authorization subsystem, which is used by DBA to create user accounts and to specify restrictions on user accounts. File processing system provides password mechanism and very less security which is not sufficient to enforce security policies like DBMS. 4. Providing Backup & RecoveryData should be restored to a consistent state at the time system crash and changes being made. If hardware or software fails in the middle of the update program, the recovery subsystem of DBMS ensures that update program is resumed at the point of failure.5. Multiple user interfacesDBMS provides a variety of user interfaces for the users of varying level of technical knowledge. These includes query language for casual users, programming language interfaces for application programmers, forms and command codes for parametric users, menu driven interfaces and natural language interfaces for stand alone users etc6. Enforcing Integrity ConstraintsThe DBMS have certain integrity constraints that hold on data. These constraints are derived from the meaning of the data and of the miniworld. Some constraints can be specified to the DBMS at the time of defining data definitions and automatically enforced. Database does not

Page 5: Sybullus of DBMS

allow violation of constraints at the time of updating the database.7. Data Redundancy and inconsistency control in file systemThe same data is to stored multiple times. This redundancy leads to several problem duplication of effort, wastages of storage space and inconsistency in data i.e. files that represent the same data show different value, this may happen because an update is applied to some of the files but not to others.8. Representing Complex Relationships among dataA DBMS must have the capability to represent a variety of complex relationship among the data, to define new relationships as they arise, and to retrieve and update the related data easily and efficiently.

Disadvantages of DBMSA database system generally provides on-line access to the database for many users. In contrast, a conventional system is often designed to meet a specific need and therefore generally provides access to only a small number of users. Because of the larger number of users accessing the data when a database is used, the enterprise may involve additional risks as compared to a conventional data processing system in the following areas.

Confidentiality, Privacy and Security When information is centralized and is made available to users from remote locations, the possibilities of abuse are often more than in a conventional data processing system. To reduce the chances of unauthorized users accessing sensitive information, it is necessary to take technical, administrative and, possibly, legal measures. Most databases store valuable information that must be protected against deliberate trespass and destruction. 

Data Quality Since the database is accessible to users remotely, adequate controls are needed to control users updating data and to control data quality. With increased number of users accessing data directly, there are enormous opportunities for users to damage the data. Unless there are suitable controls, the data quality may be compromised. 

Data Integrity Since a large number of users could be using a database concurrently, technical safeguards are necessary to ensure that the data remain correct during operation. The main threat to data integrity comes from several different users attempting to update the same data at the same time. The database therefore needs to be protected against inadvertent changes by the users. 

Enterprise Vulnerability 

Page 6: Sybullus of DBMS

Centralizing all data of an enterprise in one database may mean that the database becomes an indispensable resource. The survival of the enterprise may depend on reliable information being available from its database. The enterprise therefore becomes vulnerable to the destruction of the database or to unauthorized modification of the database.

Database DamageIn most of the organizations, all data is integrated into a single database. If database is damaged due to electric failure or database is corrupted on the storage media, then your valuable data may be lost forever.

Appointing Technical StaffThe trained technical persons such as database administrator, application programmers, data entry operators etc. Are required to handle the DBMS. You have to pay handsome salaries to these persons. Therefore, the" system cost increases.

Components of a DBMSDatabase EngineThe database engine is the heart of the DBMS. It is the core service for storing, processing, and securing data. The Database Engine provides controlled access and rapid transaction processing to meet the requirements of the most demanding data consuming applications within your enterprise. This includes creating tables for storing data, and database objects such as indexes, views, and stored procedures for viewing, managing, and securing data. 

Data dictionary:The data dictionary stores the definition of all of the data tables. A data dictionary is a reserved space within a database which is used to store information about the database itself. A data dictionary is a set of table and views which can only be read and never altered. Most data dictionaries contain different information about the data used in the enterprise.

In terms of the database representation of the data, the data table defines all schema objects including views, tables, clusters, indexes, sequences, synonyms, procedures, packages, functions, triggers and many more.

A data dictionary is used when finding information about users, objects, schema and storage structures. Every time a data definition language (DDL) statement is issued, the data dictionary becomes modified.

Query Processor:

Page 7: Sybullus of DBMS

Query processors a fundamental component of the DBMS. It enables developers and user to store and retrieve data. It manages records, controls concurrency, and maintains log files. The query processor accepts SQL syntax, selects a plan for executing the syntax, and then executes the chosen plan. The user or program interacts with the query processor, and the query processor in turn interacts with the storage engine. 

Form GeneratorA form generator helps the developer to create input forms. The forms are used for data entry it enables developers to build forms by dragging and dropping item on the screen.

Application GeneratorApplication Generation Subsystem contains facilities to help users to develop transaction-intensive applications. It usually requires that user perform a detailed series of tasks to process a transaction. It facilitates easy-to-use data entry screens, programming languages, and interfaces.An application is a collection of form and report design for a specific user task. A good DBMS contains an application generator which consists of tools that assist the developer in creating a complete application package.

Communication and Integration UtilitiesThese utilities are used to store and use data in several database running on different machines even if they are in different location.

Report writer:Most report writers allow you to select records that meet certain conditions and to display selected fields in rows and columns. You can also format data into pie charts, bar charts, and other diagrams. Once you have created a format for a report, you can save the format specifications in a file and continue reusing it for new data.

Also called a report generator, a program, usually part of a database management system that extracts information from one or more files and presents the information in a specified format.

Security & other utilitiesA primary goal of a database is store data with multiple users hence the DBMS must be responsible for establishing and maintaining security access controls. This unit is responsible for security issue. This describes now individuals or groups of users can be granted. Specific privileges and how their action can be restricted too specific areas of the database. The other utilities may include backup and recovery, user management, data storage evaluation, and performance monitoring tools.

Data Definition Subsystem helps user to create and maintain the data dictionary and define the

Page 8: Sybullus of DBMS

structure of the files in a database.

Data Administration Subsystem helps users to manage the overall database environment by providing facilities for backup and recovery, security management, query optimization, concurrency control, and change management.

Functions of a DBMSa. Data Storage, Retrieval, and Update.b. A User-Accessible Catalog.c. Transaction Support.d. Concurrency Control Services.e. Recovery Services.f. Authorization Services.g. Support for Data Communication.h. Integrity Services.i. Services to Promote Data Independence.j. Utility Services.

Classification of DBMS1. According to data model:-a. Relational Model:- The relational model uses a collection of tables to represent both data and the relationship among these data. Each table has multiple columns and each column has a unique name.b. ER Model(Entity Relationship):- The ER data model is based on a perception of a real world that consists of a collection of basic objects, called entities and of relationship among these object. An entity is a thing or objects in a real world that is distinguishable other object. It is a graphical view of entity and relationship. c. Object Oriented Model:-The object based model is an extension to the relation model to incorporate object database concept and concept of encapsulation, method and object identity.

2. Based on Number of user supported by the systema. Single User System:- Single User system supports only one users at a time and mostly used with personal computer.b. Multi-user system:- Multi-User system supports multi users concurrently. It is mostly used in network environment.3. According to the number of sites over which the database is distributeda. Centralized DBMS:-In centralized database system, the data is stored at a single computer. It support multiple users but the DBMS and the data base themselves reside totally at a single computer site.b. Distributed DBMS:- A distributed DBMS can have the actual database DBMS software

Page 9: Sybullus of DBMS

distributed over many sites, connected by computer network.4. According to the purposea. General Purpose DBMS:- These DBMS software are designed and built to use for general purpose. These can be used for management of data from any field and areas.b. Specific purpose DBMS:- When performance is primary consideration, a specific purpose DBMS can be designed and built for the specific application. Such system can not be used for other application without modification.Posted by Sujan Kunwar at 8:12 AM 1 commentsEmail This BlogThis! Share to Twitter Share to Facebook

2.Database DesignIdentifying User Requirements:-

One challenging aspect of designing a system is to determine the requirements. You must thoroughly understand the business needs before you can create a user files system. Excellent communication skill and experience are important to becoming a good designer.One of the most important tasks in designing a database application is to correctly identify the data that needs to store. The DBMS makes it easy to create and modify reports. The three basic information for the initial design: a. the data that needs to be collected. b. the data type (domain), and c. the amount of data involved. The initial goal is to identify the business entities or objects and describe how they are related to each other.

Logical data modeling:-A Logical Data Model (LDM) is a complete representation of data requirements and the structural business rules that govern data quality in support of project’s requirements. The LDM shows the specific entities, attributes and relationships involved in a business function and is the basis for the creation of the physical data model. Logical data models should be based on the structures identified in a preceding conceptual data model.The term 'Logical Data Model' is sometimes used as a synonym of 'Domain Model' or as an alternative to the domain model.

Why Build Logical Data Modela. Helps common understanding of business data elements and requirementsb. Provides foundation for designing a databasec. Facilitates avoidance of data redundancy and thus prevent data & business transaction inconsistencyd. Facilitates data re-use and sharinge. Decreases development and maintenance time and costf. Confirms a logical process model and helps impact analysis.

Logical Modeling Benefitsa. Clarifies functional specifications and avoids assumptionb. Confirms business requirementsc. Facilitates business process improvementd. Focuses on requirements independent of technologye. Decreases system development time and costf. Becomes a template for the enterpriseg. Facilitates data re-use and sharingh. Faster ROI

Page 10: Sybullus of DBMS

i. Gathers metadataj. Foster seamless communication between applicationsk. Focuses communication for data analysis and project team membersl. Establishes a consistent naming scheme

Logical Vs Physical Data ModelLogical Data Model Vs Physical Data ModelIncludes entities/tables, attributes/columns/fields and relationships Includes tables, columns, keys, data types, validation rules, database triggers, stored procedures, domains, and access constraintsUses business names for attributes Uses abbreviated column names limited by the database management system (DBMS)Is independent of technology (platform, DBMS) Includes primary keys and indices for fast data access.Is normalized to fourth normal form May be de-normalized to meet performance requirements based on the nature of the database. If the nature of the database is Online Transaction Processing (OLTP) or Operational Data Store (ODS) it is usually not de-normalized. De-normalization is common in Datawarehouses.

E-R diagram:-An entity-relationship diagram is a data modeling technique that creates a graphical representation of the entities, and the relationships between entities, within an information system.OrEntity-relationship(ER) diagram is a specialized graphic that illustrates the interrelationships between entities in a database. ER diagram often use symbols to represent three different types of information. Boxes are commonly used to rep[resent entities. Diamonds are normally used to represent relationship and ovals are used to represent attributes.Also known as: E-R diagram, Entity-relationship model ER diagram.Consider the example of a database that contains information on the residents of a city. The ER diagram shown in the image above contains two entities—people and cities. There is s single “Lives In” relationship. In our example, due to space constraints, there is only one attribute associated with each entity. People have names and cities have populations. In a real-world example, each one of these would likely have many different attributes.

Components of E-R diagramEntity:-The entity is a person, object, place or event for which data is collected. For example, if you consider the information system for a business, entities would include not only customers, but the customer's address, and orders as well.

Attributes:-Attributes are the parameter that describes entity types. For example, for entity student, attributes are roll no, Name, address, faculty, etc.

Relationship:-Relationship is the interaction between the entities. For example Teacher teaches students. Here ‘teacher’ is a relationship between two entity teacher and students.

Weak and strong entityWeak entity VS Strong entity

Page 11: Sybullus of DBMS

1. A weak entity set has no primary key unless attributes of the strong entity set on which it depends are included. 1. A strong entity set has a primary key. All tuples in the set are distinguishable by that key.

2. Weak entity is the one that does not exit own its own (depend on other entity). 2. Strong entity is the one that is independent

3. It does not have a unique identifier (only a partial identifier)3. It has own unique identifier

4. Partial identifier underlined with double-line 4. Identifier underlined with single-line

Atomic attributes Vs Complex attributes1.Simple, or atomic, attribute is one that cannot be decomposed into meaningful components. For example, an attribute for gender cannot be meaningfully decomposed into other attributes. Such an attribute will assume values such as Male or Female.1.A composite attribute is an attribute that is shown as comprising two or more simpler attributes.Consider an attribute such as empName that holds an employee’s first and last names. For example, suppose an employee’s name is John McKenzie. The first name is John and the last name is McKenzie.

2.A simple attribute cannot be subdivided. 2.A composite attribute is one that can be subdivided to yield additional attributes. For example, a phone number can be subdivided into area code, exchange, and number.

Discuss the difference between a composite key and a composite attribute.

A composite key is one that consists of more than one attribute. A composite attribute is one that can be subdivided to yield attributes for each of its components. If the E-R diagram contains the attribute names for each of its entities, a composite key is indicated in the E-R diagram by the fact that more than one attribute name is underlined to indicate its participation in the primary key.

What is a derived attribute? Give an example.

Database designers who concentrate on designs that display "design elegance" are very reluctant to store derived attributes in the database. Instead, they prefer that these derived attribute values are computed through appropriate algorithms when they are needed in a query. For example, a person's age may be calculated by using Julian dates to subtract the birth date from the current date and dividing the resulting number of days by 365.

Single Value attribute:-Single-valued attributes are shown with a simple oval, see below. In all of our examples so far, we have assumed that each attribute was single-valued.Consider employees for a typical business application where we need to store a value for gender. Each employee is either male or female, and so there is only one value to store per employee.

Page 12: Sybullus of DBMS

Attributes may also be single-valued or multivalued. As the name suggests, a single-valued attribute can have only one value. For example, a person can have only one gender and one birth date. Multivalued attributes can have many values: A person can have more than one college degree, and a household may have more than one phone.

What role does the E-R diagram play in the design process?

A completed E-R diagram is the actual blueprint of the database. Its composition must reflect an organization's operations accurately if the database is to meet that organization's data requirements. It forms the basis for a final check on whether the included entities are appropriate and sufficient, on the attributes found within those entities, and on the relationships between those entities. It is also used as a final crosscheck against the proposed data dictionary entries. The completed E-R diagram also lets the designer communicate more precisely with those who commissioned the database design.Finally, the completed E-R diagram serves as the implementation guide to those who create the actual database. In short, the E-R diagram is as important to the database designer as a blueprint is to the architect and builder.

What is a composite entity, and when is it used?A composite entity, also known as a bridge entity, is one that is used to transform M:N relationships into sets of 1:M relationships. The composite entity's primary key consists of the combination of primary keys from the entities it connects.

How are database models related to the level of data abstraction?

The higher the level of abstraction, the less need for the often difficult-to-understand physical details. The hierarchical and network database models make use of all three levels of abstraction. In contrast, the relational model primarily makes use of high and medium degrees of abstraction. In fact, the relational model generally allows its users to focus on the highest and, therefore, easiest to understand, level of abstraction. Given this focus, the relational implementation model lets us make better use of the conceptual data model. The conceptual model, being located at the abstraction apex, identifies and describes only the main data objects, avoiding the details. And it is this conceptual model that underlies the widely used E-R model whose use produces valuable database blueprints.

How is a composite entity represented in an E-R diagram, and what is its function?

In the Chen model, a composite entity, also known as a bridge entity, is represented through a diamond contained within a box. The diamond represents a relationship, while the box represents an entity. Thus the composite entity indicates that it translates a M:N relationship into two 1:M relationships through an entity. The label "bridge entity" is based on the fact that a composite entity serves as a connection between other entities.

The label "composite" is based on the fact that the composite entity contains at least the primary key attributes of each of the entities that are connected by it. The composite entity is an important component of the E-R model because relational database models should not contain M:N relationships.

Page 13: Sybullus of DBMS

Class Diagram:-A class diagram is an illustration of the relationships and source code dependencies among classes in the Unified Modeling Language (UML). In this context, a class defines the methods and variables in an object. Class diagrams are useful in all forms of object-oriented programming (OOP). In a class diagram, the classes are arranged in groups that share common characteristics. The top rectangle contains the name of the class; the middle rectangle contains the attributes of the class; the lower rectangle contains the methods, also called operations, of the class. Lines, which may have arrows at one or both ends, connect the boxes. These lines define the relationships, also called associations, between the classes.

MemberUML provides mechanisms to represent class members, such as attributes and methods, and additional information about them.

VisibilityTo specify the visibility of a class member (i.e., any attribute or method) there are the following notations that must be placed before the member's name.+public:- visible to all elements that can access the contents of the namespace that owns it.

#protected:-visible to elements that have a generalization relationship to the namespace that owns it.

–Private”-only visible inside the namespace that owns it.

~package:- owned by a namespace that is not a package, and is visible to elements that are in the same package as its owning namespace. Only named elements that are not owned by packages can be marked as having package visibility. Any element marked as having package visibility is visible to all elements within the nearest enclosing package (given that other owning elements have proper visibility). Outside the nearest enclosing package, an element marked as having package visibility is not visible.

ScopeThe UML specifies two types of scope for members: instance and classifier. In the case of instance members, the scope is a specific instance. For attributes, it means that its value can vary between instances. For methods, it means that its invocation affects the instance state, in other words, affects the instance attributes. Otherwise, in the classifier member, the scope is the class. For attributes, it means that its value is equal for all instances. For methods, it means that its invocation do not affect the instance state. Classifier members are commonly recognized as "static" in many programming languages. To indicate that a member has the classifier scope, its name must be underlined. Otherwise, as default, the instance scope is considered.Posted by Sujan Kunwar at 8:09 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

3.Data Normalization3.NormalizationIntroduction:-Database normalization is a technique for designing relational database tables to minimize duplication of information and, in so doing, to safeguard the database against certain types of logical or structural problems, namely data anomalies. Normalization is a process of remove the redundancy and inconsistency

Page 14: Sybullus of DBMS

Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored. 

The Normal FormsThe database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen and won't be discussed in this article. 

Before we begin our discussion of the normal forms, it's important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it's extremely important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let's explore the normal forms. 

The purposes of normalization are to:• Reduce or eliminate storage of duplicate data • Organize data into an efficient and logical structureThe need of normalizationNormalization is needed in data modeling of any system because it helps to remove the following anomalies:• Insert• Delete• UpdateCase of a Construction Companya.Building project -- Project number, Name, Employees assigned to the project.b.Employee -- Employee number, Name, Job classificationc.Periodically, a report is generated.

First Normal Forms:- First Normal Form that deals atomicity.The term first normal form (1NF) describes the tabular format in which:a.All the key attributes are defined.b.There are no repeating groups in the table. c.All attributes are dependent on the primary key.orFirst Normal Form (1NF)First normal form (1NF) sets the very basic rules for an organized database: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). 

Second Normal Forms:- Second Normal Form that deal function dependence. 

Page 15: Sybullus of DBMS

It is in 1NF andIt includes no partial dependencies; that is, no attribute is dependent on only a portion of the primary key.(It is still possible for a table in 2NF to exhibit transitive dependency; that is, one or more attributes may be functionally dependent on nonkey attributes.)orSecond Normal Form (2NF)Second normal form (2NF) further addresses the concept of removing duplicative data: Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys. Meet all the requirements of the first normal form. 

Third Normal Forms:-Third Normal Form that deals Transitive dependence.A table is in 3NF if:a.It is in 2NF andb.It contains no transitive dependencies.orThird Normal Form (3NF)Third normal form (3NF) goes one large step further: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key.

BCNF()A table is in BCNF if every determinant in that table is a candidate key. If a table contains only one candidate key, 3NF and BCNF are equivalent.

How does data integrity differ with data security? Data integrity refers to the consistency and accuracy of the data stored in a database. Data security has to do with ensuring the data is safe.D ata integrity = making sure the data is correct and not corruptData security = making sure only the people who should have access to the data are the only ones who can access the data. also, keeping straight who can read the data and who can write data.

Define the types of constraints in RDBMS with suitable example.An integrity constraint is a rule that restricts the values that may be present in the database. Integrity constraints allow only correct changes to be made to a database. There are two types of integrity constraints - entity integrity and referential integrity.

Entity Integrity: Entity Integrity ensures that for each row in a table, the value of the primary key is unique and is not null.Referential Integrity : Referential Integrity ensures that for each row in a table, the value of the foreign key is present in the reference table.Referential integrity consists of:• Not inserting a record if the value of the foreign key being inserted does not match an existing record in another table with the primary key having the same value,• Not deleting a record whose primary key is defined as a foreign key in child records and• Not modifying the value of primary keys.

Page 16: Sybullus of DBMS

User-Defined IntegrityUser-defined integrity refers to specific business rules not covered by the other integrity categories. It is typically implemented through triggers and stored procedures.

Types of constraints in RDBMSa.Domain Constraints:Domain constraints specify that the value of each attribute must be atomic value and each data must have same data format.

b.Key Constraints:-No two tuples can have the same combination of values for all their attributes.

c.NOT NULL Constraints:-This constraint prohibit the insertion of a NULL value for this attributes.

d.UNIQUE Constraints:The value of attributes for each tuples must be unique. It may permit NULL value.

e.Primary Key Constraints:It ensure that certain attributes or set of attributes must have unique value and also it cannot permits null value.

f.CHECK Constraints:If ensure that each value of attributes must satisfy the given condition balance decimal(7,2) CHECK(balance >2000)

g.Foreign key Constraints:Foreign key always points to primary key of same or other relation. It ensure that foreign key always points to void primary key. i.e. Value of foreign key must be in primary key.

Domain ConstraintsDomain constraints are a user-defined data type which enforces the integrity of the standard data types. A domain consists of all values permitted in a column. In constructing your database you would first select a standard data type such as VARCHAR or INT. You could then constrain or limit the data using NOT NULL, UNIQUE, CHECK, PRIMARY KEY or FOREIGN KEY. For example the CHECK constraint could limit INT data within your domain [column] to numbers less than 5000. You would thus define a custom data type using domain constraints.

Data DictionaryCREAT TABLE{:

Page 17: Sybullus of DBMS

:}

Data dictionary store data that describes the data stored in the database. Such data is also known as metadata (Data of data). It typically list all tables, column, data domain, constraint and assu,ption. The data dictionary store following informationa. Name of the relation.b. Name of attribute of each relationc. Domain & length of attributesd. Integrity constant.e. Name of authorized user.f. Authorized & accounting information.Posted by Sujan Kunwar at 8:04 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

4.Introduction TO SQL-Simple QueriesSQL:-SQL often referred to as Structured Query Language, is a database computer language designed for managing data in relational database management systems (RDBMS), and originally based upon relational algebra. Its scope includes data query and update, schema creation and modification, and data access control. SQL was one of the first languages for Edgar F. Codd's relational model in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks" and became the most widely used language for relational databases.

Basic structure of an SQL queryGeneral StructureSELECT ...... FROM ...... WHERE ......SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;FROM tablename WHERE conditiona.The query will select rows from the source tablename and output the result in table form.b.Expressions expr1, expr2 can be : • a column, or • an expression of functions and fields.c. And col1, col2 are their corresponding column names in the output table.

List all the student records.SELECT * FROM student

List the names and house code of 1A students.SELECT name, hcode, class FROM student ;WHERE class="1A"

List the residential district of the Red House members.SELECT DISTINCT dcode FROM student ;WHERE hcode="R"

List the names and ages (1 d.p.) of 1B girls.SELECT name, ROUND((DATE( )-dob)/365,1) AS age ;FROM student WHERE class="1B" AND sex="F"

List the names, id of 1A students with no fee remission.

Page 18: Sybullus of DBMS

SELECT name, id, class FROM student ; WHERE class="1A" AND NOT remission

GroupingSELECT ...... FROM ...... WHERE condition ;GROUP BY groupexpr [HAVING requirement]Group functions:COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )-groupexpr specifies the related rows to be grouped as one entry. Usually it is a column.-WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group.List the number of students of each class.SELECT class, COUNT(*) FROM student ;GROUP BY class

List the average Math test score of each class.SELECT class, AVG(mtest) FROM student ;GROUP BY class

List the number of girls of each district.SELECT dcode, COUNT(*) FROM student ;WHERE sex="F" GROUP BY dcode

List the max. and min. test score of Form 1 students of each district.SELECT MAX(mtest), MIN(mtest), dcode ;FROM student ; WHERE class LIKE "1_" GROUP BY dcode

List the average Math test score of the boys in each class. The list should not contain class with less than 3 boys.SELECT AVG(mtest), class FROM student ;WHERE sex="M" GROUP BY class ;HAVING COUNT(*) >= 3

Display OrderSELECT .... FROM ... WHERE .... GROUP BY ..... ;ORDER BY colname ASC / DESCList the boys of class 1A, order by their names.SELECT name, id FROM student; WHERE sex="M" AND class="1A" ORDER BY nameList the 2A students by their residential districtSELECT name, id, class, dcode FROM student ;WHERE class="2A" ORDER BY dcode

List the number of students of each district (in desc. order).SELECT COUNT(*) AS cnt, dcode FROM student ; GROUP BY dcode ORDER BY cnt DESC

List the boys of each house order by the classes. (2-level ordering)SELECT name, class, hcode FROM student ;WHERE sex="M" ORDER BY hcode, class

OutputList the students in desc. order of their names and save the result as a database file name.dbf.SELECT * FROM student ;ORDER BY name DESC INTO TABLE name.dbf

Print the Red House members by their classes, sex and name.SELECT class, name, sex FROM student ;WHERE hcode="R" ; ORDER BY class, sex DESC, name TO PRINTER

Union, Intersection and Difference of Tables

Page 19: Sybullus of DBMS

The two clubs want to hold a joint party. Make a list of all students. (Union)SELECT * FROM bridge ; UNION ;SELECT * FROM chess ;ORDER BY class, name INTO TABLE party

Print a list of students who are members of both clubs. (Intersection)SELECT * FROM bridge ;WHERE id IN ( SELECT id FROM chess ) ; TO PRINTER

Make a list of students who are members of the Bridge Club but not Chess Club. (Difference)SELECT * FROM bridge ;WHERE id NOT IN ( SELECT id FROM chess ) ;INTO TABLE diff

SQL Aggregate Functions What are SQL Aggregate Functions?The SQL Aggregate Functions are functions that provide mathematical operations. The functions include: 

count() - counts a number of rows sum() - compute sum avg() - compute average min() - compute minimum max() - compute maximum 

Why Use SQL Aggregate Functions?The SQL Aggregate Functions are useful when mathematical operations must be performed on all or a grouping of values. 

How To Use SQL Aggregate FunctionsSQL Aggregate Functions are used as follows. If a grouping of values is needed also include the GROUP BY clause. 

Use a column name or expression as the parameter to the Aggregate Function. The parameter, '*', represents all rows. 

SQL Aggregate Functions Syntax 

SELECT , FROM GROUP BY , 

SQL Aggregate Functions Example 

The following example Aggregate Functions are applied to the employee_count of the branch table. The region_nbr is the level of grouping. 

Here are the contents of the table: 

Table: BRANCHbranch_nbr branch_name region_nbr employee_count 

Page 20: Sybullus of DBMS

108 New York 100 10 110 Boston 100 6 212 Chicago 200 5 404 San Diego 400 6 415 San Jose 400 3 

This SQL Statement with aggregate functions is executed: 

SELECT region_nbr, count(branch_nbr), sum(employee_count), min(employee_count), max(employee_count), avg(employee_count)FROM dbo.branchGROUP BY region_nbrORDER BY region_nbr

Here is the result. 

region_nbr count(branch_nbr) sum (employee_count) min(employee_count) max(employee_count) avg(employee_count) 100 2 16 6 10 8 200 1 5 5 5 5 400 2 9 3 6 4 

Comparisonexpr IN ( value1, value2, value3)expr BETWEEN value1 AND value2expr LIKE "%_"List the students who were born on Wednesday or Saturdays.SELECT name, class, CDOW(dob) AS bdate ;FROM student ;WHERE DOW(dob) IN(4,7)

List the students who were not born in January, March, June, September.SELECT name, class, dob FROM student ;WHERE MONTH(dob) NOT IN (1,3,6,9)

List the 1A students whose Math test score is between 80 and 90 (incl.)SELECT name, mtest FROM student ;WHERE class="1A" AND ;mtest BETWEEN 80 AND 90

List the students whose names start with "T".SELECT name, class FROM student ;WHERE name LIKE "T%"

List the Red house members whose names contain "a" as the 2nd letter.SELECT name, class, hcode FROM student ;WHERE name LIKE "_a%" AND hcode="R"Posted by Sujan Kunwar at 8:01 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

Page 21: Sybullus of DBMS

5.Advances QueriesSQL(Structured Query Language)This is a common language through which we can interact with the database.SQL is classified mainly into three categories.1.DDL(Data Definition Language)1. Create 2. Alter 3. Truncate 4. Drop2. DML(Data Manipulation Language).1. Select 2. Insert 3. Update 4. Delete3. TCL(Transaction Control Language).1. Commit 2.Rollback 3. Save point4. DCL(Data Control Language)

DDL CommandThe Data Definition Language (DDL) is used to create and destroy databases and database objects. These commands will primarily be used by database administrators during the setup and removal phases of a database project. Let's take a look at the structure and usage of four basic DDL commands:

Create:This command is used to create database object such as –Tables, Views, Indexes, synonyms, sequences, stored procedures, Triggers, Functions, Packages and User-define data types.Example:-CREATE TABLE Employee(empno number(4) constraint pk_empno primary key,ename varchar2(50) constraint nn_ename not null,salary number(10,2),hire_date data,gender char(1) constraint chk_gen check(gender in ('M', 'F', 'm', 'f')),email varchar2(50) unique);

Alter:This command is used to modify the structure of the database object.Example:- ALTER TABLE Employee ADD CONSTRAINT nn_hdata NOT NULL hire_date;

Drop:This command is used to remove the objects from the database.Example:- DROP TABLE Employee;Truncate:Using this command we can permanently remove the rows from a table. Here we cannot append any clauses the truncate statement.Example:-TRUNCATE TABLE Employee;

DML CommandThe Data Manipulation Language (DML) is used to retrieve, insert and modify database information. These commands will be used by all database users during the routine operation of the database. Let's take a brief look

Page 22: Sybullus of DBMS

at the basic DML commands:

SELECTIt allows database users to retrieve the specific information they desire from an operational database.ExampleSELECT *FROM Employee

INSERTUsing this command we can append data into tables.ExampleINSERT INTO Employee(empno,ename,salary,hire_date,gender,e-mail)VALUES(1234, 'JOHN', '8000', '18-AUG-80', 'M', '[email protected]');

UPDATEThe UPDATE command can be used to modify information contained within a table, either in bulk or individually.Example:- UPDATE Employee SET salary=1500;UPDATE Employee SET salary=1500 WHERE empno=1235;

DELETEThis command is used to remove the data form the tables.Example:-DELETE FROM Employee;DELETE FROM Employee WHWRE empno =1236

Join Operation :-The join operation defined for relational databases is often referred to as a natural join. In this type of join, two relations are connected by their common attributes. A SQL JOIN clause combines records from two or more tables in a database.[1] It creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by using values common to each. ANSI standard SQL specifies four types of JOINs: INNER, OUTER, LEFT, and RIGHT.

Inner join:-An inner join is the most common join operation used in applications, and represents the default join-type. Inner join creates a new result table by combining column values of two tables (A and B) based upon the join-predicate. The result of the join can be defined as the outcome of first taking the Cartesian product (or cross-join) of all records in the tables (combining every record in table A with every record in table B) - then return all records which satisfy the join predicate.Example SQL statementSELECT *FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID

Page 23: Sybullus of DBMS

Equi-join:-An equi-join, also known as an equijoin, is a specific type of comparator-based join, or theta join, that uses only equality comparisons in the join-predicate. Using other comparison operators (such as <) disqualifies a join as an equi-join. The query shown above has already provided an example of an equi-join: SELECT *FROM employee INNER JOIN department ON employee.DepartmentID = department.DepartmentID 

Natural join:- A natural join offers a further specialization of equi-joins. The join predicate arises implicitly by comparing all columns in both tables that have the same column-name in the joined tables. The resulting joined table contains only one column for each pair of equally-named columns. The above sample query for inner joins can be expressed as a natural join in the following way:- SELECT *FROM employee NATURAL JOIN department 

Cross join:- A cross join, cartesian join or product provides the foundation upon which all types of inner joins operate. A cross join returns the cartesian product of the sets of records from the two joined tables. Thus, it equates to an inner join where the join-condition always evaluates to True or where the join-condition is absent from the statement. In other words, a cross join combines every row in B with every row in A. The number of rows in the result set will be the number of rows in A times the number of rows in B.Thus, if A and B are two sets, then the cross join is written as A × B. The SQL code for a cross join lists the tables for joining (FROM), but does not include any filtering join-predicate. Example of an explicit cross join: SELECT * FROM employee CROSS JOIN department Example of an implicit cross join: SELECT *FROM employee, department; 

Outer join:- An outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer joins, depending on which table(s) one retains the rows from (left, right, or both). No implicit join-notation for outer joins exists in standard SQL. Left outer join:- The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the left table returns one row and the right table returns more than one matching row for it, the values in the left table will be repeated for each distinct row on the right table. For example, this allows us to find an employee's department, but still shows the employee(s)

Page 24: Sybullus of DBMS

even when they have not been assigned to a department (contrary to the inner-join example above, where unassigned employees are excluded from the result). Example of a left outer join, with the additional result row italicized: SELECT * FROM employee LEFT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID Right outer joins A right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for those records that have no match in B. A right outer join returns all the values from the right table and matched values from the left table (NULL in case of no matching join predicate). For example, this allows us to find each employee and his or her department, but still show departments that have no employees. Example right outer join, with the additional result row italicized: SELECT * FROM employee RIGHT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID 

Full outer join A full outer join combines the results of both left and right outer joins. The joined table will contain all records from both tables, and fill in NULLs for missing matches on either side. For example, this allows us to see each employee who is in a department and each department that has an employee, but also see each employee who is not part of a department and each department which doesn't have an employee. Example full outer join: SELECT * FROM employee FULL OUTER JOIN department ON employee.DepartmentID = department.DepartmentID UNION SELECT *FROM employee RIGHT JOIN department ON employee.DepartmentID = department.DepartmentID WHERE employee.DepartmentID IS NULL SQLite does not support right join, so outer join can be emulated as follows: SELECT employee.*, department.*FROM employee LEFT JOIN department ON employee.DepartmentID = department.DepartmentID UNION ALL SELECT employee.*, department.* FROM department LEFT JOIN employee ON employee.DepartmentID = department.DepartmentID WHERE employee.DepartmentID IS NULL Self-join A self-join is joining a table to itself.This is best illustrated by the following example. Example A query to find all pairings of two employees in the same country is desired. If you had two separate tables for employees and a query which requested employees in the first table having the same country as employees in the second table, you could use a normal join operation to find the answer table. However, all the employee information is contained within a single large table An example solution query could be as follows: SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country FROM Employee F, Employee S WHERE F.Country = S.Country AND F.EmployeeID < S.EmployeeID ORDER BY F.EmployeeID, S.EmployeeID; Relational operations The union operator combines the tuples of two relations and removes all duplicate tuples from the result. The relational union operator is equivalent to the SQL UNION operator. The intersection operator produces the set of tuples that two relations share in common. Intersection is implemented in SQL in the form of the INTERSECT operator. The difference operator acts on two relations and produces the set of tuples from the first relation that do not exist in the second relation. Difference is implemented in SQL in the form of the EXCEPT or MINUS operator. The cartesian product of two relations is a join that is not restricted by any criteria, resulting in every tuples of the first relation being matched with every tuple of the second relation. The cartesian product is implemented in SQL as the CROSS JOIN join operator. 

GROUP BY Clause :-The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group

Page 25: Sybullus of DBMS

the results by one or more columns.The syntax for the GROUP BY clause is:SELECT column1, column2, ... column_n, aggregate_function (expression) FROM tables WHERE predicatesGROUP BY column1, column2, ... column_n;aggregate_function can be a function such as SUM, COUNT, MIN, or MAX.Example using the SUM functionFor example, you could also use the SUM function to return the name of the department and the total sales (in the associated department).SELECT department, SUM(sales) as "Total sales"FROM order_details

GROUP BY department;Because you have listed one column in your SELECT statement that is not encapsulated in the SUM function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Example using the COUNT functionFor example, you could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year.SELECT department, COUNT(*) as "Number of employees"FROM employeesWHERE salary > 25000GROUP BY department;Example using the MIN functionFor example, you could also use the MIN function to return the name of each department and the minimum salary in the department.SELECT department, MIN(salary) as "Lowest salary"FROM employeesGROUP BY department;Example using the MAX functionFor example, you could also use the MAX function to return the name of each department and the maximum salary in the department.SELECT department, MAX(salary) as "Highest salary"FROM employeesGROUP BY department;

HAVING Clause:-The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT statement to filter the records that a GROUP BY returns.The syntax for the HAVING clause is:SELECT column1, column2, ... column_n, aggregate_function (expression)FROM tablesWHERE predicatesGROUP BY column1, column2, ... column_nHAVING condition1 ... condition_n; aggregate_function can be a function such as SUM, COUNT, MIN, or MAX.Example using the SUM functionFor example, you could also use the SUM function to return the name of the department and the total sales (in

Page 26: Sybullus of DBMS

the associated department). The HAVING clause will filter the results so that only departments with sales greater than $1000 will be returned.

SELECT department, SUM(sales) as "Total sales"FROM order_detailsGROUP BY departmentHAVING SUM(sales) > 1000;

Example using the COUNT functionFor example, you could use the COUNT function to return the name of the department and the number of employees (in the associated department) that make over $25,000 / year. The HAVING clause will filter the results so that only departments with more than 10 employees will be returned.

SELECT department, COUNT(*) as "Number of employees"FROM employeesWHERE salary > 25000GROUP BY departmentHAVING COUNT(*) > 10;

Example using the MIN functionFor example, you could also use the MIN function to return the name of each department and the minimum salary in the department. The HAVING clause will return only those departments where the starting salary is $35,000.

SELECT department, MIN(salary) as "Lowest salary"FROM employeesGROUP BY departmentHAVING MIN(salary) = 35000;

Example using the MAX functionFor example, you could also use the MAX function to return the name of each department and the maximum salary in the department. The HAVING clause will return only those departments whose maximum salary is less than $50,000.SELECT department, MAX(salary) as "Highest salary"FROM employeesGROUP BY departmentHAVING MAX(salary) < 50000;Posted by Sujan Kunwar at 7:06 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

6.Forms and ReportsIntroduction to Form and Report:-Forms and reports are an important part of the database application. Designer use them to create an integrated application, making it easier for user to perform their task. Decision maker and clerical workers use from and report on a daily basis. Normally forms were used as input and report were used to display result. Now a day forms are also used to display result, Basic use of forms are:o Collect data

Page 27: Sybullus of DBMS

o Display query datao Display analysis and computation resulto Switch boardo Direct manipulation of object like Graphics Report are typically printed on paper, but they are increasingly begin created for direct display on the screen. Report can be used to format the data and present results from complex analysis. Forms and reports have several common features.

Effective Design of forms and ReportThe most important concept to remember when designing forms and reports is to understand that they are the primary concert of the user. The key of effective design is to determine the needs of the user. As a designer, you talk with to learn what they want to accomplish. Then you use your experience to provide features that make the form more useful. Researchers in human factors have developed several guidelines to help you design forms. Some factors are:a. User Control: match user task, Respond to user control and event User customization.b. Consistency: Layout, design, and color, action.c. Feedback: Method( Visual, text, Audio, Graphics)d. Forgiveness: Correction of errors, Confirmation on delete and updates.

Form Layout:-Individual forms or windows are your primary means of communication with people who use your application. Forms are used to collect data, display results and organize the overall system. Several standard layouts are provided by the DBMS to simplify the development of many common forms. Normally we will be working with four basic types of form.

a. Tabular Forms:-One of the simplest forms is the tabular forms, which displays the columns and rows from a table or query. It can be used as a sub form and is rarely used as a stand-alone form. Microsoft Access provides an even simpler version of form called a datasheet.

b. Single-Row or Columnar Forms:-A single-row form displays data for one row at a time. The goal is to display every column. Its greatest feature is that the designer can display the data at any location on the form. It is useful for designing a form like a traditional paper form.

c. Subform Forms:-A subform is usually a datasheet (or tabular form) embedded on the main form. A subform generally shows a one-to-many relationship.

d. Switchboard:-It provides overall structure of an application. It directs the user to other form & report in the application. It often contains image and reflect the style of the company.

Page 28: Sybullus of DBMS

ReportSeveral issue are involve in designing report as in the development of form, you and users need to determine the content and layout of reports. Issues in designing report are:a. Report usage and user need.b. Report layout choice like tabular, subgroup, chart, etc.c. Paper sized. How often it is generated.e. Even that triggers report.f. How large is the report.g. Colorsh. Security control, etc.

Types of Reporta.Tabular and level reportIt is basically means printing column of data like output of query in tabular reports, data are presented in tabular forms .Example grade sheets of all students.

b.Group and subtotal ReportThe most common types of report is based on groups and compute, subtotals common example may be printing receipt or a bills.

c.GraphsGraphs on reports are similar to graphs on forms. Graphs gives comparison of different record. Example of graph may be pi-chart, bar-chart, etc.Posted by Sujan Kunwar at 6:44 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

7.Data Manipulation7. Data ManipulationIntroduction:-The SQL language is powerful and can be used to solve complex problems. However, it cannot solve every problem. There are times when you need to use a procedural language. For example, some computations may required several steps. In particular, decisions involving complex conditions can be easier to evaluate with a procedural language than with a SQL.Similarly, complex transactions might require updating several tables, so you use a procedural language to sequence the changes in the proper order. You will often have to create modules to interact with users or to respond to user requests. Few standards are defined for using procedural languages within a database environment. The primary environment is Microsoft Access Visual Basic for Application (VBA), which has some powerful (and complex) capabilities for user interaction in the Windows environment.

Computer tools:-Dealing with totals and subtotals is a challenging problem in database application design. Consider the basic sales from example, where a subform displays purchases of individual items. The main advantage to storing totals is that it is faster to retrieve them later, and the queries are easier to write. If you do not store the totals, then your queries have to computer the value every time you need them. These calculations

Page 29: Sybullus of DBMS

are slower than retrieving the totals because the process entails retrieving all of the underlying details rows, instead of just one total line. The main drawback to storing calculated values is that the totals might become inconsistent.To be safe, for all stored totals, you need to include a separate program that goes back to the underlying transaction details and computers the correct totals. Many of these calculations required the use of procedural languages, or chains of SQL statements.

Procedural language:- Procedural language is the generic term for a traditional programming language such as BASIC, COBOL, C++, or Java that evaluates commands in sequential order and contains certain basic logic elements. To write programs, you need to learn the basic operations listed in below:-• Variables• Computations• Standard functions• Debug• Output• Input• Conditions• Loops• ArraysProgramming ultimately reduces to two components: logic and syntax. Programming logic represents the structure of the program and the use of the programming elements to solve the underlying problem.Syntax represents the specific commands and features in a programming language.

Programming environment:-Even beyond basic structure and syntax, DBMS vendors have several choices about how to create a programming language. Perhaps the biggest choice is exactly where the language will be used. Three common methods is used:1. within the database forms and reports.2. within the query system as an extension to SQL3. hosted within separate programs outside the DBMS(Embedded SQL)The location or environment, of the language affects what it can do, how it is used and what you will have to learn. For example, to embed SQL within an external program, if you already known the host language (e.g., C++ or COBOL), you only have to learn how to transfer data between SQL and the host language. On the other hand, languages inside the DBMS have their own logic and syntax, so you have to learn an entirely new system.

Windows Environment:- The windows interface has significantly changed way programs operate. In the “old days”, each program had its own style. The programmer had to design every aspect of the user interface. Also, the program was in control form the start of the session to the end. The user and the operating system (Windows) have control of the computer. As a developer, you write procedures that are called by the user or the operating system to perform a specific task. When the task is accomplished, control is returned to the operating system. As the user performs some task, the event triggers your code to run. A key aspect of developing system is to identify which of the many events should trigger your code. In many systems (e.g., Oracle and SQL Server), triggers can also be define directly on the data tables. 

Data on Forms:-When you need a user to enter data, you will create a form. Forms are also used to display data and results of

Page 30: Sybullus of DBMS

computations. Each control on the form represents a type of data associated with that form.You can also create unbound controls that will hold and display data on a form temporarily. When the form closed, the unbound data disappears. You can use unbound controls when you want users to enter raw data. Then your procedure performs computations on the data and stores it in the database.

Using programs to save and retrieve data in the data base:-Once you can understand the basic operation of cursors, it is straightforward to retrieve or change the data. Just remember that you change data on row at a time. In Microsoft Access you essentially treat the columns as variables. For example, to obtain the value in the BalanceDue column of the current row, you would use rst(“BalanceDue”).The advantages of the programming arise when the calculations are more complex. In particular, the code within the loop might have several conditions (If/Then/Else) and use data that was entered on the form.

Handling error:- There are many sources of errors like mistake in code, faulty data entered by users, hardware or network failures, operating system glitches, and so on. You need to create your programs so that they can deal with errors. If you do not, the program might crash and the user will be left with a blank screen and lost data.The two primary philosophies exit for handling errors:-a. Check whether every major operation is performed correctly.

b. Write a special error-handling routine that is called only when any error arise.

Eg:-On Erroe Go to ErrSub1Program code::ErrSub:Program to handle errorPosted by Sujan Kunwar at 6:43 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

8.Application DevelopmentWhy Application?Ans:Applications are complete systems that perform specific tasks. The task is defined by the user. For example, you could develop an application to track the location and status of shipping containers.The goal of an application is to provide information and help users make decisions. To achieve this goal, the application should be easy to use. Applications serve two primary functions:1. They established and control the user interface2. They ensure data integrity.Additionally, applications can be used to build decision support systems and expert systems and expert systems. Each application needs a different combination of these features. As a designer, you need to be aware of the choices and use them to improve your applications.

Application Structure:-The overall structure is an important feature of any application. The structure or layout define how the user will

Page 31: Sybullus of DBMS

deal with the application. Most data base applications will use forms and reports as individual components. The first step in designing the structure of the application is to design each form.The objective of application structure is to organize all of the forms and reports to produce a complete application. It is common to separate a database application into two or three major sections. Sometimes a middle tire is added that consists of program code top define and enforce business rules.

User interface featuresModern windows based applications have several user interface feature that are designed to standardize the look and feel of applications and to make your applications relatively.Three features are particularly important: Menus, toolbars, help system.

Menus:-The menu is simply a list of choices that perform some action when selected by the user. Most menus are hierarchical. The windows interface standard specifies that menus should be displayed at the top of the application.

Toolbar:-A toolbar generally contains a collection of buttons and menu items. When the user click a toolbar button, a predefined operation. A toolbar can contain traditional buttons, and it can contain texture menus. Most toolbars are dockable, when means that users ca drag them to any place on the application windows.

Helps system:-The goal of this system is to provide the background information and the specific instructions that a user might need to effectively use the application system. Help files can contains text-based descriptions, figures and hypertext links to related topics. The user should be presented with information that is designed to help with the specific task they are working on at the time.

Transactions:-A transaction is defined as a set of changes that must all be made together. Consider the example; you are working on a system for a bank. A customer goes to the ATM and instructs it to transfer $1,000 from savings to a checking account. This simple transaction required two steps: (1) subtracting the money from the savings account balance and (2) adding the money to the checking account balance. The code to create this transaction will required two updates to the database. For example, there will be two SQL statements: one UPDATE command to decrease the balance in savings and a second UPDATE command to increase the balance in the checking account. If both IPDATE performed successful then transaction is ‘COMMIT’ otherwise ‘ROLLBACK’.

Forms to help userYou can do several things to make your forms easier to use. The key is to understand the business operations and how the forms will be used. For example, you can control combo boxes with the WHERE clause and the NotInList event. You can reduce user keystrokes by user keystrokes by using mouse clicks and double clicks to automatically enter data and perform advanced lookups. Additionally, you can add decisions support features

Page 32: Sybullus of DBMS

such as statistical analysis, optimization, and simulation. By adding more logic and control to your code, you can add expert system features that automatically computer or estimate key values.

Custom reportsReport writers are good at formatting data for common reports. Some report writers are powerful enough to handle complex reports. Some times you might encounter reports that are difficult to create with a report writer. Sometimes you want to conditional formatting, where the output changes based on the data. So, we should use a report writer to display the final report. Creating reports with the programming is time-consuming.The fist step is to create a query that provides the data on the report. Then you can write a program that start at top of the query and examines each row. Your code becomes more complex if you want to keep all elements within a group on one page. Then you have to do termine the size of the group before it is printed.You code must identify the breaks for each group. You should also keep track of the number of lines so that you can identity the end of the page.Posted by Sujan Kunwar at 6:41 AM 0 commentsEmail This BlogThis! Share to Twitter Share to Facebook

9.Database AdministrationDatabase administration:-Database administration is a complex, often thankless chore. The collection of links on this page will help you keep your DBMS humming along at peak performance. It consists of technical aspect creating and running the database. The basic task is performance monitoring, backup and recovery and assigning and controlling security. Database administrations are trained in detail to installing, configuring and operating the DBMS.

Database administrator (DBA)A DBA is a complex software package. Installing, running and upgrading a DBMS are not trivial task. Even with personal computer based system, this task can be required the service of fulltime person. Every data requires the service of a DBA which position is generally staff who is trained in the administration of the particular DBMS.OrA database administrator (DBA) directs or performs all activities related to maintaining a successful database environment. Responsibilities include designing, implementing, and maintaining the database system; establishing policies and procedures pertaining to the management, security, maintenance, and use of the database management system; and training employees in database management and use. A DBA is usually expected to have experience with one or more of the major database management products, such as Structured Query Language, SAP, and Oracle-based database management software.

DBA tasko Install & upgrade DBMSo Create user account and monitor securityo Manage backup and recovery of the databaseo Monitor and the tune the database performance o Co-ordinate with DBMS vender and plan for changeso Maintains DBMS- specific information’s for developer

General tasks 

Page 33: Sybullus of DBMS

Installation, configuration, upgrade, and migrationAlthough system administrators are generally responsible for the hardware and operating system on a given server, installation of the database software is typically up to the DBA. This job role requires knowledge of the hardware prerequisites for an efficient database server, and communicating those requirements to the system administrator. 

Backup and recoveryDBAs are responsible for developing, implementing, and periodically testing a backup and recovery plan for the databases they manage. Even in large shops where a separate system administrator performs server backups, the DBA has final responsibility for making sure that the backups are being done as scheduled and that they include all the files needed to make database recovery possible after a failure. When failures do occur, the DBA needs to know how to use the backups to return the database to operational status as quickly as possible, without losing any transactions that were committed. There are several ways the database can fail, and the DBA must have a strategy to recover from each. From a business standpoint, there is a cost to doing backups, and the DBA makes management aware of the cost/risk trade-offs of various backup methods.

Database securityBecause databases centralize the storage of data, they are attractive targets for hackers and even curious employees. The DBA must understand the particular security model that the database product uses and how to use it effectively to control access to the data. The three basic security tasks are authentication (setting up user accounts to control log-ins to the database), authorization (setting permissions on various parts of the database), and auditing (tracking who did what with the database). The auditing task is particularly important currently, as regulatory laws like Sarbanes-Oxley and HIPAA have reporting requirements that must be met.

Storage and capacity planningThe primary purpose of a database is to store and retrieve data, so planning how much disk storage will be required and monitoring available disk space are key DBA responsibilities. Watching growth trends are important so that the DBA can advise management on long-term capacity plans.

Performance monitoring and tuningThe DBA is responsible for monitoring the database server on a regular basis to identify bottlenecks (parts of the system that are slowing down processing) and remedy them. Tuning a database server is done on multiple levels. The capacity of the server hardware and the way the operating system is configured can become limiting factors, as can the database software configuration. The way the database is physically laid out on the disk drives and the types of indexing chosen also have an effect. The way queries against the database are coded can dramatically change how fast results are returned. A DBA needs to understand which monitoring tools are available at each of these levels and how to use them to tune the system. Proactive tuning is an attitude of designing performance into an application from the start, rather than waiting for problems to occur and fixing them. It requires working closely with developers of applications that run against the database to make sure that best practices are followed so good performance will result.

TroubleshootingWhen things do go wrong with the database server, the DBA needs to know how to quickly ascertain the problem and to correct it without losing data or making the situation worse.

Data task by development 

Page 34: Sybullus of DBMS

Whichever development methodology you follow, certain database task are requires at each step. Most of the tasks are performed by the applications developer, with co-ordinate on with DBA.a. Data planning-:It this stage you will have to make a estimate of the data storage requirements. This may helps to decide hardwire requirement of parallel processing number of forms and reports needed etc.

b. Database designThe basic goals of the design stage are to identify the user needs and design the appropriate data tables. Data normalization is the primary database related activity in this state. The final table definition will also provide better estimates of the storage requirement.

c. Data implementations Define standard for application programming. Development of the application and user interface is the major step. Determine the overall looks and feels of application programming standard and testing procedure are defined. 

d. Database operation and maintainsOnce the database is place in operation the DBA performs most of the management task. The primary tasks are a. monitor usage & security b. performs backup and recoveryc. support the users

Backup and recovery system Perhaps most critical database management task is backup. No matter how well you plan, no matter how sophisticated your security system. Something well go wrong. Database manager and developer have an obligation to plan for disasters. The most critical aspect of planning to make sure that a current copy of database is easily accessible. Any types of disasters like fire, flood, terrorist attack, power failure computer virus, disk drive crash or accidental deletion required backup data. If there is a problem the database has to be restored from the backup.OrDBAs are responsible for developing, implementing, and periodically testing a backup and recovery plan for the databases they manage. Even in large shops where a separate system administrator performs server backups, the DBA has final responsibility for making sure that the backups are being done as scheduled and that they include all the files needed to make database recovery possible after a failure. When failures do occur, the DBA needs to know how to use the backups to return the database to operational status as quickly as possible, without losing any transactions that were committed. There are several ways the database can fail, and the DBA must have a strategy to recover from each. From a business standpoint, there is a cost to doing backups, and the DBA makes management aware of the cost/risk trade-offs of various backup methods.

Security and privacy issue of databaseComputer security is an issue with every company today and any computer application files security problem. The purpose of database is to share data. In a security context you want to control who can share the data and what user can do with it. There are basic categories computer securities.

• Physical security:-

Page 35: Sybullus of DBMS

It is the concerned with physical protecting the computing resources and preparing for avoiding physical disaster that might damage equipment or data. The must important task is to make sure that you always have current backup.

• Logical security:-It consists of protecting the data and controlling access to the data. The essence of logical security is that you want to allow each user to have some access to the data but you want to control exactly what types of access the user will have.Posted by Sujan Kunwar at 6:40 AM 1 commentsEmail This BlogThis! Share to Twitter Share to Facebook

Newer Posts Home Subscribe to: Posts (Atom)

About Me

Sujan KunwarKathmandu, Sitapaila, Nepal

Studies at Acme Engineering Collge Phone no: +9779841897208 9779806530917

View my complete profileChapter

▼     2011 (10)

o ▼     February (10)

Sybullus of DBMS

1.Introduction to DBMS

2.Database Design

3.Data Normalization

4.Introduction TO SQL-Simple Queries

5.Advances Queries

6.Forms and Reports

7.Data Manipulation

8.Application Development

9.Database Administration

FOLLOW ME

Sujan Kunwar , Acme Engineering College. Awesome Inc. template. Template images by molotovcoketail. Powered byBlogger.