Ch-7 MYSQL
Ch-7 MYSQL
MYSQL
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.
2. Hierarchical Data Model: In this model the data are represented by collection and relationship between data are
represented by links. In this model the collection of data are organized as tree.
3. Network Data Model: This is same as the hierarchical model but in this model the collection of data is organized
as arbitrary graphs.
4. Object Oriented Data Model: In this model the data and its operations are represented by objects.
2. Candidate Key
3. Alternate Key
4. Foreign Key
1. Primary Key: A primary key is a set of one or more attributes that can uniquely identify tuples within the relation.
This key does not have duplicate values in the relation. There must be any value for this key, it cannot be NULL.
2. Candidate Key: All attributes combination inside a relation that can serve as a primary key, is called candidate key.
3. Alternate Key: A candidate key that is not the primary key is called an alternate key.
4. 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.
INTRODUCTION TO MySQL-
3. Transaction Control Language (TCL) Commands that allow you to manage and control the transactions e.g.,
Creating save points
Rollback
Commit
4. Data control Language (DCL)- This language is used to control data and access to the databases. It is used for
protecting the data from unauthorized access.
GRANT
REVOKE
MySQL ELEMENTS
1. Literals 2. Data types 3. Nulls 4. Comments
1. 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.
2. 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
Numeric Data Type
int – used for number without decimal.
Decimal(m,d) – used for floating/real numbers. m denotes the total length of number and d is number
of decimal digits.
Float- Holds Number with decimal points. Each float value occupies 4 bytes.
Date and Time Data Type
date – used to store date in YYYY-MM-DD format.
time – used to store time in HH:MM:SS format.
String Data Types
char(n) – used to store a fixed length string. n denotes max. number of characters.
varchar(n) – used to store a variable length string. n denotes max. no. of characters.
Binary Data Type: Stores the data in binary objects, such as graphics, images, multimedia etc.
3. NULL values: If a column in a row has no value, then column is said to be null. NULLs can appear in a column if the
column is not restricted by NOT NULL or Primary Key. You should use a null value when the actual value is not
known. Null and Zero is not equivalent. Any arithmetic expression containing a null always evaluates to null.
Example: 7 + null = null
7+0=7 Difference between null and zero.
4. Comments: Comment is a text that is not executed. There are two types of comments that we use in MySQL.
(i) Single line Comment: Beginning with two hyphens (--) OR beginning with # symbol.
(ii) Multi Line Comment: /*……………………………………….. …………………………………….*/
DATABASE COMMNADS
VIEW EXISTING DATABASE
To view existing database names, the command is- SHOW DATABASES ;
6. VIEWING STRUCTURE OF A TABLE - If we want to know the structure of a table, we can use DESCRIBE or DESC
command, as per following syntax : DESCRIBE | DESC ; to view the structure of table EMPLOYEE,
command is : DESCRIBE EMPLOYEE ; OR DESC EMPLOYEE ;
7- Alter Table command- The alter table command is used to perform the following operation.
To add column to an existing table.
To add a column specific position.
To rename any existing column.
To change the data type of any column or to modify its size.
To remove or physically delete a column.
a) Add Column To An Existing Table. add a column to a table, ALTER TABLE command can be used as per following
syntax: ALTER TABLE ADD ; e.g. to add a new column Mob_no to the Student table, we can write command as :
b) Add a Column with default value- We can add the column with default value
c) Modifying an existing column definition- To change the data-type and size of the any column, we use the
MODIFY command.
Alter table Student Modify City varchar(25) ;
The above command will modify the data type size for the City field form 15 to 25 characters.
d) Renaming a column- The existing column in a relation can be renamed using Alter table command.
Alter table Student <old column name > <new column name > column definition;
e) Removing a column- To remove or drop a column in a table, Alter table command is used.
Alter table Student Drop State ;
Above command will drop state column from the Student table.
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
f) Adding and deleting Primary key constraints- by Alter table command add a primary key constraint on the
column Rollno in the table Student.
Alter table Student Add Primary Key Rollno ;
Note- make sure while using alter table command to add a primary key that the primary key column must be
declared with NOT NULL.
Delete Primary key constraints-
Alter table Student Drop Primary Key ;
After -
ALTER TABLE Student ADD LastName varchar(50) After Name ;
Rollno Name LastName Gender Marks DOB Mob_no
1 Raj kumar NULL M 50 2012-06-11 NULL
2 Deep singh NULL M 56 2001-08-12 NULL
8. DROP TABLE COMMAND- Drop table command is used to remove/delete a table permanently. If you drop a table
all the rows in the table are deleted along with its structure. Once a table is dropped we cannot get it back and all
other references to the table become invalid. This command completely destroys the table structure.
Drop table Student;
DML COMMANDS- Data Manipulation using a database means either insertion of new data, removal of existing data
or modification of existing data in the database.
1. Inserting Data into a table- The Insert into command is used to insert a new record/row/tuple in a table. Insert
into statement in the following different forms-
a) Inserting data ( for all the ) into a table- in the first method, while inserting a row if we are adding value for all the
column of the table we need not specify the column(s) name in the SQL query. But we need to make sure that the
same order of the values is in the same order as the columns represented in the structure of the table.
-> the argument/ value of character or text and date data type are always enclosed in double or single quotation
marks.
-> NULL values are stored and displayed as NULL only without any quotes.
Insert into Student Values(3, ‘mohit kumar’, ‘M’, 42, ‘2000-01-12’, 9658535);
b) Inserting data by specifying all the columns and associated values into a table- the second form specifies both
the column names and the values to be inserted.
Insert into Student(Rollno,Name,Gender,Marks,DOB,Mob_no) Values(4, ‘Priyanshi’, ‘F’, 24, ‘2005-01-10’,
975859);
c) Inserting data into specific columns of a table- This command insert a record into the student table for the
columns Rollno, Name, Marks Only.
Insert into Student(Rollno,Name,Marks) Values(5, ‘Riya sharma’, 50);
Note-Remaining of columns shall hold the values as NULL.
d) Inserting NULL values into a table-If a column in a row has no value or missing value then the column is said to be
null or holding NULL value. Null value can be given to any column other than being assigned as primary key or
Not Null constraint. It can be done by typing NULL without quotes.
Insert into Student(Rollno,Name,Gender,Marks,DOB,Mob_no) Values(4, ‘Priyanshi’, ‘F’, 24, NULL, NULL);
2. Modifying Data in a table- To modify data in a table or to make changes for some or all of the values in the
existing records in a table, we use the UPDATE statement. The update command specifies the rows to be
modified using the WHERE clause and the new data is written into the respective record using the SET keyword.
a) Updating single column- The below statement shall change the value of Marks field to 85 for the Student whose
Rollno is 1.
Update Student Set Marks=85 Where Rollno=1;
b) Updating multiple columns- Modifying the values in more than one column can be done by separating the
columns along with the new values using SET clause, separated by commas.
Update Student Set Marks=95 , DOB= ‘2000-05-02’ Where Rollno=2;
d) Updating to NULL values- the values for the attributes in a relation can be entered as NULL using UPDATE
command.
Update Student Set LastName= ‘Sharma’, Where Rollno=2;
Update Student Set Marks=NULL Where Rollno=1;
e) Updating using an expression or formula- we can update the value with an expression.
Update Student Set Marks=Marks+8 Where Rollno=2 or Rollno 4 ;
The above statement shall increment the value of marks by 8 for all the records with Rollno 2 or 4.
f) Updating all rows using an expression or formula-
Update Student Set Marks=Marks+15 ;
The above statement shall increase the value of marks of all the students by 15.
3. Delete (Removing) data from a table- The DELETE statement is used to delete row from table.
Delete form Student Where Rollno=4
The above statement shall delete the record only for roll number 4.
Note- the Where clause in the SQL delete command is optional and is identifies the rows in the column that
get deleted. If you do not include the where clause, all the roes in the table are deleted.
Deleting all the rows from the table- to delete all the rows from the student table the delete statement will
be-
Delete from Student;
SQL TRUNCATE statement- The SQL Truncate command is used to delete all the rows from the table and
free the space containing the table.
Truncate table Student;
Difference between DELETE and TRUNCATE Statement –
Delete Statement- This command deletes only the rows from the table based on the condition given the
where clause or deletes all the row form the tables if no condition is specified. But it does not free the space
containing the table.
TRUNCATE Statement – The SQL Truncate command is used to delete all the rows from the table and free
the space containing the table.
SQL SELECT Statement- This command can perform selection as well as projection. It is the most extensively used sql
command. The select statement can be used to retrieve a subset of rows or columns form one or more tables
present in a database.
1. Projection- This capability of SQL returns all rows from a relation with selective attributes.
Select Name, Gender from Student;
Name Gender
Raj kumar M
Deep singh M
The above command displays only Name and Gender attributes from the student table.
To display all columns along with the respective rows we use the command-
Select * from Student;
Note- the asterisk (*) means displaying all the columns from a relation.
2. Selection- Selecting Specific Rows- (Where Clause)-this capability of SQL returns some of the rows and all the
columns in the relation. Use of WHERE clause is required when specific tuples are to be fetched or manipulated. To
select all the columns from a table, the asterisk(*) can be used.
Select * form Student Where Gender =’M’ ;
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
Select * form Student Where Rollno<=5;
The above command shall display only those records whose Rollno is less than or equal to 5
4- Eliminating Duplicating/ Redundant Data –Distinct Clause – Distinct clause is used to remove duplicate row from
the results of a Select statement. It is used to retrieve only unique values for a column in the table.
Select Gender from Student; Select Distinct Gender from Student;
Gender Gender
M M
M F
F
M
F
Relational Operator- Equal to, Grater than, Less than, Greater than or equal to, Less than or equal to, Not equal to
Select * from Student where Marks >=50;
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
3 Payal F 51 1999-02-03 NULL
Not Equal (!=)-This command shall display the records of all the students who are not get 50 marks.
Select * from Student where Marks !=50;
Rollno Name Gender Marks DOB Mob_no
2 Deep singh M 56 2001-08-12 NULL
3 Payal F 51 1999-02-03 NULL
4 Ankit M 36 2004-12-03 NULL
5 Gauri F 40 2001-03-25 NULL
Logical Operators- The three logical operator in sql are-AND, OR and NOT operator. Out of these AND and OR
operator are termed as conjunctive operators since these two operators combine two or more conditions.
1- AND Operator- The AND operator displays a record and returns a true value if all the conditions (usually two
conditions) specified in the where clause are true.
Select * from Student where Marks>= 50 AND Gender =’M’;
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
2 Deep singh M 56 2001-08-12 NULL
2 – OR Operator- The OR operator displays a record and returns a true value if either of the conditions (two
conditions) specified in the where clause is true.
Select Rollno, Name, Gender ,Marks from Student where Marks>=36 OR Gender= ‘M’;
3-Not Operator- Not operator is also termed as a negation operator. Unlike the other two operators, This operator
takes only one condition and gives the reverse of it as the result. It returns a false value if the condition holds true
and vice versa.
Select Name, Marks from Student where NOT Gender= ‘F’;
Name Marks
Raj kumar 50
Deep singh 56
Ankit 36
SPECIAL OPERATOR-
BETWEEN and AND Operator - The BETWEEN operator defines a range of values that the column values must fall in
to make the condition true. The range includes both lower value and upper value.
SELECT Name , Gender ,DOB, Marks from Student WHERE Marks BETWEEN 45 AND 55;
Name Gender DOB Marks
Raj kumar M 2012-06-11 50
Payal F 1999-02-03 51
NOT BETWEEN- The not between operator works opposite to the between operator it retrieves the rows which do
not satisfy the between condition.
SELECT Name , Gender ,DOB, Marks from Student WHERE Marks NOT BETWEEN 45 AND 55;
Name Gender DOB Marks
Deep singh M 2001-08-12 56
Ankit M 2004-12-03 36
Gauri F 2001-03-25 37
IN operator - To specify a list of values, IN operator is used. The IN operator selects value that match any value in a
given list of values. E.g.
SELECT * FROM Student WHERE DOB IN (‘2001-08-12’ , ‘2001-03-25’);
Rollno Name Gender Marks DOB Mob_no
2 Deep singh M 56 2001-08-12 NULL
5 Gauri F 58 2001-03-25 NULL
NOT IN – The NOT IN operator work opposite to IN operator. It returns the rows that do not match the list.
SELECT * FROM Student WHERE DOB NOT IN (‘2001-08-12’ , ‘2001-03-25’);
Rollno Name Gender Marks DOB Mob_no
1 Raj kumar M 50 2012-06-11 NULL
3 Payal F 51 1999-02-03 NULL
4 Ankit M 36 2004-12-03 NULL
Condition Based On Pattern Matches – LIKE - The LIKE operator is used to search for a specified pattern in a
column. This operator is used with the columns of type CHAR and VARCHAR. (Matches the string specified pattern)
Condition Based On Pattern Matches – WILD CARD CHARACTERS- The SQL like condition allows you to use wild card
to perform pattern matching sql provides two wild card characters that are used while comparing the strings with
LIKE operator.
Ex- 1
Ex- 2
Ex- 3
Ex- 4
Select * from Student Where Name Like “_a%”;
NOT LIKE- The not like operator works opposite to like operator. It returns the rows that do not match the specified
pattern.
Ex- 1
SEARCHING FOR NULL - The NULL value in a column can be searched for in a table using IS NULL in the WHERE
clause. E.g. to list Students details whose Mob_no contain NULL, we use the command:
Select Name, Gender, Marks, Mob_no From Students Where Mob_no Is Null ;
Column Aliases- Column alias are used to make column headings in the query result set easier to read.
Student_name Date_of_Birth
Raj kumar 2012-06-11
Deep singh 2001-08-12
Payal 1999-02-03
Ankit kumar 2004-12-03
Gauri 2001-03-25
SORTING IN SQL –ORDER BY - Whenever the SELECT query is executed , the resulting rows appear in a pre-decided
order. The ORDER BY clause allow sorting of query result. The sorting can be done either in ascending or descending
order, the default is ascending
1. Ascending Order- - to display the all records of students on the basis of their Name in the ascending order.
2. Descending Order- - to display the all records of students on the basis of their Name in the ascending order.
COUNT( )
AVG( )
MIN( )
MAX( )
SUM ( )
Table: Emp
Empno Ename job salary Deptno City
8369 SMITH CLERK 2985 10 jaipur
8499 ANYA SALESMAN 9870 20 Kanpur
8566 AMIR SALESMAN 8760 30 Delhi
8698 BINA MANAGER 5643 20 Agra
AVG(SAL)
6051.
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
SELECT COUNT(*) FROM Emp ;
Output
COUNT(*)
5
COUNT(JOB)
4
3. MAX ( )- This function returns the maximum value from a given column or expression.
SELECT MAX (SAL) FROM Emp ;
Output
MAX(SAL)
9870
4. MIN ( )- This function returns the minimum value from a given column or expression.
SELECT MIN (SAL) FROM Emp ;
Output
MIN(SAL)
2985
5. SUM ( )- This function returns the sum of values in given column or expression.
SELECT SUM(SAL) FROM Emp ;
Output
SUM(SAL)
30258
Group by – The group by clause can be used in a select statement to collect data across multiple records and group
the results by one or more columns. It groups the row on the basis of the values present in one or the columns and
then the aggregate functions are applied on any column of these groups to obtain the result of the query.
Calculate the number of employees in each grade.
SELECT JOB, COUNT (*) FROM EMP GROUP BY JOB ;
Output
JOB COUNT(*)
CLERK 1
SALESMA 2
N
MANAGER 1
DEPTNO SUM(SAL)
10 2985
20 15513
30 8760
WHERE AND HAVING- Where clause works in respect to the whole table but having clause works on group only.
If where and having both are used, then where will be executed first. Where is used to put a condition on individual
row of a table whereas having is used to put a condition on an individual group formed by group by clause in a select
statement.
SQL JOIN- An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between
them. While querying for a join more than one table is considered in from clause. The process/function of combining
data from multiple tables is called a join. Usually such an attribute is the primary key in one table and foreign key in
another table.
1. Cartesian Product ( Cross Product)
2. Equi Join
Table: Student
Table: Game GameNo Game
10 Football
12 Cricket
Student X games
Rohan Football
Jaya Football
Teena Football
Rohan Cricket
Jaya Cricket
Teena Cricket
Equi Join- An equi join is a simple sql join condition that uses the equal to sign(=) as a comparison operator for
defining a relationship between two tables on the basis of a common field i.e. primary key and foreign key.