MySQL Notes
MySQL Notes
IP - 12th
IMPORTANT DEFINITIONS
Database: Database is the collection of related data.
DBMS: Database Management System is used to manage the database. A Database Management
System is a collection of interrelated data. Its objective is to provide an environment to retrieve and
store database information.
Relational Database Management System (RDBMS): It facilitates the storage, access, security and
integrity of data and eliminates data redundancy. It stores the data in a set of tables. Example: MySql,
SQL Server etc.
Data Integrity: It means that data contained in the database is both accurate and consistent.
Database Models: A database model describes the database scheme as per the stated requirements.
These models are called data models. These are three types of models:
a) Relational Model
b) Hierarchical Model
c) Network Model
Data Dictionary: A file containing facts or data about the data stored in the table. It is also called as
“metadata”.
Candidate Key: A candidate key is the one that is capable of becoming primary key i.e., a field or
attribute that has unique value for each row in a relation.
Alternate Key: A candidate key that is not primary key is called an alternate key.
Foreign Key: A non-key attribute, whose values are derived from the primary key of some other table.
A foreign key refers to a primary key or a unique key in another table.
Explain with example:-
*Employee
Empno regno ename sal deptno
1 1011 abc 7000 20
2 1021 xyz 10000 10
3 1031 mno 6800 5
4 1041 rst 15000 20
Dept
Deptno dept_name
5 accounts
10 sales
20 purchase
30 production
Empno & regno are candidate keys in Employee table
Empno is primary key & deptno is foreign key of employee table
Deptno is primary key of dept table
Integrity constraints: They are the rules that a database must comply at all times. It determines what
all changes are allowable to the database.
*it can be done by all constraints like not null, default, primary key etc
2. Data Manipulation Language (DML) commands: Allows you to perform the data manipulation
such as retrieval, insertion, deletion, and modification of data stored in a database.
3. Transaction Control Language: Allows you to manage and control the transactions such as commit,
rollback, creating save points.
Data Types: means to identify the type of data. Various MYSQL data type is:
Numeric
Integer: Stores numeric values.
Float, Double and Decimal
Date and time types
Date: Stores date in ’yyyy- mm- dd’ format.
Time: Stores time ‘hh: mm: ss’ in format.
Datetime: Stores date and time combination in ’yyyy- mm- dd’ ‘hh: mm: ss’ format.
String types: char(size) and varchar(size)
Difference between char and varchar.
Char Varchar
2. Occupy fixed number of bytes i.e., n No blanks are added if the length is
bytes. If a value is shorter than this shorter than the maximum length n.
length n then blanks are added, but the
size of values remains n byte.
Relational operators: These operators are used to compare two values. Various relational operators
are:
= equal to, >greater than, < less then, >= greater than or equal to,
<= smaller than or equal to, <>not equal to
Logical operators: OR (||), AND (&&) and Not (!)
COMMANDS IN MYSQL
1. For creating a database syntax is:
Create database <database name>;
For e.g., create database employee;
2. To open databases syntax is:
Use <database name>;
For e.g., use employee;
3. To see all the databases use syntax is:
Show databases;
4. To remove a database syntax is:
Drop database <database name>;
For e.g., drop database employee;
5. For Creating tables in a database syntax is:
Create table <table name>
(<Column name> <data type> [(size)]),
<Column name><data type> [(size)…]);
For e.g., Create table emp
( ecode integer Primary key,
ename varchar(20),
grade char(2),
gender char(1),
salary int );
6. To view the number of tables in a database:
Show tables;
7. To view the structure of table:
Desc <tablename>;
For e.g., desc employee;
8. Insert into command:
Insert into <tablename> values (<value>, <value1>…);
For e.g., Insert into emp values (101, ’smith’, ’e1’, 5000.00);
9. Select Command:
Select <column name …> from <table name>;
For e.g.,
a) To show all the columns from emp table.
Select * from emp;
b) To view only two columns i.e., code and name grade from emp table.
Select ecode, ename, grade from emp;
c) To eliminate redundant data (with distinct keyword).
Select distinct department from emp;
10. Where Clause:
Select <column name …> from <table name> where <condition>;
For e.g.,
1. Select all information of employee whose empid =101
Select * from emp where empid =101;
2. Select all employee that were born on or after jan 1,1998.
Select * from emp where dob>=’1998-01-01’;
3. Select all manger of deptno 20.
Select * from emp where job=’manager’ and deptno=20;
4. Select all salesman or manager.
Select * from emp where job=’salesman’ or job=’manager’;
11. Condition based on a range: The Between operator defines a range of values.
For e.g.,
1. Display the records of an employee whose salary is between 30000 and 70000.
Select * from emp where salary between 30000 and 70000;
2. Display the records of an employee whose salary is not between 30000 and 70000.
Select * from emp where salary not between 30000 and 70000;
12. Condition based on Pattern matching: For comparing the character strings using Patterns.
Patterns are described using 2 special wildcard characters:
Percentage (%): It matches any substring.
Underscore (_): It matches any character.
The like keyword is used to that match a wildcard pattern.
For e.g.,
1. List the name of employee whose name starts with ‘A’.
Select ename from employee where name like’A%’;
3. List the name of employee whose name contains ‘A’ as fourth alphabet.
Select ename from employee where name like’_ _ _A%’;
14. Order by: Sorting can be done either in ascending or descending order, the default order is
ascending.
For e.g., List the details of employees in descending order of employee code.
Select * from employees Order by ecode desc;
15. Column Alias: Columns that you select in a query can be given different
Select <column name> AS [column alias] from <table name>;
For e.g., select sal as “salary” from employee;
MYSQL FUNCTIONS
Function: A function is a special type of predefined command set, that performs some operation and
return a single value.
Functions are two types:
i. single row functions
ii. Multiple row functions
Single-Row Functions (Scalar Functions):
Single-row functions operate on individual rows of data and return a single result for each row
processed. These functions can be used in the SELECT, WHERE and order by clauses of a SQL query.
NUMERIC FUNCTIONS
Function Description Example
name
Group by clause
The GROUP BY clause in SQL is used to group rows that have the same values in one or more
specified columns into a summary row for each group. This clause is typically used in conjunction with
aggregate functions (e.g., COUNT(), SUM(), AVG(), MAX(), MIN()) to perform calculations on each
group.
For eg.
SELECT Department, COUNT(EmployeeID) AS NumberOfEmployees FROM Employees
GROUP BY Department;
HAVING Clause:
The HAVING clause is used to filter groups based on a specified condition, similar to how
the WHERE clause filters individual rows.
The HAVING clause is applied after the GROUP BY clause has formed the groups and
aggregate functions have been calculated. This allows filtering based on the results of those
aggregate functions.
Unlike WHERE, HAVING can directly use aggregate functions in its conditions.
Order of Execution:
It is important to understand the typical order of execution for clauses in a SQL query:
FROM, WHERE, GROUP BY, HAVING, SELECT, and ORDER BY.
This means WHERE filters individual rows before grouping, and HAVING filters the resulting groups
after aggregation.
SELECT Department, SUM(Salary) AS TotalSalary FROM Employee WHERE HireDate >=
'2020-01-01' GROUP BY Department HAVING SUM(Salary) >= 50000 order by Department;
JOINS-
In SQL, joins are used to combine rows from two or more tables based on a related column between
them. (Primary Key and Foreign Key).
Referential integrity in DBMS is a set of rules that ensures the consistency and accuracy of relationships
between tables. It guarantees that foreign key values in a child table always refer to existing, valid
primary key values in a parent table.
Types of Joins-
EQUI JOIN:
A specific type of join where the join condition uses the equality operator (=) to match values in the
specified columns.
SELECT column_list FROM table1, table2 where table1.PK=table2.FK;
NATURAL JOIN:
This join automatically joins tables based on columns that have the same name and data type in both
tables. It eliminates duplicate columns in the result.
SELECT column_list FROM table1 NATURAL JOIN table2;
Cartesian product
In SQL, a Cartesian product is an operation that combines every row from one table with every row
from another table. It results in a new table containing all possible combinations of rows from the
participating tables. It
If TableA has M rows and TableB has N rows, a Cartesian product of TableA and TableB will produce
a result set with M * N rows. Each row from TableA is paired with every single row from TableB.
to perform a Cartesian product in SQL by removing join command.
Example:
Consider two tables:
colors.
Color
Red
Blue
sizes.
Size
Small
Large
A Cartesian product between Colors and Sizes would yield:
Color Size
Red Small
Red Large
Blue Small
Blue Large
ALTER COMMAND
Sometimes we need to make changes in the definitions of existing table. This command is used to:
1. Adding column to a table
Alter table <table name> Add <column name> <data type> <size> [<constraint name>];
For e.g., To add a new column E-mail of datatype varchar and size 20 to the table employee.
Alter table employee Add Email varchar(20);
2. To redefine a column (data type, size, default value) using Modify command
Alter table <table name> Modify (column name newdata type (newsize));
For e.g., To modify column name with new width of 30 characters in employee table.
Alter table employee modify salary varchar(30);
Convert the datatype of column salary int to float.
Alter table employee modify salary float(10,2);
*Define questions:-
B)Consider the EXAM given below. Write commands in MySql for (i) to (iv)
and output for (v) to (vii).
Table: EXAM
No Name Stipend Subjet Average Division
1 Karan 400 English 68 FIRST
2 Aman 680 Mathematics 72 FIRST
3 Javed 500 Accounts 67 FIRST
4 Bishakh 200 Informatics 55 SECOND
5 Sugandha 400 History 35 THIRD
6 Suparna 550 Geography 45 THIRD
(i) To list the names of those students. who have obtained Division as FIRST in the ascending order of
NAME.
Ans. SELECT Name FROM Exam WHERE Division = 'FIRST' ORDER BY Name;
(ii) To display a report listing NAME, SUBJECT and Annual stipend received assuming that the
stipend column has monthly stipend.
Ans. SELECT NAME, SUBJECT, STIPEND * 12 FROM EXAM;
(iii) To insert a new row in the table EXAM: 6 “Mohan”, 500, “English”, 73, “SECOND”;
Ans. INSERT INTO EXAM VALUES (6, “Mohan”, 500, “English”, 73, “SECOND”);
OR
INSERT INTO EXAM (NO, NAME, STIPEND, SUBJECT, AVERAGE, DIVISION)
VALUES (6, "Mohan", 500, "English", 73, "SECOND");
ROUND() TRUNCATE()
the ROUND() function returns a number the TRUNCATE() function returns a number with
rounded off according to the given some digits truncated. The TRUNCATE() function
specifications. simply removes the specified digits without
rounding
them off.
Select round(467.789,2) Select truncate(467.789,2)
467.79 467.78
Single row functions Multiple row/Aggregate functions
These are also known as Scalar functions. Aggregate functions are also called multiple row
Single row functions are applied on a single functions. These functions work on a set of
value and return a single value. records as a whole, and return a single value for
each column of the records on which the
function is applied.
single row functions under three categories Multiple row functions are- min(),max(), avg(),
— Numeric (Math), String, Date and Time. sum(), count()
It can apply on single value and column It can apply only on column value.
values both.
Select length(“welcome”); Select sum(salary) from emp;
The columns used in the join condition do It requires that at least one common column with
not necessarily need to have the same name, the same name exists in both tables.
but they must have compatible data types.
In the result set of an equi join, the common In the result set of a natural join, the common
column(s) from both tables will appear as column(s) appear only once, eliminating
separate columns, potentially leading to redundancy.
duplicate columns if all columns are
selected.
Select emp.*,dept.* from emp,dept where Select emp.*,dept.* from dept natural join emp;
emp.deptid=dept.deprtid;