0% found this document useful (0 votes)
19 views

DBMS_Notes3

Uploaded by

shijingeorge3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

DBMS_Notes3

Uploaded by

shijingeorge3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

DATABASE SYSTEMS FYCS Sem I Unit 3

DBMS – MYSQL
Constraints

• MySQL CONSTRAINT is used to define rules to allow or restrict what values can be stored in
columns. The purpose of inducing constraints is to enforce the integrity of a database.
• MySQL CONSTRAINTS are used to limit the type of data that can be inserted into a table.
1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an attribute.
NOT NULL - allows to specify that a column can not contain any NULL value.
DEFAULT - In a MySQL table, each column must contain a value ( including a NULL). While inserting data
into a table, if no value is supplied to a column, then the column gets the value set as DEFAULT.

2. Entity integrity constraints


PRIMARY KEY - A PRIMARY KEY constraint for a table enforces the table to accept unique data for a
specific column and this constraint creates a unique index for accessing the table faster.
UNIQUE - The UNIQUE constraint in MySQL does not allow to insert a duplicate value in a column.

3. Referential Integrity Constraints


o A referential integrity constraint is specified between two tables.
o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of
Table 2, then every value of the Foreign Key in Table 1 must be null or be available in Table 2.
FOREIGN KEY - A FOREIGN KEY in MySQL creates a link between two tables by one specific column of
both tables

Backup and Restore MySQL Database


One important task of a database administrator is to regularly backup the database. Then if the
database ever becomes corrupted, the database administrator can use the backup files to restore the
database.

It is important to make regular backups of all data in case of loss. Database recovery is the process of
restoring the database to original state as it was before database failure occurs.
mysqldump is an effective tool to backup MySQL database. It creates a *.sql file.
# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql
When you are restoring the dumpfilename.sql on a remote database, make sure to create the database
before you can perform the restore.
# mysql -u root -p[root_password] [database_name] < dumpfilename.sql

SELECT statement
The SQL SELECT command is used to fetch data from the MySQL database. The SELECT statement
controls which columns and rows that you want to see. Syntax is

1 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

SELECT [ALL/DISTINCT] column1,column2,... FROM tablename [WHERE Clause] [LIMIT n]


You can specify star (*) in place of fields. In this case, SELECT will return all the fields. You can specify any
condition using the WHERE clause. You can limit the number of returns using the LIMIT attribute.
The SELECT DISTINCT statement is used to return only distinct (different) values.

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');

The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND operator displays a record if all the conditions separated by AND are TRUE.

The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.

SELECT * FROM Customers ORDER BY Country;

A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value. To test for NULL values we will have to
use the IS NULL and IS NOT NULL operators

The GROUP BY statement groups rows that have the same values into summary rows, like "find the
number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to
group the result

SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;

The HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or
aggregates. The HAVING clause is often used with the GROUP BY clause to filter groups based on a

2 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

specified condition. It is similar to the WHERE clause. The HAVING clause was added to SQL because the
WHERE keyword can not be used with aggregate functions.

SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country


HAVING COUNT(CustomerID) > 5;

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

• % - The percent sign represents zero, one, or multiple characters


• _ - The underscore represents a single character

WHERE CustomerName LIKE 'a%' - Finds any values that start with "a"

WHERE CustomerName LIKE '%a' - Finds any values that end with "a"

WHERE CustomerName LIKE '_r%' - Finds any values that have "r" in the second position

Aggregate Functions

By definition, an aggregate function performs a calculation on a set of values and returns a single
value. MySQL provides many aggregate functions that include AVG , COUNT , SUM , MIN , MAX , etc.
An aggregate function ignores NULL values when it performs calculation except for the COUNT function.

• The COUNT() function returns the number of rows that matches a specified criteria.
SELECT COUNT(ProductID) FROM Products;
• The AVG() function returns the average value of a numeric column.
• The SUM() function returns the total sum of a numeric column.

SELECT AVG(Price) FROM Products;

SELECT SUM(Quantity) FROM OrderDetails;

• The MIN() function returns the smallest value of the selected column.
• The MAX() function returns the largest value of the selected column.

SELECT MIN(Price) AS SmallestPrice FROM Products;

SELECT MAX(Price) AS LargestPrice FROM Products;

Date Functions

NOW(): Returns the current date and time. Example:


SELECT NOW();
CURDATE(): Returns the current date. Example:

3 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

SELECT CURDATE();
CURTIME(): Returns the current time. Example:
SELECT CURTIME();
DATE_ADD() : Adds a specified time interval to a date
DATE_ADD(date, INTERVAL expr type);
SELECT Name, DATE_ADD(BirthTime, INTERVAL 1 YEAR) from test;

DATEDIFF(): Returns the number of days between two dates

SELECT DATE_DIFF('2017-01-13','2017-01-03') AS DateDiff;

MySQL string functions

• CONCAT – combine two or more strings into one string.


• LENGTH - get the length of strings in bytes and in characters.
• LEFT – get the left part of a string with a specified length.
• REPLACE – search and replaces a substring in a string.
• SUBSTRING – extract a substring starting from a position with a specific length.
• TRIM – remove unwanted characters from a string.
• STRCMP – compares 2 strings, returns 0 if both are equal, -1 if first string smaller, 1 otherwise

MySQL Math functions

• ABS – return the absolute value of a number.


• CEIL – return the smallest integer value greater than or equal to the input number.
• FLOOR – return the largest integer value not greater than the argument.
• MOD – return the remainder of a number divided by another.
• ROUND – rounds a number to a specified number of decimal places.
• TRUNCATE – truncate a number to a specified number of decimal places.
• POW(n,m) – returns n raised to m
• SQRT(n) – returns square root

Join
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

4 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

The different types of the JOINs in SQL:

• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the
right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from
the left table

SubQueries

In MySQL, a subquery is a query within a query. You can create subqueries within your SQL statements.
A sub query is a select query that is contained inside another query. The inner select query is usually
used to determine the results of the outer select query.

SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );

Types of Subqueries

1) A scalar subquery is a subquery that returns exactly one column value from one row.
2) An independent subquery is the subquery that return at most one value. SQL then compares the
value that results from the subquery with the value on the other side of the comparison
operator.
SELECT employee_id,name,salary
FROM employees WHERE salary >
(SELECT AVG(SALARY) FROM employees);

3) Multiple row subquery is the one that returns more than one row
4) A correlated subquery is a subquery that contains a reference to a table (in the parent query) that
also appears in the inner query. A correlated subquery is evaluated once for each row in outer
query

5 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

SELECT name, salary, department_id FROM employees out


WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = out.department_id);

EXISTS , Any, ALL clauses


The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records.
SELECT SupplierName FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);

The ANY operator returns true if any of the subquery values meet the condition.

The ALL operator returns true if all of the subquery values meet the condition.

SELECT ProductName FROM Products


WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

SELECT ProductName FROM Products


WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

Types of threats to database security

1. Privilege abuse: When database users are provided with privileges that exceeds their day-to-day job
requirement, these privileges may be misused intentionally or unintentionally.

2. Operating System vulnerabilities: Vulnerabilities in underlying operating systems like Windows, UNIX,
Linux, etc., and the services that are related to the databases could lead to unauthorized access.

3.Weak authentication: Weak authentication models allow attackers to employ strategies such as to
obtain database login credentials and assume the identity of legitimate database users.

4. Input Injection (SQL Injection)


This type of attack allows an attacker to inject code into a program or query or inject malware onto a
computer in order to execute remote commands that can read or modify a database, or change data on
a web site.

5. Unavailability of data : authorized users must be able to access data at any time

Security Mechanisms

• A DBMS system always has a separate system for security which is responsible for protecting
database against accidental or intentional loss, destruction or misuse.
• Security Mechanisms:

o Access Control(Authorization) -Each application is associated with a specified role. Each


role has a list of authorized users who may execute/Design/administers the application.

6 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

o Authenticate the User:This may be done with help of concept of views in Relational
databases.

o Cryptographic control/Data Encryption -Encode data in a cryptic form(Coded)so that


although data is captured by unintentional user still he can’t be able to decode the data.

o Inference control - Prevent disclosure of data through statistical summaries of


confidential data.

o Physical Protection: Computer systems must be physically secured against any


unauthorized entry.
o Virus control: There should be mechanism for providing protection against data virus.

• Granting of privileges:

o A system privilege is the right to perform a particular action, or to perform an action on


any schema objects of a particular type.
o An authorized user may pass on this authorization to other users. This process is called
as granting of privileges.

Role of a Database Administrator (DBA)

A Database Administrator is a person or a group of person who are responsible for managing all the
activities related to database system. This job requires a high level of expertise.

Responsibilities of database Administrator( DBA)

1. Deciding the hardware device


Depending upon the cost, performance and efficiency of the hardware, it is DBA who have the duty of
deciding which hardware devise will suit the company requirement.
2. Installing and Configuration of database: DBA is responsible for installing the database software. He
configure the software of database and then upgrades it if needed.

3. Managing Data Integrity


Data integrity should be managed accurately because it protects the data from unauthorized use. DBA
manages relationship between the data to maintain data consistency.

4. Decides Data Recovery and Back up method


If any company is having a big database, then it is likely to happen that database may fail at any
instance. It is require that a DBA takes backup of entire database in regular time span. DBA has to decide
that how much data should be backed up and how frequently the back should be taken.

7 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

5. Tuning Database Performance


Database performance plays an important role for any business. If user is not able to fetch data speedily
then it may loss company business.

6. Database design
The logical design of the database is designed by the DBA. Also a DBA is responsible for physical design,
external model design, and integrity control.
8. Decides validation checks on data
9. Monitoring performance
10. Provides help and support to user

Views

In SQL, a view is a virtual table based on the result-set of an SQL statement.

By virtual, we mean, the tables do not store any data of their own but display data stored in other tables
referenced in the SELECT statement.

Views improve security of the database by showing only intended data to authorized users. They hide
sensitive data.

Views make life easy as you do not have write complex queries time and again.

It's possible to use INSERT, UPDATE and DELETE on a VIEW. These operations will change the underlying
tables of the VIEW.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.

CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name


WHERE condition;
A view can be updated with the CREATE OR REPLACE VIEW command.
CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ... FROM table_name
WHERE condition;
A view is deleted with the DROP VIEW command.
DROP VIEW view_name;

DCL Commands
DCL(Data Control Language) : DCL includes commands such as GRANT and REVOKE which mainly deals
with the rights, permissions and other controls of the database system.
DCL is about security. DCL is used to control the database transaction.DCL statement allow you to
control who has access to specific object in your database.
Creating and Dropping Users

8 Bindy Wilson
DATABASE SYSTEMS FYCS Sem I Unit 3

The CREATE USER statement is used to create a database account that allows the user to log into the
MySQL database.
CREATE USER user_account IDENTIFIED BY password;
1. user_account: It is the name that the user wants to give to the database account.The
user_account should be in the format ‘username’@’hostname’
2. password:It is the password used to assign to the user_account.The password is specified in the
IDENTIFIED BY clause.

The “Show Grants” statement is used to view the permissions of a user account.

SHOW GRANTS FOR user-account;

The DROP USER statement in MySQL can be used to remove a user account along with its privileges
from the MySQL completely.But before using the drop user statement, the privileges of the user should
be revoked.

DROP USER 'user'@'host';

Privileges

A system privilege is the right to perform a particular action, or to perform an action on any schema
objects of a particular type.

An authorized user may pass on this authorization to other users. This process is called as granting of
privileges

GRANT and REVOKE

To grant privileges to a user account, the GRANT statement is used.

GRANT privileges_names ON object TO user;


privileges_name: These are the access rights or privileges granted to the user.

object:It is the name of the database object to which permissions are being granted. In the case of

granting privileges on a table, this would be the table name.
• user:It is the name of the user to whom the privileges would be granted.
GRANT SELECT, INSERT, UPDATE ON Emp TO ‘fycs’@’localhost’;

The Revoke statement is used to revoke some or all of the privileges which have been granted to a user
in the past.

REVOKE privileges ON object FROM user;


REVOKE UPDATE ON Emp FROM ‘fycs’@’localhost’;

9 Bindy Wilson

You might also like