CHAPTER 1 – INTEGRATION OF USER INTERFACE AND DATABASE
1.1 USER INTERFACE
A user interface is the view of a database interface that is seen by the user.
User interfaces are often graphical or at least partly graphical (GUI - graphical
user interface) constructed and offer tools which make the interaction with the
database easier.
Forms-Based Interfaces
This interface consist of forms which are adapted to the user.
He/She can fill in all of the fields and make new entries to the database or only
some of the fields to query the other ones.
Form-based user interfaces are wide spread and are a very important means of
interacting with a DBMS.
They are easy to use and have the advantage that the user does not need special
knowledge about database languages like SQL.
Text-based Interfaces
To be able to administrate the database directly in the query language SQL (in
code form) via an input/output window.
Text-based interfaces are very powerful tools and allow a comprehensive
interaction with a DBMS.
However, the use of these is based on active knowledge of the respective
database language.
Menu-Based Interfaces for Web Clients or Browsing
These interfaces present the user with lists of options (called menus).
Basic advantage of using menus is that they removes the tension of
remembering specific commands and syntax of any query language.
Pull-down menus are a very popular technique in Web based interfaces.
They are also often used in browsing interface which allow a user to look
through the contents of a database in an exploratory and unstructured manner.
Graphical User Interface
A GUI typically displays a schema to the user in diagrammatic form.
The user then can specify a query by manipulating the diagram.
In many cases, GUI’s utilize both menus and forms.
Most GUIs use a pointing device such as mouse, to pick certain part of the
displayed schema diagram
1.2 APPLICATIONS OF DATABASE SYSTEMS
Inventory Control
Financial Accounting
Fees Management System
Result Analysis system
Admission Management System
Income tax Management System
1.2.1 INVENTORY CONTROL
Inventory management software is made up of several key components that include:
Reorder Point
Should inventory reach a specific threshold, a company's inventory
management system can be programmed to tell managers to reorder that
product.
This helps companies avoid running out of products or tying up too much
capital in inventory.
Asset tracking
When a product is in a warehouse or store, it can be tracked via
its barcode and/or other tracking criteria, such as serial number, lot number or
revision number.
Nowadays, inventory management software often utilizes barcode, radio-
frequency identification (RFID), and/or wireless tracking technology.
Service management
Companies that are primarily service-oriented rather than product-oriented can
use inventory management software to track the cost of the materials they use
to provide services.
This way, they can attach prices to their services that reflect the total cost of
performing them.
Inventory optimization
A fully automated demand forecasting and inventory optimization system to
attain key inventory optimization metrics such as:
Reorder point: the number of units that should trigger a replenishment order
Order quantity: the number of units that should be reordered, based on the
reorder point, stock on hand and stock on order
Lead demand: the number of units that will be sold during the lead time
Stock cover: the number of days left before a stockout if no reorder is made
Accuracy: the expected accuracy of the forecasts
CHAPTER 2 – ADVANCE PROGRAM DEVELOPMENT
METHODOLOGY : SOFTWARE DEVELOPMENT
2.1 SOFTWARE DEVELOPMENT
Software is more than just a program code.
A program is an executable code, which serves some computational purpose.
Software is considered to be collection of executable programming code,
associated libraries and documentations.
Software, when made for a specific requirement is called software product.
Engineering on the other hand, is all about developing products, using well-defined,
scientific principles and methods.
Software engineering is an engineering branch associated with development of
software product using well-defined scientific principles, methods and procedures.
The outcome of software engineering is an efficient and reliable software product
IEEE defines software engineering as:
The application of a systematic,disciplined,quantifiable approach to the
development,operation and maintenance of software; that is, the application of
engineering to software.
2.2 SOFTWARE DEVELOPMENT MODELS
The software development model helps developer to select a strategy to
develop the software.
A software development model has its own set of tools, methods and
procedures, which are expressed clearly and defines software development life
cycle.
A few of software development paradigms or process models are defined as
follows:
2.2.1 Waterfall Model
Waterfall model is the simplest model of software development paradigm.
It says the all the phases of SDLC will function one after another in linear
manner.
That is, when the first phase is finished then only the second phase will start
and so on.
This model assumes that everything is carried out and taken place perfectly as
planned in the previous stage and there is no need to think about the past issues that
may arise in the next phase.
Drawbacks:
This model does not work smoothly if there are some issues left at the
previous step.
The sequential nature of model does not allow us go back and undo or redo
our actions.
Good at:
This model is best suited when developers already have designed and developed
similar software in the past and are aware of all its domains.
2.2.2 Iterative Model
This model leads the software development process in iterations.
It projects the process of development in cyclic manner repeating every step
after every cycle of SDLC process.
The software is first developed on very small scale and all the steps are
followed which are taken into consideration.
Then, on every next iteration, more features and modules are designed,
coded, tested and added to the software.
Every cycle produces a software, which is complete in itself and has more
features and capabilities than that of the previous one.
After each iteration, the management team can do work on risk management
and prepare for the next iteration.
Because a cycle includes small portion of whole software process, it is easier
to manage the development process but it consumes more resources.
2.2.3 Spiral Model
Spiral model is a combination of both, iterative model and one of the SDLC
model.
It can be seen as if you choose one SDLC model and combine it with cyclic
process (iterative model).
This model considers risk, which often goes un-noticed by most other models.
Phase 1: The model starts with determining objectives and constraints of
the software at the start of one iteration.
Phase 2: Next phase is of prototyping the software. This includes risk
analysis.
Phase 3: Product Development
Then one standard SDLC model is used to build the software.
Phase 4: In the fourth phase of the plan of next iteration is prepared.
2.2.4 V – model
The major drawback of waterfall model is we move to the next stage only
when the previous one is finished and there was no chance to go back if
something is found wrong in later stages.
V-Model provides means of testing of software at each stage in reverse
manner.
At every stage, test plans and test cases are created to verify and validate the
product according to the requirement of that stage.
This makes both verification and validation go in parallel.
This model is also known as verification and validation model.
2.2.5 Incremental Model
Incremental Model is a process of software development where requirements
are broken down into multiple standalone modules of software development
cycle. Incremental development is done in steps from analysis design,
implementation, testing/verification, maintenance.
Each iteration passes through the requirements, design, coding and testing phases.
And each subsequent release of the system adds function to the previous release until
all designed functionality has been implemented.
The system is put into production when the first increment is delivered. The first
increment is often a core product where the basic requirements are addressed, and
supplementary features are added in the next increments. Once the core product is
analyzed by the client, there is plan development for the next increment.
Characteristics of an Incremental module includes
System development is broken down into many mini development projects
Partial systems are successively built to produce a final total system
Highest priority requirement is tackled first
Once the requirement is developed, requirement for that increment are frozen
Incremental Phases Activities performed in incremental phases
Requirement Analysis Requirement and specification of the software are collected
Design Some high-end function are designed during this stage
Code Coding of software is done during this stage
Test Once the system is deployed, it goes through the testing phase
When to use Incremental models?
Requirements of the system are clearly understood
When demand for an early release of a product arises
When software engineering team are not very well skilled or trained
When high-risk features and goals are involved
Such methodology is more in use for web application and product based
companies
Advantages and Disadvantages of Incremental Model
Advantages Disadvantages
The software will be generated It requires a good planning
quickly during the software life designing
cycle
It is flexible and less expensive to Problems might cause due to
change requirements and scope system architecture as such not
all requirements collected up
front for the entire software
lifecycle
Thought the development stages Each iteration phase is rigid and
changes can be done does not overlap each other
This model is less costly Rectifying a problem in one unit
compared to others requires correction in all the units
and consumes a lot of time
A customer can respond to each
building
Errors are easy to be identified
2.2.6RAPID APPLICATION DEVELOPMENT MODEL
Rapid application development is a software development methodology that uses
minimal planning in favor of rapid prototyping.
A prototype is a working model that is functionally equivalent to a component of the
product.
In the RAD model, the functional modules are developed in parallel as prototypes
and are integrated to make the complete product for faster product delivery.
RAD projects follow iterative and incremental model and have small teams
comprising of developers, domain experts, customer representatives and other IT
resources working progressively on their component or prototype.
The most important aspect for this model to be successful is to make sure that the
prototypes developed are reusable.
Different phases of RAD model includes
Phases of Activities performed in RAD Model
RAD model
Business On basis of the flow of information and distribution
Modeling between various business channels, the product is designed
Data The information collected from business modeling is
Modeling refined into a set of data objects that are significant for the
business
Process The data object that is declared in the data modeling phase
Modeling is transformed to achieve the information flow necessary to
implement a business function
Application Automated tools are used for the construction of the
Generation software, to convert process and data models into
prototypes
Testing and As prototypes are individually tested during every iteration,
Turnover the overall testing time is reduced in RAD.
When to use RAD Methodology?
When a system needs to be produced in a short span of time (2-3 months)
When the requirements are known
When the user will be involved all through the life cycle
When technical risk is less
When there is a necessity to create a system that can be modularized in 2-3
months of time
When a budget is high enough to afford designers for modeling along with the
cost of automated tools for code generation
Advantages and Disadvantages of SDLC RAD Model
Advantages Disadvantages
Flexible and adaptable to changes It can't be used for smaller
projects
It is useful when you have to Not all application is compatible
reduce the overall project risk with RAD
It is adaptable and flexible to When technical risk is high, it is
changes not suitable
It is easier to transfer deliverables If developers are not committed
as scripts, high-level abstractions to delivering software on time,
and intermediate codes are used RAD projects can fail
Due to code generators and code Reduced features due to time
reuse, there is a reduction of boxing, where features are
manual coding pushed to a later version to finish
a release in short period
Due to prototyping in nature, Reduced scalability occurs
there is a possibility of lesser because a RAD developed
defects application begins as a prototype
and evolves into a finished
application
Each phase in RAD delivers Progress and problems
highest priority functionality to accustomed are hard to track as
client such there is no documentation to
demonstrate what has been done
With less people, productivity Requires highly skilled designers
can be increased in short time or developers
CHAPTER 3 – DATA MODELS
Before Developing a Database we should model to understand its requirements.
This model will be helpful to the End User, DBA, Developer and the
Management.
A Database model defines the logical design and structure of a database and
defines how data will be stored, accessed and updated in a database
management system.
While the Relational Model is the most widely used database model, there are
other models too:
Hierarchical Model
Network Model
Entity-relationship Model
Relational Model
We can develop a data model in to three levels
High Level or Conceptual View (Eg. E-R Model – Understandable By End
User)
Representational or Implementation View (Eg. Relational - Chart used by
developer)
Low level or Physical Model (Storage mechanism in Hard Disk)
3.1 HIERARCHICAL MODEL
This database model organises data into a tree-like-structure, with a single root, to
which all the other data is linked.
The hierarchy starts from the Root data, and expands like a tree, adding child nodes to
the parent nodes.
In this model, a child node will only have a single parent node.
This model efficiently describes many real-world relationships like index of a book,
recipes etc.
In hierarchical model, data is organised into tree-like structure with one one-to-many
relationship between two different types of data, for example, one department can
have many courses, many professors and of course many students.
3.2 NETWORK MODEL
This is an extension of the Hierarchical model.
In this model data is organised more like a graph, and are allowed to have more
than one parent node.
This database model was used to map many-to-many data relationships.
This was the most widely used database model, before Relational Model was
introduced.
3.3 ENTITY RELATIONSHIP MODEL
Entity-Relationship (ER) Model is based on the notion of real-world entities and
relationships among them.
While formulating real-world scenario into the database model, the ER Model
creates entity set, relationship set, general attributes and constraints.
ER Model is best used for the conceptual design of a database.
ER Model is based on −
Entities and their Attributes.
Relationships among entities
Entities may be considered as noun in real world scenario
Attribute describes that noun
Relationship is verb that associate two entities
Entity Set − An entity set in an ER Model is a real-world entity having
properties called attributes. Every attribute is defined by its set of values
called domain. For example, in a school database, a student is considered as
an entity set. Student has various attributes like name, age, class, etc.
Relationship − The logical association among entities is called relationship.
Relationships are mapped with entities in various ways. Mapping cardinalities
define the number of association between two entities.
For Example Consider two entity sets Cars with the attributes model, colour,
Engine Number and Person with attributes Name, age, gender, address.
There is a relationship between the Car and the person is Owns. A person
owns a Car
Facts about ER Diagram Model:
ER model allows you to draw Database Design
It is an easy to use graphical tool for modeling data
Widely used in Database Design
It is a GUI representation of the logical structure of a Database
It helps you to identifies the entities which exist in a system and the
relationships between those entities
3.3.1 STRONG ENTITY SET
A strong entity set is an entity set that contains sufficient attributes to uniquely
identify all its entities.
In other words, a primary key exists for a strong entity set.
Primary key of a strong entity set is represented by underlining it.
Symbols Used
A single rectangle is used for representing a strong entity set.
A diamond symbol is used for representing the relationship that exists between
two strong entity sets.
A single line is used for representing the connection of the strong entity set
with the relationship set.
A double line is used for representing the total participation of an entity set
with the relationship set.
Total participation may or may not exist in the relationship.
In this ER diagram,
Two strong entity sets “Student” and “Course” are related to each other.
Student ID and Student name are the attributes of entity set “Student”.
Student ID is the primary key using which any student can be identified
uniquely.
Course ID and Course name are the attributes of entity set “Course”.
Course ID is the primary key using which any course can be identified
uniquely.
Double line between Student and relationship set signifies total participation.
It suggests that each student must be enrolled in at least one course.
Single line between Course and relationship set signifies partial participation.
It suggests that there might exist some courses for which no enrollments are
made.
3.3.2 WEAK ENTITY
A weak entity set is an entity set that does not contain sufficient attributes to
uniquely identify its entities.
In other words, a primary key does not exist for a weak entity set.
However, it contains a partial key called as a discriminator.
Discriminator is represented by underlining with a dashed line.
NOTE-
The combination of discriminator and primary key of the strong entity set
makes it possible to uniquely identify all entities of the weak entity set.
Thus, this combination serves as a primary key for the weak entity set.
Clearly, this primary key is not formed by the weak entity set completely.
Symbols Used
A double rectangle is used for representing a weak entity set.
A double diamond symbol is used for representing the relationship that exists
between the strong and weak entity sets and this relationship is known
as identifying relationship.
A double line is used for representing the connection of the weak entity set
with the relationship set.
Total participation always exists in the identifying relationship.
Example-
Consider the following ER diagram-
In this ER diagram,
One strong entity set “Building” and one weak entity set “Apartment” are
related to each other.
Strong entity set “Building” has building number as its primary key.
Door number is the discriminator of the weak entity set “Apartment”.
This is because door number alone cannot identify an apartment uniquely as
there may be several other buildings having the same door number.
Double line between Apartment and relationship set signifies total
participation.
It suggests that each apartment must be present in at least one building.
Single line between Building and relationship set signifies partial participation.
It suggests that there might exist some buildings which has no apartment.
To uniquely identify any apartment,
First, building number is required to identify the particular building.
Secondly, door number of the apartment is required to uniquely identify the
apartment.
Thus,
Primary key of Apartment
= Primary key of Building + Its own discriminator
= Building number + Door number
3.3.3 STRONG ENTITY VS. WEAK ENTITY
Strong Entity Set Weak Entity Set
Strong entity set always has a primary key. It does not have enough attributes to build a
primary key.
It is represented by a rectangle symbol. It is represented by a double rectangle
symbol.
It contains a Primary key represented by It contains a Partial Key which is
the underline symbol. represented by a dashed underline symbol.
The member of a strong entity set is called The member of a weak entity set called as a
as dominant entity set. subordinate entity set.
Primary Key is one of its attributes which In a weak entity set, it is a combination of
helps to identify its member. primary key and partial key of the strong
entity set.
In the ER diagram the relationship between The relationship between one strong and a
two strong entity set shown by using a weak entity set shown by using the double
diamond symbol. diamond symbol.
The connecting line of the strong entity set The line connecting the weak entity set for
with the relationship is single. identifying relationship is double.
3.3.4 ATTRIBUTES IN ER DIAGRAM
Attributes are the descriptive properties which are owned by each entity of
an Entity Set.
There exist a specific domain or set of values for each attribute from where the
attribute can take its values.
Types of Attributes-
In ER diagram, attributes associated with an entity set may be of the following types-
1. Simple attributes
2. Composite attributes
3. Single valued attributes
4. Multi valued attributes
5. Derived attributes
6. Key attributes
1. Simple Attributes-
Simple attributes are those attributes which cannot be divided further.
Here, all the attributes are simple attributes as they cannot be divided further.
2. Composite Attributes-
Composite attributes are those attributes which are composed of many other simple
attributes.
Here, the attributes “Name” and “Address” are composite attributes as they are
composed of many other simple attributes.
3. Single Valued Attributes-
Single valued attributes are those attributes which can take only one value for a given
entity from an entity set. This is also a Simple attribute.
Example-
Here, all the attributes are single valued attributes as they can take only one specific
value for each entity.
4. Multi Valued Attributes-
Multi valued attributes are those attributes which can take more than one value for a
given entity from an entity set.
Example-
Here, the attributes “Mob_no” and “Email_id” are multi valued attributes as they can
take more than one values for a given entity.
5. Derived Attributes-
Derived attributes are those attributes which can be derived from other attribute(s).
Example-
Here, the attribute “Age” is a derived attribute as it can be derived from the attribute
“DOB”.
6. Key Attributes-
Key attributes are those attributes which can identify an entity uniquely in an entity
set.
Here, the attribute “Roll_no” is a key attribute as it can identify any student uniquely.
3.3.5 CARDINALITY IN ER DIAGRAM
Cardinality Constraint-
Cardinality constraint defines the maximum number of relationship instances in which an
entity can participate.
Types of Cardinality Ratios-
There are 4 types of cardinality ratios-
1. Many-to-Many Cardinality-
By this cardinality constraint,
An entity in set A can be associated with any number (zero or more) of entities
in set B.
An entity in set B can be associated with any number (zero or more) of entities
in set A.
Here,
One student can enroll in any number (zero or more) of courses.
One course can be enrolled by any number (zero or more) of students.
2. Many-to-One Cardinality-
By this cardinality constraint,
An entity in set A can be associated with at most one entity in set B.
An entity in set B can be associated with any number (zero or more) of entities
in set A.
Consider the following ER diagram-
One student can enroll in at most one course.
One course can be enrolled by any number (zero or more) of students.
3. One-to-Many Cardinality-
By this cardinality constraint,
An entity in set A can be associated with any number (zero or more) of entities
in set B.
An entity in set B can be associated with at most one entity in set A.
One student can enroll in any number (zero or more) of courses.
One course can be enrolled by at most one student.
4. One-to-One Cardinality-
By this cardinality constraint,
An entity in set A can be associated with at most one entity in set B.
An entity in set B can be associated with at most one entity in set A.
One student can enroll in at most one course.
One course can be enrolled by at most one student.
Some other Way of Representation for Cardinality, another method is given
below
3.4 SQL STATEMENTS
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the
Relational Database Management Systems (RDMS) like MySQL, MS Access,
Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard
database language.
SQL Commands
The standard SQL commands to interact with relational databases are CREATE,
SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be
classified into the following groups based on their nature −
DDL - Data Definition Language
[Link]. Command & Description
CREATE
1
Creates a new table, a view of a table, or other object in the database.
ALTER
2
Modifies an existing database object, such as a table.
DROP
3
Deletes an entire table, a view of a table or other objects in the database.
DML - Data Manipulation Language
[Link]. Command & Description
SELECT (DQL)
1
Retrieves certain records from one or more tables.
INSERT
2
Creates a record.
UPDATE
3
Modifies records.
DELETE
4
Deletes records.
DCL - Data Control Language
[Link]. Command & Description
GRANT
1
Gives a privilege to user.
REVOKE
2
Takes back privileges granted from user.
TCL –Transaction Control Language
[Link]. Command & Description
COMMIT
1
permanently save any transaction into the database.
ROLLBACK
2
restores the database to last committed state..
SAVEPOINT
3 used to temporarily save a transaction so that you can rollback to that
point whenever required.
3.4.1 DDL COMMANDS
There are two CREATE statements available in SQL:
1. CREATE DATABASE
2. CREATE TABLE
[Link] CREATE DATABASE
A Database is defined as a structured set of data. So, in SQL the very first step to
store the data in a well-structured manner is to create a database. The CREATE
DATABASE statement is used to create a new database in SQL.
Syntax:
CREATE DATABASE database_name;
Example Query:
This query will create a new database in SQL and name the database as my_database.
CREATE DATABASE my_database;
[Link] CREATE TABLE
The CREATE TABLE statement is used to create a table in SQL. While creating
tables we have to provide all the information to SQL about the names of the columns,
type of data to be stored in columns, size of the data etc.
Syntax
The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
The following code block is an example, which creates a CUSTOMERS table with
an ID as a primary key and NOT NULL are the constraints showing that these fields
cannot be NULL while creating records in this table −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
[Link] DROP or DELETE Database
The SQL DROP DATABASE statement is used to drop an existing database in SQL
schema.
Syntax
The basic syntax of DROP DATABASE statement is as follows −
DROP DATABASE DatabaseName;
Always the database name should be unique within the RDBMS.
Example
If you want to delete an existing database <testDB>, then the DROP DATABASE
statement would be as shown below −
SQL> DROP DATABASE testDB;
[Link] DROP or DELETE Table
The SQL DROP TABLE statement is used to remove a table definition and all the
data, indexes, triggers, constraints and permission specifications for that table.
Syntax
The basic syntax of this DROP TABLE statement is as follows −
DROP TABLE table_name;
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
[Link] TRUNCATE TABLE Command
The SQL TRUNCATE TABLE command is used to delete complete data from an
existing table.
You can also use DROP TABLE command to delete complete table but it would
remove complete table structure form the database and you would need to re-create
this table once again if you wish you store some data.
Syntax
The basic syntax of a TRUNCATE TABLE command is as follows.
TRUNCATE TABLE table_name;
SQL > TRUNCATE TABLE CUSTOMERS;
Now, the CUSTOMERS table is truncated
Difference between DROP and TRUNCATE Statement:
If a table is dropped, all the relationships with other tables will no longer be valid,
the integrity constraints will be dropped, grant or access privileges on the table will
also be dropped, if you want use the table again it has to be recreated with the
integrity constraints, access privileges and the relationships with other tables should
be established again.
But, if a table is truncated, the table structure remains the same, therefore any of the
above problems will not exist.
Difference between DELETE and TRUNCATE Statements:
DELETE Statement: This command deletes only the rows from the table based on
the condition given in the where clause or deletes all the rows from the table if no
condition is specified. But it does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the
table and free the space containing the table.
[Link] ALTER TABLE Command
The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table. You should also use the ALTER TABLE command to add and drop
various constraints on an existing table.
Syntax
The basic syntax of an ALTER TABLE command to add a New Column in an
existing table is as follows.
ALTER TABLE table_name ADD column_name datatype;
The basic syntax of an ALTER TABLE command to DROP COLUMN in an
existing table is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a
column in a table is as follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to
a column in a table is as follows.
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is
as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
The basic syntax of an ALTER TABLE command to ADD CHECK
CONSTRAINTto a table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of an ALTER TABLE command to ADD PRIMARY
KEYconstraint to a table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a
table is as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;
If you're using MySQL, the code is as follows −
ALTER TABLE table_name
DROP INDEX MyUniqueConstraint;
The basic syntax of an ALTER TABLE command to DROP PRIMARY
KEYconstraint from a table is as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyPrimaryKey;
If you're using MySQL, the code is as follows −
ALTER TABLE table_name
DROP PRIMARY KEY;
Following is the example to ADD a New Column to an existing table −
ALTER TABLE CUSTOMERS ADD SEX char(1);
Following is the example to DROP sex column from the existing table.
ALTER TABLE CUSTOMERS DROP SEX;
3.4.2 DML - DATA MANIPULATION LANGUAGE
[Link] SELECT Query (DQL)
The SQL SELECT statement returns a result set of records from one or more
tables.
A SELECT statement retrieves zero or more rows from one or more database
tables or database views. In most applications, SELECT is the most commonly
used data query language (DQL) command.
The SELECT statement has many optional clauses:
WHERE specifies which rows to retrieve.
GROUP BY groups rows sharing a property so that an aggregate function can
be applied to each group.
HAVING selects among the groups defined by the GROUP BY clause.
ORDER BY specifies an order in which to return the rows.
AS provides an alias which can be used to temporarily rename tables or
columns.
SQL SELECT Statement
SELECT column1, column2....columnN
FROM table_name;
SQL DISTINCT Clause
SELECT DISTINCT column1, column2....columnN
FROM table_name;
SQL WHERE Clause
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;
SQL AND/OR Clause
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
SQL IN Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SQL BETWEEN Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SQL LIKE Clause
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SQL ORDER BY Clause
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SQL GROUP BY Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQL COUNT Clause
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
SQL HAVING Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
[Link]. INSERT Query
The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown
below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,'Ramesh',32,'Ahmedabad',2000.00);
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
[Link] UPDATE Query
The SQL UPDATE Query is used to modify the existing records in a table. You can
use the WHERE clause with the UPDATE query to update the selected rows,
otherwise all the rows would be affected.
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
WHERE ID = 6;
[Link]. DELETE Query
The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows,
otherwise all the records would be deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
SQL> DELETE FROM CUSTOMERS;
Now, the CUSTOMERS table would not have any record.
3.4.3 DCL COMMANDS
Introduction to DCL
DCL stands for Data Control Language.
DCL is used to control user access in a database.
This command is related to the security issues.
Using DCL command, it allows or restricts the user from accessing data in
database schema.
DCL commands are as follows,
1. GRANT
2. REVOKE
It is used to grant or revoke access permissions from any database user.
[Link] GRANT COMMAND
GRANT command gives user's access privileges to the database.
This command allows specified users to perform specific tasks.
Syntax:
GRANT <privilege list>
ON <object Name or relation name or view name>
TO <user/role list>;
Example : GRANT Command
GRANT ALL ON employee
TO ABC;
[WITH GRANT OPTION]
In the above example, user 'ABC' has been given permission to view and modify the
records in the 'employee' table.
eg:
GRANT SELECT, UPDATE
ON Student TO X
Objects Privileges that can be given to users.
Each object privileges that is granted authorized the grantee to perform some
operation on the object. A user can grant all the privileges or grant only specific object
privileges.
The list of object privileges is as follows:
Alter: Allows the grantee to change the table definition with the ALTER TABLE
command.
DELETE: Allows the grantee to remove the records from the table with the DELETE
command.
INDEX: Allows the grantee to create an index on the table with the CREATE
INDEX command.
INSERT: Allows the grantee to add records to the table with the INSERT command.
SELECT: Allows the grantee to query the table with the SELECT command.
UPDATE: Allows the grantee to modify the records in the tables with the UPDATE
command.
[Link] REVOKE COMMAND
REVOKE command is used to cancel previously granted or denied
permissions.
This command withdraw access privileges given with the GRANT command.
It takes back permissions from user.
Syntax:
REVOKE <privilege list>
ON <object name or relation name or view name>
FROM <user name>;
Example : REVOKE Command
REVOKE UPDATE
ON employee
FROM ABC;
Difference between GRANT and REVOKE command.
GRANT REVOKE
GRANT command allows a user to REVOKE command disallows a user to
perform certain activities on the database. perform certain activities.
It grants access privileges for database It revokes access privileges for database
objects to other users. objects previously granted to other users.
Example: Example:
GRANT privilege_name REVOKE privilege_name
ON object_name ON object_name
TO
FROM
{ {
user_name|PUBLIC|role_name user_name|PUBLIC|role_name
} }
[WITH GRANT OPTION];
3.4.4 DCL COMMANDS
Transaction Control Language(TCL) commands are used to manage transactions in
the database. These are used to manage the changes made to the data in a table by
DML statements. It also allows statements to be grouped together into logical
transactions.
[Link] COMMIT command
COMMIT command is used to permanently save any transaction into the
database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes
made by these commands are not permanent, until the current session is closed, the
changes made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
[Link] ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use
the ROLLBACK command to rollback those changes, if they were not commited
using the COMMIT command.
Following is rollback command's syntax,
ROLLBACKTO savepoint_name;
[Link] SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can
rollback to that point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in any table
and then rollback to that state using the ROLLBACK command whenever required.
Using Savepoint and Rollback
Following is the table class,
id name
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
INSERTINTO class VALUES(5,'Rahul');
COMMIT;
UPDATE class SET name ='Abhijit'WHERE id ='5';
SAVEPOINT A;
INSERTINTO class VALUES(6,'Chris');
SAVEPOINT B;
INSERTINTO class VALUES(7,'Bravo');
SAVEPOINT C;
SELECT*FROM class;
NOTE: SELECT statement is used to show the data stored in the table.
The resultant table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to
the savepoint B.
ROLLBACKTO B;
SELECT*FROM class;
Now our class table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to
the savepoint A
ROLLBACKTO A;
SELECT*FROM class;
Now the table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
So now you know how the
commands COMMIT, ROLLBACK and SAVEPOINT works.
3.5 DATA DICTIONARY
A data dictionary is a file or a set of files that contains a database's metadata
(data about data). The data dictionary contains records about other objects in the
database, such as data ownership, data relationships to other objects, and other
data.
The data dictionary is a crucial component of any relational database. Ironically,
because of its importance, it is invisible to most database users. Typically, only
database administrators interact with the data dictionary.
The metadata in the data dictionary includes the following:
Names of all tables in the database and their owners
Names of all indexes and the columns to which the tables in those indexes
relate
Constraints defined on tables, including primary keys, foreign-key
relationships to other tables, and not-null constraints
Last accessed information of the object
Last updated information of the object
Physical information like where is the data stored for this table
The definitions of all database objects like tables, views, constraints,
indexes, clusters, synonyms, sequences, procedures, functions,
packages, triggers etc
It stores the information about how much space is allocated for each
object and how much space has been used by them
Any default values that a column can have are stored
Database user names - schemas
Access rights for schemas on each of the objects
Types of Data Dictionary
Here are the two types of data dictionary:
Active Data Dictionary
The DBMS software manages the active data dictionary automatically. The modification is an
automatic task and most RDBMS has active data dictionary. It is also known as integrated data
dictionary.
Passive Data Dictionary
Managed by the users and is modified manually when the database structure change. Also
known as non-integrated data dictionary.
SELECT * FROM DBA_TABLES WHERE TABLE_NAME LIKE '%LOAN%';
SELECT * FROM SYSOBJECTS WHERE TYPE='U' AND NAME LIKE
'%LOAN%';