Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

MYSQL Notes

The document provides an overview of MySQL, a free open-source relational database management system (RDBMS) that utilizes SQL for data management. It covers fundamental concepts such as database structure, data types, SQL commands, and integrity constraints, along with practical examples for creating, modifying, and querying databases. Additionally, it explains the differences between Data Definition Language (DDL) and Data Manipulation Language (DML) commands.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

MYSQL Notes

The document provides an overview of MySQL, a free open-source relational database management system (RDBMS) that utilizes SQL for data management. It covers fundamental concepts such as database structure, data types, SQL commands, and integrity constraints, along with practical examples for creating, modifying, and querying databases. Additionally, it explains the differences between Data Definition Language (DDL) and Data Manipulation Language (DML) commands.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

MySQL

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

Relational Data Model


Relation: A table containing logically related data, arranged in the form of rows and columns.

Tuple: A row of a table, also called a record.

Attribute: A column of a table also called field.

Domain: A pool of values from which the actual values of a column are derived.

Degree: The number of columns (Fields) of a table.

Cardinality: The number of rows (Tuples) of a table.

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.

Alternate key: A candidate key that is not a primary key

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.

Examples of common RDBMS


Oracle, Microsoft SQL Server, MySQL, IBM DB2, IBM Informix, SAP Sybase IQ, Terdata, PostgreSQL,
SQLite, etc. Out of these MySQL, SQLite and PostgreSQL are Open Source Implementations.

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

TEXT DATE NUMERIC

CHAR VARCHAR INT/ INTEGER FLOAT DOUBLE DECIMAL

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;

II.To see the available databases


show databases;
Page 2
III.Using a Database
Syntax: use <databasename>;
Example: use ip;

IV.Creating tables in MySQL


Syntax: create table <tablename> (<columnname><datatype> [<size>],…..);
Example: create table student
(rollno integer,
name varchar(20),
class varchar(10),
marks decimal);
Integrity Constraints
Integrity constraints are the rules which ensure that the data in the database should be correct and consistent.
These rules check that the changes that are being done to the database are correct and permissible.
A constraint that is applied on one column is known as column constraint.
A constraint that is applied at the end of the table definition, on one or more columns is called a table constraint.

The integrity constraints that can be used in MySQL are:


1. Primary Key: A column or combination of columns that identifies each row of a table uniquely.
Also it cannot be left blank.
2. Not Null: Checks that a column cannot be left blank (Null). Not Null constraint is defined at
column level only.
3. Unique: Ensures that the column will not take duplicate values.
4. Default: It is used to assign a default value to the column.
5. Foreign Key: It is used to ensure referential integrity. It is assigned on a child table where that
particular column derives its values from the primary key of another table. The table in which a
foreign key is defined is called a referencing table or child table. A table to which a foreign key
points is called a referenced table or parent table.

Defining Primary Key


At Column Level: At Table Level: Defining Composite Primary Key
Create table bank Create table bank Create table boardexams
(accno integer primary key, (accno integer, (rollno integer(7),
name varchar(20), name varchar(20), year integer(4),
address varchar(30), address varchar(30), name varchar(15),
dateofopening date, dateofopening date, class varchar(10),
balance decimal); balance decimal, school varchar(20),
primary key(accno)); center varchar(20),
primary key (rollno, year));
Defining other Constraints
create table student create table activity Create table transactions
(rollno integer primary key, (activityid integer primary key, (tid integer,
name varchar(20) not null, aname varchar(20) unique, transdate date,
class varchar(10), rollno integer, accno integer,
marks decimal ); score integer default 80); type varchar(10),
amount decimal,
foreign key(accno) references bank(accno));
Note: If a primary key is a composite key (combination of more than one column) then it can be defined only at
table level.

Page 3
V.To see the available tables
show tables;

VI.Inserting data into table


Syntax: Insert into <tablename> [<column list>] values ( <value>,<value>….);
Example: Insert into student values (1, ‘Ajay’, ‘XII Com’, 56.5);
Insert into student (name, class, rollno) values (‘Neha’, ‘XII Sc’, 2);
Note: The dates are inserted in ‘YYYY-MM-DD’ format and NULL is inserted by typing NULL
without quotes.

VII.Modifying the data in tables


Syntax: Update <table name> set <column name>=<new value> [where <condition>];
1. To change the marks of rollno 1 to 60.
Update student set marks=60 where rollno=1;
2. To increase marks of all students by 5.
Update student set marks=marks+5;

VIII.Deleting data from tables


Syntax: Delete from <tablename> [where <condition>];
1. To delete the record of rollno 2.
Delete from student where rollno=2;
2. To delete all records.
Delete from student;

IX.Viewing the structure of a table


Syntax: describe / desc<table name>;
Example: descempl;

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

Consider the following create table command:


create table student
(srno integer,
studentname varchar(10),
class char(2));

1. adding columns to a table


Q. To add a new column marks of decimal datatype size 5,2 to the student table
Alter table student add (marks decimal(5,2));

2. modifying the datatype, size or constraints for a column


Q. To change the datatype of class to varchar and size to 10
Alter table student modify (class varchar(10)); OR
Alter table student modify column (class varchar(10));

3. changing the name of the column


Q. To change the name of the column studentname to name
Alter table student change studentname name varchar(10); OR
Alter table student change column studentname name varchar(10);

4. deleting columns of a table


Q. To remove the column marks
Alter table student drop marks; OR
Alter table student drop column marks;

5. Adding/ Removing Primary key to a table


Q. To add a primary key on the srno column
Alter table student add primary key (srno);
Q. To remove the primary key from student table.
Alter table student drop primary key;

XI.Dropping tables
Syntax: Drop table [if exists] <tablename>;
Example: drop table student; or
drop table if exists student;

XII.Simple Queries using Select Command


Syntax: Select [all/distinct] */<column names>
from<table name>
[where<condition>]
[order by <column name>];

Page 5
Selecting all data
i.To display all the data in empl table
Select * from empl;

Selecting particular columns


ii.To display ename, sal and deptno from empl table
Select ename, sal, deptno from empl;
iii.To display the job from empl table
Select job from empl; or Select all job from empl;
iv.To display the different jobs available in empl table
Select distinct job from empl;

Selecting particular rows


- Using conditional operators ( =, <, >, <=, >=, <>, !=)
v.To display all employees working in deptno 30 from empl table.
Select * from empl where deptno=30;
vi.To display the employees who earn more than 4000.
Select * from empl where sal>4000;
- Using logical operators (AND(&&), OR(||) , NOT(!))
vii.To display all clerks in deptno 20.
Select * from empl where job=’clerk’ and deptno=20;

viii.To select all the employees working in deptno 10 or 30


Select * from empl where deptno = 10 or deptno = 30;
ix.To display the name and job of employees who are not working as manager.
Select ename, job from empl where not (job=’manager’);
- Condition based on range
x.To display the details of employees who earn in the range of 2000 to 5000.
Select * from empl where sal between 2000 and 5000; or
Select * from empl where sal>=2000 and sal<=5000;
- Condition based on a list
xi.To display the details of employees who are working as manager, clerk or analyst.
Select * from empl where job in (‘manager’, ‘clerk’ , ‘analyst’);
- Condition based on pattern matches (like used with wildcards)
% (Multiple characters), _ (single character)
xii.To display the details of employees whose name starts with S.
Select * from empl where ename like ‘S%’;
xiii.To display the name of employees who have the letter “A” as the second letter in their
name.
Select ename from empl where ename like ‘_A%’;
xiv.To display the details of employees who joined in 1991.
Select * from empl where hiredate like ‘1991%’; or
Select * from empl where hiredate between ‘1991-01-01’ and ‘1991-12-01’;
- Searching for NULL
xv.To display the name and hiredate of employees who do not get any commission.
Select ename, hiredate from empl where comm is null;
xvi.To display the name and hiredate of employees who get commission.
Select ename, hiredate from empl where comm. is not null;

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 the records in the ascending order of name


SELECT * FROM EMPL ORDER BY ENAME;
Or SELECT * FROM EMPL ORDER BY ENAME ASC;

To arrange the records in the descending order of salary


SELECT * FROM EMPL ORDER BY SAL DESC;

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;

Ordering data based on an expression


To display the name, salary and bonus of all employees in the descending order of bonus. Bonus is calculated as
35% of the salary.
SELECT ENAME, SAL, SAL*0.35 AS "BONUS" FROM EMPL ORDER BY SAL*0.35 DESC;

Specifying custom sort order


To display the employees in the specified order of job (President, Manager, Analyst, Salesman, Clerk)
SELECT * FROM EMPL ORDER BY FIELD (JOB, 'President', 'Manager','Analyst', 'Salesman', 'Clerk');

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

Date and Time Functions


Function Description Example Output
1 Curdate() / Returns the current date Select curdate(); 2019-04-15
Current_date()
2 Now() Returns current date and time Select now(); 2019-04-15 10:20:45
3 Sysdate() Returns current date and time Select sysdate(); 2019-04-15 10:20:45
4 Date() Returns the date part from a Select date(now()); 2019-04-15
datetime expression
5 Month() Returns the month from the date Select month(now()); 4
Select month(‘2014-01-9’); 1
6 Year() Returns the year from the date Select year(now()); 2019
7 Dayname() Returns the name of the weekday Select dayname(now()); Monday
8 Dayofmonth() Returns the day of the month(1-31) Select dayofmonth(now()); 15
9 Dayofweek() Returns the day of the week(1-7) Select dayofweek(now()); 4
10 Dayofyear() Returns the day of the year (1-366) Select dayofyear(now()); 105

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;

To find the average salary of all managers.


SELECT AVG(SAL) FROM EMPL WHERE JOB='MANAGER';

To display the total number of employees in the table empl.


SELECT COUNT(*) FROM EMPL;
Or SELECT COUNT(EMPNO) FROM EMPL;

To display number of employees who get commission


SELECT COUNT(COMM) FROM EMPL;

To display the number of values in the job column of empl table.


SELECT COUNT(JOB) FROM EMPL;

To display the number of different jobs in the table.


SELECT COUNT(DISTINCT JOB) 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;

To display the average salary of each job.


SELECT JOB, AVG(SAL) FROM EMPL GROUP BY JOB;

To display the number of employees in each job within each department.


SELECT DEPTNO, JOB, COUNT(*) FROM EMPL GROUP BY DEPTNO,JOB;

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

You might also like