MYSQL Notes
MYSQL Notes
A database is a collection of interrelated data stored together to serve some application. It can also be defined as
a computer based record keeping system. A Database management system (DBMS) is software that contains the
database and the tools to manage that database. It is responsible for storing, maintaining and utilizing a
database. Various advantages of the database system are:
• Reduce data redundancy (Repetition of data)
• Control data inconsistency (Improper update)
• Facilitate sharing of data
• Enforce standards
• Ensure data security
• Maintain integrity
Domain: A pool of values from which the actual values of a column are derived.
View: A view is a kind of table whose contents are taken from other table(s) depending upon a condition. They
do not contain their own data rather store a query whose result is displayed.
Primary key: A field or a combination of fields used to uniquely identify each record of a database table.
Candidate key: All key combinations that are eligible to become a primary key are called candidate keys.
Foreign key: A non-key field whose values are derived from the primary key of some other table.
Referential integrity: A system of rules to ensure that the related tables contain valid data and the user does
not accidentally delete / change related data.
MySQL
MySQL is a freely available open source RDBMS (Relational database management system) that uses
SQL(Structured Query Language). It can be downloaded from www.mysql.org. It is a fast, reliable, scalable
alternative to many of the commercial RDBMSs available today. MySQL operates using client/server
architecture in which the server runs on the machine containing the databases and clients connect to the server
over a network.
Page 1
SQL
SQL is the set of commands that is used to work on all RDBMS. The commands of SQL can be divided into the
following categories:
i.DDL(Data Definition Language): Commands which are used to work on the structure of the tables.
• Creating, altering, and dropping
• Granting and revoking privileges and roles
• Maintenance commands
ii.DML (Data Manipulation Language): Commands used to work on the data stored in the tables and
maintain it such as
• Retrieval of data
• Insertion, deletion and modification of data
MySQL Elements
A. Literals: A fixed data value, which may be character literal or numeric literal. The numeric literals can
be further integer literals or real literals. Eg: “Informatics”, 567, 789.56
B. Data Types: They are the means to identify the type of data and associated operations for handling it.
Data Types
CHAR VARCHAR
Fixed length string Variable length string
If a column is given datatype as CHAR(10), then If a column is given datatype as VARCHAR(10),
MySQL ensures that all values in that column are then the maximum size of string in that column can
of 10 characters or it adds spaces to its right side be 10 characters, but if the string is shorter no
to make it of 10 characters. spaces are added to it.
Uses more memory Uses less memory
If the size is not specified the default size is 1. It is necessary to specify the size in varchar.
C. NULL Values: If a column in a row contains no value, then column is said to be null.
Any arithmetic expression containing a null, always evaluates to null.
D. Comments: A comment is a text that is not executed; it is only for documentation purpose.
Comments in MySQL can be written in 3 ways:
a. Multiple line comments: Enclosed in /* ………. */
b. Single line comments: Comments beginning with 2 hyphens followed by a space (-- ) / #
MySQL Commands
I.Creating a Database
Syntax: create database <databasename>;
Example: create database ip;
Page 3
V.To see the available tables
show tables;
DDL DML
Data Definition Language Data Manipulation Language
These commands work on the structure of the tables. These commands work on the data stored inside the tables.
Create, Alter, Drop Insert, Update, Delete, Select
Example example
drop table student; delete from student where rollno=1;
ALTER UPDATE
Data Definition Language Data Manipulation Language
It is used to change the structure of the table, that is, to It is used to change the data stored in the table.
add/drop/modify columns.
Cannot be cancelled. Can be cancelled using rollback.
Example Example
Alter table student add address varchar(20); Update student set marks=90 where rollno=1;
DROP DELETE
Data Definition Language Data Manipulation Language
It is used to remove both the data and structure of a table. It is used to delete the records in a table.
Cannot be cancelled. Can be cancelled using rollback.
Example Example
Drop table student; Delete from student where rollno=1;
Page 4
X.Altering tables: To add / modify / rename a column
This command is used to make changes to the definitions of existing tables. It can be used for:
1. adding columns to a table
2. modifying the datatype, size or constraints for a column
3. changing the name of the column
4. deleting columns of a table
5. adding constraints to a table
XI.Dropping tables
Syntax: Drop table [if exists] <tablename>;
Example: drop table student; or
drop table if exists student;
Page 5
Selecting all data
i.To display all the data in empl table
Select * from empl;
Page 6
xvii. To display the name and comm. of all employees. Those with null commission should
display ‘no commission’.
Select ename, ifnull(comm, “no commission”) from empl;
xviii.Display the records of all employees as “Ajay gets Rs. 5000”
Select ename, ‘ getsRs. ‘, sal from empl;
- Performing Simple Calculations
xix.To calculate 7*8+3
Select 7*8+3; or
Select 7*8+3 from dual;
- Using Calculated columns
xx.To display the ename and annual salary of all employees
Select ename, sal*12 from empl; or
Select ename, sal*12 “Annual Salary” from empl; or (with Column Alias)
Select ename, sal*12 as “Annual Salary” from empl;
Order by clause
The MySQL ORDER BY clause is used to sort the records in your result set.
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
expressions
The columns or calculations that you wish to retrieve.
ASC
Optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).
DESC
Optional. It sorts the result set in descending order by expression.
Consider the table EMPL containing Empno, Ename, Job, Mgr, Hiredate, Sal, Comm, Deptno
To arrange records in ascending order of deptno. If the deptno is same, arrange in descending order of salary.
SELET * FROM EMPL ORDER BY DEPTNO ASC, SAL DESC;
Page 7
MySQL Functions
A function is a special type of predefined command that performs some operation and returns some values. The
values that are provided to the functions are called as parameters or arguments.
String Functions
Function Description Example Output
1 Lcase()/ Lower() Converts the string to lower case Select lcase informatics
(‘INFORMATICS’);
2 Ucase()/ Upper() Converts the string to upper case Select ucase (‘class’); CLASS
3 Left() Returns the leftmost n chararters Select left(‘Informatics’,6); Inform
from the string
4 Right() Returns the rightmost n chararters Select right(‘Monday’,3); day
from the string
5 Mid()/ Substr()/ Returns a substring Select substr(‘informatics’,3,4); form
Substring()
6 Ltrim() Removes leading spaces Select ltrim(‘ abc ‘); abc
7 Rtrim() Removes trailing spaces Select rtrim(‘ abc ‘); abc
8 Trim() Removes leading & trailing spaces Select trim(‘ abc ‘); abc
9 Instr() Returns the position of the first Select instr(‘corporation’, ‘or’); 2
occurrence of substring
10 Length() Returns the length of the string Select length(‘abc xyz’); 7
including spaces
11 Concat() Joins two or more strings Select concat(‘abc’, ‘xyz’); abcxyz
12 Char() Returns the character for each integer Select char(70,65,67,69); FACE
passed A-Z(65-90), a-z (97-122)
Numeric Functions
Function Description Example Output
1 Power(A,B)/Pow(A,B) Returns the value of AB Select power(3,2); 9
2 Round() Rounds off the given number to the Select round(15.193,1); 15.2
given precision.
3 Mod() Returns the remainder Select mod(11,4); 3
Page 8
Aggregate / Group / Multiple row functions
These functions work of a group of rows and then give the result. These functions are:
Function Description Example
1 Sum Calculates the sum total of values in a column Select SUM(sal) from empl;
2 Max Calculates the highest value in a column Select MAX(sal) from empl;
3 Min Calculates the lowest value in a column Select MIN(sal) from empl;
4 Avg Calculates the average of values in a column Select AVG(sal) from empl;
5 Count Calculates the number of values in a column Select COUNT(*) from empl;
Group by clause
The group by clause combines all those records that have identical values in a particular field. This grouping
results in one result per group.
To display the number of employees in each department.
SELECT DEPTNO, COUNT(*) FROM EMPL GROUP BY DEPTNO;
Having clause
The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on
individual rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can do so.
To display the jobs where the number of employees is less than three.
SELECT JOB, COUNT(*)FROM EMPL GROUP BY JOB HAVING COUNT(*)<3;
To see the total salary of each deptno where the total salary is in the range 10000 to 20000.
SELECT DEPTNO, SUM(SAL) FROM EMPL
GROUP BY DEPTNO HAVING SUM(SAL) BETWEEN 10000 AND 20000;
Page 9
Joins
The most important aspect of SQL is its relational feature. A join is a query that combines data from two or
more tables. The names of all the tables from which the data has to be combined are given in the “from” clause
of select query.
Cartesian product
A query in which all rows of one table are combined with all rows of the other table is called an unrestricted
join or Cartesian product or Cross Join.
Select * from empl, dept;
Equi Join
The join in which columns are compared for equality is called equi join.
Q. Write a query to display the details of all employees along with their department details.
Select * from empl, dept where empl.deptno=dept.deptno; OR
Q. To display the empno, ename, loc of all employees.
selectempno, ename, loc from empl e, dept d where e.deptno=d.deptno;
Q. To display the empno, ename, deptno, loc of all employees.
Select empno, ename, d.deptno, loc from empl e, dept d where e.deptno=d.deptno; //qualified field names
Q. To display the ename, dname of all managers.
selectename, dname from empl e, dept d where e.deptno=d.deptno and job='manager';
Table Alias: A table alias is a temporary label given along with table name in the from clause.
Natural Join
The equi join in which the common column between the two tables is displayed only once is called the natural
join.
Q. Write a query to display the details of all employees along with their department details.
Select * from empl natural join dept;
Page 10