Upload
buidiep
View
226
Download
0
Embed Size (px)
Citation preview
Information Systems : Fundamentals of Information Systems : Fundamentals of
Professor : Imade BENELALLAM
Information SystemPr. Imade BENELALLAM
Information Systems : Fundamentals of Information Systems : Fundamentals of DatabasesDatabases
1
Objectives:
In this course, you will work with databases by :
• identifying the fundamental concepts of databases,
• creating a preliminary database design,
• applying normalization techniques,
• and familiarizing yourself with relational database management • and familiarizing yourself with relational database management systems.
you will work with MySQL by :
• Using various SQL commands, indexes, and views, you can work with and modify data efficiently within a database.
• Using features such as Enterprise Monitor and MySQL Administrator, you can manage users and administer and monitor a database.
2
Outline
• Introduction to Information Systems• Fundamentals of Databases• Creating a Preliminary Database Design• Applying Normalization Techniques• Applying Normalization Techniques• Explore the MySQL RDBMS• Using the SQL Commands to Work with Tables• Working with Databases• Managing Databases• Administering a Database
3
Introduction to Information Systems
Objectives : In this lesson, You will be introduced to
information systems.
Introduction to Information Systems
4
Introduction to Information Systems
Information Systems
Definition :
Information systems or the more common legacy information systems include :
• people,
5
• people,
• procedures,
• data,
• software,
• and hardware,
that are used to gather and analyze digital Data.
Introduction to Information Systems
Types of Information Systems
The 'classic' view of Information systems is a pyramid of systems that reflected the
hierarchy of the organization, usually :
• Transaction processing systems at the bottom of the pyramid, followed by
• Management information systems,
• Decision support systems and ending with
• Executive information systems at the top.
6
• Executive information systems at the top.
Fundamentals of Databases
Objectives : In this lesson, you will identify the
fundamental concepts of databases.
Fundamentals of Databases
7
Fundamentals of Databases
Introduction : why we need a Database ?
Problem :
Imagine a scenario where you have to maintain a contact directory.
As the number of users in the directory increases, searching for the details of a
specific person or modifying his contact information becomes a cumbersome task.
Solution :
• Maintaining huge volumes of data using a data management system will enable you
8
• Maintaining huge volumes of data using a data management system will enable you
to manage information efficiently.
Fundamentals of Databases
Introduction : Manual file processing !!
Problem :
• Managing large volumes of data using manual file processing systems becomes
tedious and time consuming.
• It could result in issues such as data redundancy,
Solution :
• Acquiring knowledge on the basics of database and MySQL will enable you to add,
9
• Acquiring knowledge on the basics of database and MySQL will enable you to add,
update, and maintain data using a computerized database management system.
Fundamentals of Databases
Databases
• A database is an organized collection of data; it is used to facilitate easy storage and
retrieval of information.
• In a database, data may be grouped into a series of records, which can be further
organized into smaller segments of data called fields.
• A table is the basic storage unit of a database and it consists of rows and columns.
• The model of a database decides the way the data is organized in it.
Identify the Database Developpment Life Cycle
10
• The model of a database decides the way the data is organized in it.
Fundamentals of Databases
DBMS
• A Database Management System (DBMS) is an application program that is used to
manage electronic data.
• A user can use a DBMS to store and retrieve information in an organized manner.
Identify the Database Developpment Life Cycle
11
Fundamentals of Databases
Database Models
Databases can be designed using various database models such as hierarchical,
network, and relational.
Identify the Database Developpment Life Cycle
12
Fundamentals of Databases
Database Models
Identify the Database Developpment Life Cycle
13
Fundamentals of Databases
Database Models
Identify the Database Developpment Life Cycle
14
Fundamentals of Databases
Database Types
Identify the Database Developpment Life Cycle
Databases can be broadly classified into two types. They are Online Transaction
Processing (OLTP) and Decision Support System (DSS).
15
Fundamentals of Databases
Database Types
Identify the Database Developpment Life Cycle
16
Fundamentals of Databases
Tables
Identify the Database Developpment Life Cycle
• A table is a set of data elements represented in vertical columns and horizontal
rows.
• A column is a field or an attribute of a table, and
• A row is a combination of column values in a table. it represents records.
• Tables are described by a set of unique characteristics and they store data of the
same type in each row.
• In a database structure, tables are also called entities and are used to create a
17
• In a database structure, tables are also called entities and are used to create a
graphical representation of the database structure.
Fundamentals of Databases
Data feilds
Identify the Database Developpment Life Cycle
A data field, which is a column in a database table, can store specific data. Each data
field stored in a table defines data including numeric values, characters, date, and
time. Data fields, also referred to as attributes, are present in business forms,
spreadsheets, word processing documents, and web pages.
18
Fundamentals of Databases
Tiered architecture
Identify the Database Developpment Life Cycle
Tiered architecture helps in the easy usage and maintenance of a database by
providing various views to different levels of users. With tiered architecture,
application developers can reuse specific codes or write development programs. It
facilitates the server to respond efficiently to client requests and also allows an end
user to access a database irrespective of the database design.
19
Fundamentals of Databases
Tiered architecture
Identify the Database Developpment Life Cycle
Tiered architecture is predominantly of two types, two-tier and multi-tier.
20
Fundamentals of Databases
Tiered architecture
Identify the Database Developpment Life Cycle
21
Fundamentals of Databases
Data warehouse
Identify the Database Developpment Life Cycle
• A data warehouse is a collection of an
organization's electronically stored data.
• A data warehouse is also referred to as a
22
• A data warehouse is also referred to as a
Decision Support System (DSS). It facilitates
effective data retrieval, analysis, extraction,
and transformation of data.
• A data warehouse is a business
intelligence technology.
Fundamentals of Databases
Data dictionnary
Identify the Database Developpment Life Cycle
A data dictionary, which is a centralized repository of data, defines the organization of a
database. It contains information such as the
• file format,
• structure,
23
• structure,
• data meaning,
• data relationship, and their usage.
• list of files in a database,
• number of records in files, and
• the names and types of fields in records and their origin.
Data dictionaries are often hidden from users for security and safety purposes.
Fundamentals of Databases
Database development life cycle
Identify the Database Developpment Life Cycle
Database development involves five distinct phases from conception to completion in a
top-down, systematic approach.
24
Fundamentals of Databases
Database development life cycle
Identify the Database Developpment Life Cycle
Database development involves five distinct phases from conception to completion in a
top-down, systematic approach.
25
Fundamentals of Databases
Database development life cycle
Identify the Database Developpment Life Cycle
Database development involves five distinct phases from conception to completion in a
top-down, systematic approach.
26
Fundamentals of Databases
Database development life cycle
Identify the Database Developpment Life Cycle
Database development involves five distinct phases from conception to completion in a
top-down, systematic approach.
27
Fundamentals of Databases
Database development life cycle
Identify the Database Developpment Life Cycle
Database development involves five distinct phases from conception to completion in a
top-down, systematic approach.
28
Fundamentals of Databases
Quiz
Identify the Database Developpment Life Cycle
29
Fundamentals of Databases
Quiz
Identify the Database Developpment Life Cycle
30
Fundamentals of Databases
Quiz
Identify the Database Developpment Life Cycle
31
Creating a Preliminary Database Design
Objectives : In this lesson, you will creat a preliminary
database design
Creating a Preliminary Database Design
32
Creating a Preliminary Database Design
Lesson introduction
Introduction
Organizations usually store and process massive amounts of data !!...
The problem :
33
The problem :
If there are changes in the data storage structure after the design is implemented, it will
lead to major rework.
Creating a Preliminary Database Design
Lesson introduction (cont.)
Introduction
when you design a database, it is necessary to validate and understand the need and
usage of the proposed database at every stage. A clear and accurate design will play a
crucial role in creating effective databases.
34
Creating a Preliminary Database Design
Types of information to collects
Analyze database requirements
• Conducting a database requirements analysis helps in collecting information on an
existing system to ensure that gaps, if any, are bridged in the new design.
• To design your database, you will collect information about any existing storage
systems in an organization.
35
Creating a Preliminary Database Design
Sources of information
Analyze database requirements
You can gather and collect information about database requirements from different
sources. Some of the sources are:
• data entry staff;
• department heads and managers, who analyze and view specific reports of their
departments;
• and business managers, who want reports that they are unable to retrieve from the
36
• and business managers, who want reports that they are unable to retrieve from the
existing system.
Creating a Preliminary Database Design
Business rules
Analyze database requirements
• Business rules are procedures and policies of a company that would affect the input of
data in a database.
• Business rules are translated into constraints, which are a technical limitation on how
data in a database can be stored and manipulated; they are enforced through database
design techniques.
• The constraints are then incorporated into the database design.
37
• The constraints are then incorporated into the database design.
• Business rules influence the data you collect and store, and the manner in which you
define and establish relationships among tables.
Creating a Preliminary Database Design
How to conduct a database requirements analysis ?
Analyze database requirements
Guidelines
1. Prepare a questionnaire.
2. State the purpose of the database at the beginning of each conversation to help
everyone stay focused.
3. Interview people who use the existing system and obtain information about the
38
3. Interview people who use the existing system and obtain information about the
reports and forms they use frequently.
4. Collect information on forms and reports that you would need in the future.
5. Record all information about the existing system.
6. Review existing forms and reports to:
1. Determine the relevance of reports.
2. Identify the shortcomings in generating the desired reports.
3. Determine the existing business rules.
7. Identify the hardware and software requirements for the proposed system.
8. Identify the resources for the project and the overall cost of the system.
Creating a Preliminary Database Design
Keys
Identify key fields
• A key is a data field that ensures that each
record in a table is uniquely identified.
• A key field is used for searches while creating
reports based on the data in the table. In
addition, you can also use keys to establish
relationships among tables.
39
relationships among tables.
Creating a Preliminary Database Design
Types of Keys
Identify key fields
Different types of keys are used to enter data correctly and uniquely identify it in a
table.
40
Creating a Preliminary Database Design
Types of Keys
Identify key fields
Different types of keys are used to enter data correctly and uniquely identify it in a
table.
41
Creating a Preliminary Database Design
Types of Keys
Identify key fields
Different types of keys are used to enter data correctly and uniquely identify it in a
table.
42
Creating a Preliminary Database Design
Types of Keys
Identify key fields
Different types of keys are used to enter data correctly and uniquely identify it in a
table.
43
Creating a Preliminary Database Design
Null values
Identify key fields
• A null value is the value used to indicate the absence of any data in a given field.
• A field is considered to be null, only when there is no value assigned to it or the data
for the field is unavailable. Further, a null value can be found in a field containing any
type of data. Null values are never equal to zero.
44
type of data. Null values are never equal to zero.
Creating a Preliminary Database Design
Constraints
Identify key fields
• Constraints are conditions or validation checks that you apply when creating a
database to ensure storage of valid data. They are derived from business rules defined
during the database design.
• Constraints can be modified once they are defined and can be implemented at both
the table and column level.
45
Creating a Preliminary Database Design
Types of Constraints
Identify key fields
Different types of constraints can be used in a database.
46
Creating a Preliminary Database Design
Types of Constraints
Identify key fields
Different types of constraints can be used in a database.
47
Creating a Preliminary Database Design
Types of Constraints
Identify key fields
Different types of constraints can be used in a database.
48
Creating a Preliminary Database Design
Types of Constraints
Identify key fields
Different types of constraints can be used in a database.
49
Creating a Preliminary Database Design
Types of Constraints
Identify key fields
Different types of constraints can be used in a database.
50
Creating a Preliminary Database Design
Determine data fields
Identify key fields
Justin Valone, the database designer of Dazzle Florist is responsible for creating a
complete list of fields for their new database. He examines the existing reports and
creates a list of fields. He sets up a meeting with potential users of the new database,
such as the department head, to understand their expectations of the new database.
He summarizes the information and prepares a final list of fields including the
calculated fields.
51
calculated fields.
Creating a Preliminary Database Design
How to Identify Key Fields
Identify key fields
Procedure Reference:
Identify Key Fields
To identify key fields:
1. Identify a candidate key by choosing a field or fields that do not accept duplicate and blank
values. A candidate key qualifies as a primary key.
2. Repeat step 1 until all candidate keys for the tables have been identified.
3. Identify a primary key from the list of candidate keys.
• From the list of candidate keys, choose a field that holds unique values under all
52
• From the list of candidate keys, choose a field that holds unique values under all
circumstances.
• If a single field from the list of candidate keys cannot be identified as a primary key, you
can have a composite primary key, which is a combination of fields that do not accept
duplicate values.
• If a field in a table does not hold a unique value, you can add a new field as a unique
identifier.
4. Identify a foreign key by choosing a field or fields in a relational table that matches a primary
key column or columns of another table. In the current table, ensure that the data type of the
foreign key column matches the data type of the primary key column of the other table.
5. Repeat steps 3 and 4 until all primary keys and foreign keys for all the tables have been
identified.
Creating a Preliminary Database Design
Entities
Creat entity relationship diagrams
An entity is a database component with specific characteristics. In a database
structure, entities refer to tables and are used to create a graphical representation of
the database structure.
53
Creating a Preliminary Database Design
Relatioships
Creat entity relationship diagrams
• A relationship is a method used for linking two
tables based on the presence of a common field
found in both tables.
54
found in both tables.
• Linking tables is necessary to create reports that
use data from both tables.
• By using relationships, you can link a record in
one table to a record in another table.
Creating a Preliminary Database Design
Types of Relatioships based on cardinality
Creat entity relationship diagrams
Cardinality specifies the relationship among tables based on the number of rows in one
table related to the number of rows in another table.
55
Creating a Preliminary Database Design
Types of Relatioships based on cardinality
Creat entity relationship diagrams
Cardinality specifies the relationship among tables based on the number of rows in one
table related to the number of rows in another table.
56
Creating a Preliminary Database Design
Types of Relatioships based on cardinality
Creat entity relationship diagrams
Cardinality specifies the relationship among tables based on the number of rows in one
table related to the number of rows in another table.
57
Creating a Preliminary Database Design
Types of Relatioships based on cardinality
Creat entity relationship diagrams
Cardinality specifies the relationship among tables based on the number of rows in one
table related to the number of rows in another table.
58
Creating a Preliminary Database Design
Types of Relatioships based on cardinality
Creat entity relationship diagrams
Cardinality specifies the relationship among tables based on the number of rows in one
table related to the number of rows in another table.
59
Creating a Preliminary Database Design
Types of Relatioships based on optionality
Creat entity relationship diagrams
Optionality relationships are based on the occurrence of rows in related tables.
60
Creating a Preliminary Database Design
Types of Relatioships based on optionality
Creat entity relationship diagrams
Optionality relationships are based on the occurrence of rows in related tables.
61
Creating a Preliminary Database Design
Entity Relatioship Diagram
Creat entity relationship diagrams
• An Entity Relationship Diagram or ERD is a graphical representation of the design of a
database.
• An ERD consists of entities, key fields in each entity, and the relationships among the
entities.
• ERD is used as a blue print of the database structure. It helps validate the design with
the client requirements and convey the requirement analysis to the development team.
62
Creating a Preliminary Database Design
Laboratory
Creat entity relationship diagrams
63
Applaying normalization techniques
Introduction : Applaying normalization techniques
Introduction
Problem :
If the client requirement is to generate a report based on the last names of employees
and the new design does not provide for a last name field in the employee table, then
64
and the new design does not provide for a last name field in the employee table, then
the design does not meet the client requirement.
Solution :
• To avoid such situations, normalization principles are applied to the preliminary
design to ensure that data fields store data in the smallest form.
• A good design results in creating an efficient table structure.
Applaying normalization techniques
Data anomalies
Normalize tables
• A data anomaly is data inconsistency introduced in data when rows are inserted or
updated in a table or deleted from a table.
• Duplicate entry of records, or improper relationships among tables cause data
anomaly.
• A data anomaly can be categorized as insertion anomaly, update anomaly, or
deletion anomaly based on the action that causes data inconsistency.
65
deletion anomaly based on the action that causes data inconsistency.
Applaying normalization techniques
Normalization
Normalize tables
• Normalization is a process that eliminates duplicate data and organizes tables to
increase the ease of managing and modifying data.
• Each normal form represents a set of rules; each normal form also assumes that the
requirements of the preceding forms have been met.
• Data normalization is part of the database design process and is not specific or
unique to any particular RDBMS.
66
unique to any particular RDBMS.
• In normalizing your data, you usually divide large tables into smaller, easy-to-
maintain tables.
Applaying normalization techniques
The normalization process
Normalize tables
The process of normalization involves applying different rules, called normal forms, in
a sequence to tables.
67
Applaying normalization techniques
The normalization process
Normalize tables
The process of normalization involves applying different rules, called normal forms, in
a sequence to tables.
68
Applaying normalization techniques
The normalization process
Normalize tables
The process of normalization involves applying different rules, called normal forms, in
a sequence to tables.
69
Applaying normalization techniques
The normalization process
Normalize tables
The process of normalization involves applying different rules, called normal forms, in
a sequence to tables.
70
Applaying normalization techniques
The first normal form
Normalize tables
• The first normal form or 1NF is a rule that states that each field in a table should be
atomic.
• Atomic field means the data stored in that field is in its smallest form and
cannot be subdivided.
• This form of normalization is also known as atomic normalization.
• In addition, this rule also states that the database should contain no repeating
71
• This form of normalization is also known as atomic normalization.
• In addition, this rule also states that the database should contain no repeating
groups, that is, no two fields in a table should store values that are logically
related.
• The first normal form is applied as the first step of the normalization process, and
this leads to splitting fields in a table or splitting tables.
Do example
Applaying normalization techniques
Functional dependency
Normalize tables
Functional dependency is a relationship between two fields in a table where the value
in one field is determined by the value in the other field. Functional dependency is
represented as B is functionally dependent on A, such that each value of B is
determined by a unique value of A.
72
Applaying normalization techniques
The second normal form
Normalize tables
• The second normal form or 2NF is a rule that states that a table should be in the first
normal form and each non-primary key field should be functionally dependent on the
complete primary key.
• If the primary key consists of multiple fields, then all non-key fields should be
functionally dependent on all the fields of the primary key.
• The second normal form is usually applied to tables having a multiple-field primary
73
• The second normal form is usually applied to tables having a multiple-field primary
key.
Do example
Applaying normalization techniques
The third normal form
Normalize tables
• The third normal form or 3NF is a rule that is applied to tables in the second normal
form to remove any transitive dependency. That is, no non-key field should be
dependent on another non-key field in a table in the third normal form.
• The third normal form is usually applied to tables with single field primary keys. The
presence of repeated values in non-key fields is an indication that the table is not in
the third normal form.
74
the third normal form.
Applaying normalization techniques
The Boyce-codd normal form
Normalize tables
• The Boyce-Codd normal form (BCNF) is a type of the third normal form applied to
tables with multiple-field primary keys.
• In BCNF, tables with multiple-field primary keys do not have any non-key fields. If
75
• In BCNF, tables with multiple-field primary keys do not have any non-key fields. If
there are any non-key fields that do not add to the uniqueness of a record, then such
fields are moved to another table.
• The non-key field in the non-BCNF table allows for logical inconsistencies.
• This is a rigid form of the third normal form. Not all third normal form tables meet
the Boyce-Codd requirement.
Applaying normalization techniques
The higher normal forms
Normalize tables
• A higher normal form is a set of rules applied to tables in the third normal form to
prevent blank or multiple values in fields.
76
prevent blank or multiple values in fields.
• When a table has a field that does not apply to many records, then it results in blank
values.
• Multiple values for a field are usually seen in tables in BCNF.
Applaying normalization techniques
The higher normal forms
Normalize tables
Higher normal forms are the fourth, fifth, and domain/key normal forms :
• Fourth normal forms ensure that fields do not contain null or multiple values and
• Fifth normal forms prevent any redundant non-key fields in a table.
77
• Fifth normal forms prevent any redundant non-key fields in a table.
• A domain/key normal form or DKNF is a set of rules that require that the database
should contain only domain constraints and key constraints. Domain constraint
specifies the set of permissible values for an attribute.
Applaying normalization techniques
Quiz
Normalize tables
78
Applaying normalization techniques
Quiz
Normalize tables
79
Applaying normalization techniques
Quiz
Normalize tables
80
Applaying normalization techniques
Quiz
Normalize tables
81
Applaying normalization techniques
Quiz
Normalize tables
82
Applaying normalization techniques
Quiz
Normalize tables
83
Applaying normalization techniques
Quiz
Normalize tables
84
Applaying normalization techniques
Quiz
Normalize tables
85
Applaying normalization techniques
Quiz
Normalize tables
86
Applaying normalization techniques
Denormalization
Denormalize tables
• Denormalization is the process of allowing controlled redundancy in tables to
improve query performance. When the normalization process splits a table into two
87
improve query performance. When the normalization process splits a table into two
and a database designer wants to combine the tables for performance reasons, the
tables are denormalized.
Applaying normalization techniques
Why Denormalizing ?
Denormalize tables
• Designers choose to denormalize tables for many reasons, such as :
1. to keep similar fields together,
2. to keep table structures simple,
3. to allow null value fields in tables,
88
3. to allow null value fields in tables,
4. to reduce joins, to avoid one-to-one relationships,
5. to reduce input-output overheads,
6. or to add calculated fields to tables to avoid complex algorithms.
• Denormalizing tables will prevent fragmenting the tables in a database, thereby
reducing the input-output overheads while creating reports.
Applaying normalization techniques
How to Denormalize tables
Denormalize tables
89
Applaying normalization techniques
Quiz
Denormalize tables
90
Applaying normalization techniques
Quiz
Denormalize tables
91
Applaying normalization techniques
Laboratory
Laboratory
92
Explore the MySQL RDBMS
Objectives : In this lesson, you will be introduced to
MySQL RDBMS
Explore the MySQL RDBMS
93
MySQL
Explore the MySQL RDBMS
MySQL is a Relational Database Management System (RDBMS) developed and
distributed by Sun Microsystems. It enables you to store, retrieve, manage, organize, and
share your data optimally. Using MySQL, you can :
Explore the MySQL RDBMS
94
MySQL users
Explore the MySQL RDBMS
• MySQL consists of various levels of users. Users may use MySQL for performing
transactions, developing an application, or writing efficient queries to recover data.
Based on usage, these users can be classified into three categories :
Explore the MySQL RDBMS
95
Based on usage, these users can be classified into three categories :
1. End user : Retrieves data and uses it by initiating transactions
2. DB Developer : Designs and develops applications
3. DBA : Administers and maintains a database management system.
MySQL command line client
Explore the MySQL RDBMS
MySQL Command Line Client is an application with a command line interface. It provides
DBAs, developers, and end users an interface to connect to or disconnect from the
MySQL server.
Explore the MySQL RDBMS
96
MySQL program categories
Explore the MySQL RDBMS
The MySQL Server has various program categories that enable you to operate a
database. These programs provide MySQL users with a graphical user interface.
Explore the MySQL RDBMS
97
MySQL program categories
Explore the MySQL RDBMS
The MySQL Server has various program categories that enable you to operate a
database. These programs provide MySQL users with a graphical user interface.
Explore the MySQL RDBMS
98
MySQL program categories
Explore the MySQL RDBMS
The MySQL Server has various program categories that enable you to operate a
database. These programs provide MySQL users with a graphical user interface.
Explore the MySQL RDBMS
99
MySQL program categories
Explore the MySQL RDBMS
The MySQL Server has various program categories that enable you to operate a
database. These programs provide MySQL users with a graphical user interface.
Explore the MySQL RDBMS
100
MySQL program categories
Explore the MySQL RDBMS
The MySQL Server has various program categories that enable you to operate a
database. These programs provide MySQL users with a graphical user interface.
Explore the MySQL RDBMS
101
MySQL program categories
Explore the MySQL RDBMS
The MySQL Server has various program categories that enable you to operate a
database. These programs provide MySQL users with a graphical user interface.
Explore the MySQL RDBMS
102
Explore the MySQL RDBMS
Laboratory
103
Demonstration
Introduction
Introduction
Databases are designed to store a wide variety of organizational information. To use this
information, you first need to access the database. To do this, you must be familiar with
language used to communicate with databases. Writing a simple instruction using a
language that the database understands will enable you to access the required
information.
Using the SQL Commands to Work with Tables
104
Structured Query Language
Structured Query Language
• Structured Query Language (SQL) is a computer language used to communicate with
a database.
• SQL consists of instructions that can be used to retrieve and delete information from
a database, and also to modify information in a database.
• SQL consists of three major language components:
1. Data Definition Language (DDL),
Using the SQL Commands to Work with Tables
105
1. Data Definition Language (DDL),
2. Data Manipulation Language (DML), and
3. Data Control Language (DCL).
Structured Query Language
Structured Query Language
• DDL is used to define a database. It includes clauses to create and eliminate tables
and views. This portion of the language is generally used by database designers.
• DML is used to modify and manipulate data within a database. DML includes
commands to update and insert data in a database, and select and delete data from
Using the SQL Commands to Work with Tables
106
commands to update and insert data in a database, and select and delete data from
a database. This portion of the language is generally used by developers
• DCL is used to control access of various users to the database. It includes commands
to specify users who are allowed to access database objects, or restricted from
accessing database objects. This portion of the language is generally used by DBAs.
Queries
Structured Query Language
A query is an instruction set that requests information from the tables present in a
database.
Using the SQL Commands to Work with Tables
107
Subqueries
Structured Query Language
• A subquery, also known as an inner query, is a query that is contained within another
query. The query that contains the subquery is known as the outer query.
• A subquery is used when the value needed by the outer query's condition is unknown.
Using the SQL Commands to Work with Tables
108
Data types
Structured Query Language
A data type is a classification of data into groups based on its characteristics. The
characteristics may include the number of characters that a value can contain, the kind
Using the SQL Commands to Work with Tables
109
characteristics may include the number of characters that a value can contain, the kind
of value it is–text or numeric, the presence of any decimal value, and the representation
of date and time value.
Data types
Structured Query LanguageUsing the SQL Commands to Work with Tables
110
Data types
Structured Query LanguageUsing the SQL Commands to Work with Tables
111
Data types
Structured Query LanguageUsing the SQL Commands to Work with Tables
112
SQL Operators
Structured Query LanguageUsing the SQL Commands to Work with Tables
113
SQL Operators
Structured Query LanguageUsing the SQL Commands to Work with Tables
114
SQL Operators
Structured Query LanguageUsing the SQL Commands to Work with Tables
115
SQL Operators
Structured Query LanguageUsing the SQL Commands to Work with Tables
116
SQL Operators
Structured Query LanguageUsing the SQL Commands to Work with Tables
117
Creat statement
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
• CREATE is a SQL statement that enables creation of an object including a
database, table, view, or indexes inside an RDBMS. The CREATE keyword is always
followed by a database, view, table, or index name. This name is then followed by a
data field, data type, and constrains if any.
• The TEMPORARY keyword allows a table to be visible only to the current
118
• The TEMPORARY keyword allows a table to be visible only to the current
connection. Once the connection is dropped, the table automatically drops.
Alter statement
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
The ALTER statement enables you to perform data modifications in an existing
database or database objects. It allows you to change an existing table structure by
performing various operations, such as adding or deleting columns, creating or
119
performing various operations, such as adding or deleting columns, creating or
destroying indexes, and changing the current types of the columns.
Various types of data modification can be performed using the ALTER statement.
Alter command
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
120
Drop command
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
The DROP statement is a SQL statement that enables you to remove one or more
database objects that includes a database, table, view, or indexes inside an RDBMS.
The TEMPORARY keyword allows you to drop temporary tables but does not check the
access rights or end an ongoing transaction. The IF EXISTS clause prevents an error from
occurring for tables that do not exist.
121
occurring for tables that do not exist.
Describe command
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
The DESCRIBE statement is a SQL statement that is used to extract information about
columns in a table.
The syntax for the DESCRIBE statement is: {DESCRIBE | DESC} tbl_name [col_name |
wildcard]
In this syntax, col_name refers to the column name and wildcard defines a string
122
In this syntax, col_name refers to the column name and wildcard defines a string
containing SQL “%” and “_” wildcard characters.
Help statement
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
The HELP statement is a SQL statement that is used to access and display online
information from the MySQL manual.
123
information from the MySQL manual.
The syntax for this statement is: HELP 'search_string'. The search_string is case
insensitive and may include details such as content to be searched for or specific
keywords.
USE statement
Creat tables using DDL commandsUsing the SQL Commands to Work with Tables
The USE statement is a SQL statement that instructs MySQL to use a specific database as
its default database. This database remains as the default database until the end of a
124
its default database. This database remains as the default database until the end of a
session or until another USE statement is issued. The syntax for the USE statement is:
USE db_name
Select statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
• The SELECT statement is a SQL statement used to retrieve information from a
database. The SELECT statement is composed of two parts
1. a SELECT clause that includes all the column names that are required in the
output, and
2. a FROM clause that contains the table name containing the columns. Additional
clauses can be added to the SELECT statement if necessary.
125
clauses can be added to the SELECT statement if necessary.
• When all the columns of a table are required in the output, an asterisk (*) can be
used instead of column names.
Optional clause of select statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
The WHERE Clause
126
The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Comparison operator
Modify data using DML commandsUsing the SQL Commands to Work with Tables
127
Joins
Modify data using DML commandsUsing the SQL Commands to Work with Tables
• A join is a query that is used to combine values in two or more tables in a
relational database.
• It results in a temporary table called the joined table. A join connects tables by
using their key fields.
128
Joins
Modify data using DML commandsUsing the SQL Commands to Work with Tables
Joins are broadly classified into two categories, inner joins and outer joins.
129
Group by
Modify data using DML commandsUsing the SQL Commands to Work with Tables
GROUP BY is a clause used to select multiple columns from a table such that there
appears at least one arithmetic operation in the SELECT statement. It is used with
functions that perform specific actions on entire columns of data in a single query
and ignores NULL values unless otherwise stated.
130
SELECT SU_Suppliers_SupplierID, SUM(OR_OrderQty) FROM
piimt.orders o GROUP BY SU_Suppliers_SupplierID;
Explain statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
The EXPLAIN statement is a SQL statement that is used to extract specific
information. You can use the EXPLAIN statement to either extract information
about the structure of a table or collect information about how MySQL executes a
SELECT statement by preceding the SELECT statement with the EXPLAIN keyword.
131
EXPLAIN SELECT SU_Suppliers_SupplierID, SUM(OR_OrderQty) FROM piimt.orders o
GROUP BY SU_Suppliers_SupplierID;
Insert statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
The INSERT statement allows you to create one or more rows in a table by
specifying the actual values of the row or by subquerying. It also allows null values,
but if the column contains the not-null constraint, it returns an error message.
The INSERT keyword inserts new rows to the existing table, INSERT ... VALUE
inserts rows based on the explicit values specified during table creation.
132
inserts rows based on the explicit values specified during table creation.
INSERT INTO Suppliers
(SU_SupplierID,SU_SupplierFirstName,SU_SupplierLastName,SU_SupplierAddr
ess1,SU_SupplierCity,SU_SupplierAddress2,SU_SupplierContactNumber,
SU_SupplierStatus) VALUES ('187','Imade','BENELALLAM','7035 Auctor,
Lane','Carson City','NV','775-555-6905','PR');
Update statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
The UPDATE statement is used to modify existing data in a database. The SET
clause is used to assign new values to the columns of a table. Like other DML
statements, this statement also uses the COMMIT statement at the end of the
query to make permanent changes to the data and prevent the rolling back of data
in case of any network failure.
133
UPDATE Suppliers SET SU_SupplierCity='Rabat' WHERE
SU_SupplierID='187';
Replace statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
The REPLACE statement is used to insert new rows to an existing table. If the
primary key value of the old row in the existing table is the same as the value in
the new row, the old row is deleted before the new row is inserted. Therefore, this
statement either inserts a row, or deletes existing data from a row and updates it
with new values in a table.
134
Delete statement
Modify data using DML commandsUsing the SQL Commands to Work with Tables
The DELETE statement is used to remove data from a table. The DELETE statement
uses a few optional clauses such as WHERE and ORDER BY. The WHERE clause
allows you to delete specific columns and ORDER BY allows you to delete rows in a
specific order. However, if the WHERE clause is not used, all the rows will be
removed from the table.
135
DELETE FROM Suppliers WHERE SU_SupplierID='187';
Laboratory
LaboratoryUsing the SQL Commands to Work with Tables
Scenario
OGC books department wants to hire a few people on contract for a short period to
meet some urgent resource requirements. The store manager wants to store
information such as contract ID, first name, last name, and salary of contractors in the
“contractors” table. You have to ensure that each record in the table is unique, and the
table should be created based on the following requirements.
136
table should be created based on the following requirements.
• contID VARCHAR(5) NOT NULL
• firstname VARCHAR(10) NOT NULL
• lastname VARCHAR(10) NOT NULL
• sal INT NOT NULL
Steps
1. Create the “contractors” table with the specified fields, and view information
on the created table structure.
2. Add a constraint to ensure the uniqueness of each record in the table.