Unit 3
Unit 3
It is freely available open source Relational Database Management System (RDBMS) that uses Structured Query
Language(SQL). In MySQL database , information is stored in Tables. A single MySQL database can contain many
tables at once and store thousands of individual records.
SQL is a language that enables you to create and operate on relational databases, which are sets of related
information stored in tables.
A data model refers to a set of concepts to describe the structure of a database, and certain constraints (restrictions)
that the database should obey. The four data model that are used for database management are :
1. Relational data model : In this data model, the data is organized into tables (i.e. rows and columns). These
tables are called relations.
2. Hierarchical data model 3. Network data model 4. Object Oriented data model
6. Primary Key : This refers to a set of one or more attributes that can uniquely identify tuples within the relation.
7. Candidate Key : All attribute combinations inside a relation that can serve as primary key are candidate keys as
these are candidates for primary key position.
8. Alternate Key : A candidate key that is not primary key, is called an alternate key.
9. Foreign Key : A non-key attribute, whose values are derived from the primary key of some other table, is
known as foreign key in its current table.
REFERENTIAL INTEGRITY
- A referential integrity is a system of rules that a DBMS uses to ensure that relationships between records in
related tables are valid, and that users don’t accidentally delete or change related data. This integrity is
ensured by foreign key.
MySQL ELEMENTS
LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example,
‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal point
e.g. 17 is an integer literal but 17.0 and 17.5 are real literals.
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it. MySQL data
types are divided into three categories:
➢
Numeric
➢
Date and time
➢
String types
DATABASE COMMNADS
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS)
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
- To insert value NULL in a specific column, we can type NULL without quotes and NULL will be inserted in that
column. E.g. in order to insert NULL value in ENAME column of above table, we write INSERT command as :
e.g.
In order to retrieve everything from Employee table, we write SELECT command as :
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965
DISTINCT(GENDER)
M
F
e.g. to display ECODE, ENAME and GRADE of those employees whose salary is between 40000 and 50000,
command is:
SELECT ECODE , ENAME ,GRADE
FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
- The NOT IN operator finds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command is :
SELECT ENAME
FROM EMPLOYEE
WHERE ENAME LIKE ‘R%’ ;
Output will be :
ENAME
Ravi
Ruby
Output will be :
Output will be :
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use command :
SELECT *
FROM EMPLOYEE
ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM EMPLOYEE
WHERE GROSS > 40000
ORDER BY ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE
SET GROSS = 55000
WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for those employee whose employee code is 1001.
UPDATE EMPLOYEE
SET GROSS = 58000, GRADE=’B2’
WHERE ECODE = 1009 ;
OTHER EXAMPLES
e.g.1. Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
SET GROSS = GROSS +100 ;
e.g.2. Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE
SET GROSS = GROSS * 2 ;
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
e.g.3. Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted. Thus
above line will delete all rows from employee table.
DROPPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP TABLE command is :
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands can be given on that table.
After this command is executed, all the data in the table along with table structure will be deleted.
To add a column to a table, ALTER TABLE command can be used as per following syntax:
However if you specify NOT NULL constraint while adding a new column, MySQL adds the new column with the
default value of that datatype e.g. for INT type it will add 0 , for CHAR types, it will add a space, and so on.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1 A
2 G
Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testt ADD col6 VARCHAR(3);
MODIFYING COLUMNS
Column name and data type of column can be changed as per following syntax :
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following form :
❖
TO ADD PRIMARY KEY CONSTRAINT
ALTER TABLE <table name>
ADD PRIMARY KEY (Column name);
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE
ADD PRIMARY KEY (ECODE) ;
❖
TO ADD FOREIGN KEY CONSTRAINT
REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP PRIMARY KEY ;
- To remove foreign key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP FOREIGN KEY ;
ENABLING/DISABLING CONSTRAINTS
Only foreign key can be disabled/enabled in MySQL.
To disable foreign keys : SET FOREIGN_KEY_CHECKS = 0 ;
To enable foreign keys : SET FOREIGN_KEY_CHECKS = 1 ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
- A constraint is a condition or check applicable on a field(column) or set of fields(columns).
- Common types of constraints include :
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.
DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not
provide a specific value. E.g.
UNIQUE CONSTRAINT
- The UNIQUE constraint ensures that all values in a column are distinct. In other words, no two rows can
hold the same value for a column with UNIQUE constraint.
e.g.
CREATE TABLE Customer
( SID integer Unique ,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;
Column SID has a unique constraint, and hence cannot include duplicate values. So, if the table already
contains the following rows :
CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the table will
only insert a new row or update an existing row if the new value satisfies the CHECK constraint.
e.g.
CREATE TABLE Customer
( SID integer CHECK (SID > 0),
Last_Name varchar(30) ,
First_Name varchar(30) ) ;
will result in an error because the values for SID must be greater than 0.
- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY. e.g.
Or
CREATE TABLE Customer
( SID integer,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (SID) ) ;
- The latter way is useful if you want to specify a composite primary key, e.g.
e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
1 ABC XI Primary key
2 DEF XII
3 XYZ XI Child Table
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from
Primary key (ROLL_NO) of STUDENT table.(Parent Key).
REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the parent table.
Referencing action with ON UPDATE clause determines what to do in case of a UPDATE occurs in the parent table.
Actions:
1. CASCADE : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
automatically delete or update the matching rows in the child table i.e., cascade the action to child table.
2. SET NULL : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
set the foreign key column in the child table to NULL.
3. NO ACTION : Any attempt for DELETE or UPDATE in parent table is not allowed.
4. RESTRICT : This action rejects the DELETE or UPDATE operation for the parent table.
Table : EMPL
1. AVG( )
This function computes the average of given
data. e.g. SELECT AVG(SAL)
FROM EMPL ;
Output
AVG(SAL)
6051.6
2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where COLUMN
is not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
3. MAX( )
This function returns the maximum value from a given column or expression.
5. SUM( )
This function returns the sum of values in given column or expression.
Output
SUM(SAL)
30258
** One thing that you should keep in mind is that while grouping , you should include only those values in the SELECT list
that either have the same value for a group or contain a group(aggregate) function. Like in e.g. 2 given above, DEPTNO
column has one(same) value for a group and the other expression SUM(SAL) contains a group function.
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiple fields in the GROUP BY
expression. e.g. To group records job wise within Deptno wise, you need to issue a query statement like :
DATABASE TRANSACTIONS
TRANSACTION
A Transaction is a logical unit of work that must succeed or fail in its entirety. This statement means that a
transaction may involve many sub steps, which should either all be carried out successfully or all be ignored if
some failure occurs. A Transaction is an atomic operation which may not be divided into smaller operations.
Example of a Transaction
Begin transaction
Get balance from account X
Calculate new balance as X – 1000
Store new balance into database file
Get balance from account Y
Calculate new balance as Y + 1000
Store new balance into database file
End transaction
TRANSACTION CONTROL COMMANDS (TCL)
The TCL of MySQL consists of following commands:
• Tables: The fundamental building blocks, storing data in rows (tuples) and columns (attributes). Each column has
a specific data type.
• Rows (Tuples): Represent individual records, with each cell containing a value for a corresponding attribute.
• Columns (Attributes): Represent named characteristics of entities stored in the table.
• Primary Key: Uniquely identifies each row within a table and enforces entity integrity.
Example:
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
phone_number VARCHAR(20)
);
Set Operations:
• UNION: Combines rows from two tables, eliminating duplicates based on the selected columns.
• INTERSECT: Returns rows common to both tables, based on the selected columns.
• EXCEPT: Returns rows from one table that are not present in the other, based on the selected columns.
Example:
SQL
SELECT * FROM Customers UNION SELECT * FROM Orders;
Aggregate Functions:
• COUNT: Number of rows in a table or satisfying a condition.
• SUM: Sum of values in a numeric column.
• AVG: Average of values in a numeric column.
• MIN/MAX: Minimum and maximum values in a column.
Example:
SQL
SELECT COUNT(*) FROM Customers;
SELECT AVG(salary) FROM Employees;
Null Values:
• Represent the absence of a known value or inapplicable information.
• Treated differently by operations and functions, impacting results.
• Can be handled using IS NULL and IS NOT NULL operators.
Example:
SELECT * FROM Customers WHERE email IS NULL;
UPDATE Customers SET phone_number = NULL WHERE phone_number = '';
Domain Constraints:
• Restrict the values allowed in a column to maintain data integrity.
• Defined using CHECK constraints with SQL.
• Example: CHECK (age >= 18)
Referential Integrity Constraints:
• Enforce relationships between tables by linking foreign keys to primary keys.
• Prevent orphaned or dangling references.
• Defined using FOREIGN KEY constraints with SQL.
• Example: FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
Assertions:
• More flexible constraints to enforce database rules beyond primary and foreign keys.
• Defined using CREATE ASSERTION in SQL.
• Example: CREATE ASSERTION no_negative_salaries CHECK (salary >= 0);
Views:
• Virtual tables defined by a query, presenting a subset or transformation of real tables.
• Simplify complex queries or provide restricted access to data.
• Created using CREATE VIEW in SQL.
• Example: CREATE VIEW ActiveCustomers AS SELECT * FROM Customers WHERE active = TRUE;
Nested Subqueries:
• Inner queries embedded within other queries to retrieve data based on conditions.
• More complex than using joins in some cases.
• Example: SELECT * FROM Customers WHERE customer_id IN (SELECT customer_id FROM Orders WHERE
order_date > '2023-01-01');
Stored Procedures:
• Definition: Stored procedures are precompiled sets of SQL statements grouped together and stored in the database
under a specific name. They act as modular units of code that can be executed repeatedly, reducing redundancy and
complexity.
• Execution: They are explicitly invoked by an application or user using commands like EXECUTE or the procedure name
itself.
• Benefits:
o Reduced network traffic: By sending the entire procedure code once, instead of individual SQL statements, you
minimize data transfer between the application and database server.
o Encapsulation of complex logic: Code becomes reusable and easier to maintain, as complex operations are
stored in one place.
o Improved security: Procedures can enforce data access rules and business logic within the database, potentially
enhancing security.
o Parameterized queries: Allow passing input values, making procedures adaptable to different scenarios.
o Error handling: Can include error checking and handling mechanisms to improve application robustness.
Example:
SELECT total;
END;
This procedure calculates the total amount for an order with a given ID. It accepts an order_id parameter, retrieves
relevant data from the order_items table, calculates the total, and returns the result.
Triggers:
• Definition: Triggers are special database objects that automatically execute predefined SQL statements or PL/SQL code
when specific events occur within a table or database (like INSERT, UPDATE, DELETE).
• Execution: They are triggered automatically based on the defined event, without explicit user intervention.
• Benefits:
o Enforcing data integrity: Can maintain referential integrity and data consistency by automatically performing
actions when data changes.
o Implementing business rules: Can execute logic when certain conditions are met, ensuring compliance with
business rules.
o Auditing database changes: Can log details of data modifications for tracking and analysis.
Example:
This trigger updates the stock level of a product whenever an order item is updated (after the update occurs). It
ensures that the product stock reflects the change in order quantity.
Key Differences:
Return values Can return values using SELECT statements Cannot return values
Can commit or rollback changes within the Usually inherit transaction context of
Transactions
procedure triggering event
Database security is a critical aspect of application development, and SQL (Structured Query Language) plays a central role in
managing and securing databases. Below are key considerations and examples for developing a secure database application
using SQL:
Explanation:
• Grant specific privileges (e.g., SELECT, INSERT, UPDATE, DELETE) to the user on specific tables.
2. Encryption:
• Explanation:
• Use SQL encryption functions to encrypt sensitive data, such as credit card numbers, within the
database.
3. Audit Trails:
CREATE TRIGGER audit_trigger BEFORE INSERT ON employees FOR EACH ROW INSERT INTO audit_log VALUES (NEW.id,
NEW.name, NOW(), 'INSERT');
• Explanation:
• Implement triggers to log changes in the database, such as inserts, updates, or deletes, to an audit log
for security analysis.
$query = "SELECT * FROM users WHERE username = :username AND password = :password"; $stmt = $pdo->prepare($query);
$stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); $stmt->execute();
• Explanation:
• Use parameterized queries or prepared statements to prevent SQL injection attacks by separating SQL
code from user input.
• Explanation:
• Assign the minimum required privileges to database roles and users to follow the principle of least
privilege.
• Explanation:
• Regularly update and patch the database system to ensure that security vulnerabilities are addressed.
7. Secure Connection:
• Explanation:
• Explanation:
• Regularly backup the database to prevent data loss and plan for recovery in case of security incidents.
Important Questions:
1. Explain the concept of referential integrity in MySQL. How does the use of foreign keys ensure referential integrity in a
relational database?
2. Describe the difference between the CHAR and VARCHAR data types in MySQL. Provide examples to illustrate their
usage and scenarios where one would be preferred over the other.
3. Discuss the various types of SQL statements and their classifications. Provide examples for each type of SQL
statement.
4. How can you add a new column to an existing table in MySQL using the ALTER TABLE command? Provide syntax and
an example.
5. Explain the significance of the SELECT statement in SQL. Discuss its various applications, including selecting specific
columns, filtering rows based on conditions, and sorting the results. Provide examples for each case.
6. Explain the importance of constraints in a relational database. Provide examples of different types of constraints and
their functionalities.
7. Compare and contrast the roles of primary keys and unique keys in a database table. Provide scenarios where each
type of key would be appropriate to use.
8. Discuss the differences between the ALTER command and the UPDATE command in SQL. Provide examples of when
each command would be used and how they affect the database structure or data.
9. Describe the role of aggregate functions in SQL. Provide examples of aggregate functions and explain how they are
used to analyze data in a database.
10. Explain the concept of transactions in a database management system. Discuss the importance of transaction control
commands (TCL) and provide examples of their usage in maintaining data integrity.
11. Discuss the basic structure of relational databases, including tables, rows, columns, and primary keys. Provide
examples to illustrate each component.
12. Explain the set operations UNION, INTERSECT, and EXCEPT in SQL. Provide examples of how these operations are used
to combine or compare data from multiple tables.
13. Describe the concept of null values in a database and how they are handled in SQL queries. Discuss the implications of
null values on data analysis and integrity.
14. Explain domain constraints and referential integrity constraints in a database. Provide examples of how these
constraints are defined and enforced in SQL.
15. Discuss the role of assertions in maintaining data integrity in a database. Provide examples of assertions and explain
how they are used to enforce database rules.