0% found this document useful (0 votes)
3 views11 pages

MySQL Notes

Uploaded by

pearlkumbhat7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

MySQL Notes

Uploaded by

pearlkumbhat7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

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.

Advantages of database management system:


1. Reduced data redundancy (duplication of data is removed).
2. Inconsistency is also maintained.
3. Sharing of data can be done.
4. Database enforced standards.
5. Secured data and Privacy of data.

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”.

Relation: A relation is a table in Relational Model.


Table: It is a collection of rows and columns which describe the necessary structure to store data.
Attribute: Column of a table is called attribute.
Tuple: Row of a table is called a tuple.
Degree: The number of attributes in a relation is called the degree of the relation.
Cardinality: The number of tuples in a relation is called the cardinality of the relation.
Primary Key: The primary key of a relation uniquely identifies each record in the table. Primary keys
may consist of a single attribute or multiple attributes in combination.

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

Classification of SQL Statements


1. Data Definition Language (DDL) commands: Allows you to perform tasks related to data
definition such as Creating, Altering and Dropping.

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

1. It is of fixed length. It is of Variable length.

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%’;

2. List the name of employee whose name ends 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%’;

13. Use of NULL: Null value can be searched in a table.


For e.g.,
1. List the name, job and department of employees whose department contain Null.
Select ename, job, dept from employee where deptno Is Null;
2. List the name and department of employees whose department contain Not Null.
Select ename, dept from employee where deptno Is Not Null;

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.

Various Single Row MYSQL functions are:


1. String function
2. Numeric function
3. Date/time function
STRING FUNCTIONS:
Function name Description Example

Char() Returns the character for each Select char (70,65,67.3,’69.9’);


integer passed. Ans: FACE
Concat() Concatenates (join) two strings. 1. Select concat (name, age) from emp;
Ans: pooja 30
2. select concat(concat (ename, “is a”,
job);
Ans: pooja is a clerk
Lower/Lcase() Converts a string into lowercase. Select lower(‘HELLO’) ;
Ans: hello
Upper/Ucase() Converts a string into uppercase. Select upper(‘hello’) ;
Ans: HELLO
Substr() Extracts a substring from a given 1. Select substr(‘webtech’ ,2,5);
string. Ans: ebtec

2. Select substr(‘webtech’ ,-4,3);


Ans: tec
Ltrim() Removes leading spaces i.e., Select ltrim(‘ pooja goel’ );
from the left of the given string. Ans: pooja goel
Rtrim() Removes trailing spaces i.e., Select rtrim(‘ pooja goel’ );
from the right of the given Ans: pooja goel
string.
Trim() Remove leading and trailing 1. Select trim(‘ star one ‘);
spaces from a given string. Ans: star one
2. Select trim (leading ‘x’ from ‘xxxstar
one xxx ‘);
Ans: star one xxx
3. Select trim (both ‘x’ from ‘xxxstar
onexxx’);
Ans: star one
Instr() Searches for given second string Select instr (‘pooja goel’,’oo’);
into given first string. Ans: 2
Length() Return the length of a given Select length (‘hello’) as len;
string in bytes. Ans: 5
Left() Return the leftmost number of Select left (‘user/23/67’ ,3);
characters as specified. Ans: use
Right() Return the rightmost number of Select right (‘user/23/hello’ ,4);
characters as specified. Ans: ello
Mid() Returns a substring staring from Select mid (‘quarter’ 3,4)
a specified position. Ans: ater

NUMERIC FUNCTIONS
Function Description Example
name

Mod() Returns modulus i.e., remainder of two Select mod(11,4) as “modulus”;


numbers. Ans: 3
Power/ Returns mn i.e., a number m raised to Select power (2,3) as “raised”;
pow() the power n. Ans: 8
Round() Returns a number rounded off. 1. Select round(20.3464,2) as “round”;
Ans: 20.35
2. Select round(20.3464,-1) as “round”;
Ans: 120
3. Select round(20.3464,-2) as “round”;
Ans:100
4. Select round(20.3464,-3) as “round”;
Ans: 0
Sign() Returns sign of a given number. Select sign(20) as ‘sign”;
Ans: 1
Select sign(-20) as ‘sign”;
Ans: -1
Sqrt() Returns the square root of given Select sqrt (144) as “square root”;
number. Ans: 12
Truncate() Returns a number with some digits Select truncate (20.19399, 4) as “trunc”;
truncated. Ans: 20.1939

DATE/ TIME FUNCTIONS


Function Description Example
name

Curdate/ Returns the current date in yyyy- Select curdate();


current_date() mm-dd format. Ans: 2011-02-16
Date() Extracts the date part of a date or Select date(‘2011-02-16 01:02:03’);
datetime expression. Ans: 2011-02-16
Month() Returns the month from the date Select month (‘2011-02-16’);
passed. Ans: 2
Year() Returns the year part of a date, in the Select year(‘2011-02-16’);
range 1000 to 9999. Ans: 2011
Dayname() Returns the name of weekday for Select dayname (‘2011-02-16’);
date Ans: Wednesday
Dayofmonth( Returns the day of month. Select dayofmonth(‘2011-02-16’);
) Ans: 16
Dayofweek() Returns the day of week. Select dayofweek(‘2011-02-16’);
1-Sunday,2-Monday……. Ans: 4
Dayofyear() Return the day of year for the date. Select dayofyear(‘2011-02-16’);
Ans: 47
Now() Returns the current date and time. Select now();
Ans: 2011-02-16 01:02:03
Sysdate() Returns the time at which the Select sysdate();
function executes Ans: 2011-02-16 01:02:03
Multiple Row Functions(Aggregate,group functions)
Multiple-row functions operate on a group of rows and return a single summary result for that entire
group. These functions are typically used with the GROUP BY clause to define the groups, or they can
operate on the entire result set if no GROUP BY clause is present.
Max Returns maximum value of the column.
Select max(salary) from employee;
Select max(salary) from employee where
salary>5000; *All group functions
Min Returns minimum value of the column. Ignores the NULL
Select min(salary) from employee; values.

Avg Returns average value of the column. *Count(*) counts


Select avg(salary) from employee; the record not
affected by NULL
Sum Returns sum value of the column. values
Select sum(salary) from employee;

Count(*) Returns total number of records


Select count(*) from employee;

Count(distinct) Returns total number of unique values of column.


Select count(distinct desig) from employee;

Count(field) Returns total number of values of column.


Select count(name) from employee;

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.

SELECT Department, AVG(Salary) AS AverageSalary FROM Employees GROUP BY


Department
HAVING AVG(Salary) > 50000;

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);

3. To change a column name


Alter table <table name> Change [column] old_col name new_col_name column_definition;
For e.g., To change the name of existing column Department to Dept.
Alter table employee Change Department Dept varchar(20);

4. To delete columns of a table.


Alter table <table name> Drop [<column name>];
For e.g., Alter table emp drop dname ;
Drop table command: To drop a table from a database.
Drop table <table name>
For e.g., drop table employee;

MODIFYING DATA WITH UPDATE COMMAND:


Update command specifies the rows to be changed using the Where clause, and the new data using the
SET keyword.
For e.g., 1) Change the salary to 5000 of all those employees whose salary is 3000.
Update employee SET Salary =5000 Where salary =3000;
2) Increase the salary of all employees by Rs.100
Update employee SET salary = salary +100;

DELETE COMMAND: Removes rows from a table.


Delete from <table name> [Where <predicate>];
For e.g., 1) To delete the records of employees whose salary is greater than 2000.
Delete from employee Where salary > 2000;
2) To remove all the contents of employee table, the command is:
Delete from employee;

*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");

Q Difference between terms:

WHERE Clause HAVING Clause


Filters rows. Filters groups after the aggregation process..
WHERE Clause can be used without HAVING Clause can be used with GROUP BY Clause
GROUP BY Clause
WHERE Clause cannot contain aggregate HAVING Clause can contain aggregate function
function
WHERE Clause can be used with SELECT, HAVING Clause can only be used with SELECT
UPDATE, DELETE statement. statement.
WHERE Clause is used with single row HAVING Clause is used with multiple row function
function like UPPER, LOWER etc. like SUM, COUNT etc.
Select * from employee where salary Select dept.sum(salary) from employee group by
>4500; dept having sum(salary)>50000;

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;

String functions Date functions


String functions are used to manipulate and Date functions are specifically designed to work
process text data (strings). with date and time values.
This includes tasks like concatenating They enable operations such as extracting
multiple strings, extracting substrings, specific parts of a date (year, month, day, hour,
changing case (uppercase/lowercase), minute, second).
finding the length of a string
Select upper(“Welcome”); Select year(“2025-07-06”);

Equi Join Natural Join


An equi join explicitly specifies the join A natural join automatically joins tables based
condition using the equality operator (=) on columns that have the same name and
between columns from the tables being compatible data types in both tables.
joined.

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;

You might also like