All in One Mysql Notes
All in One Mysql Notes
Database
o A collection of interrelated data stored together to serve multiple applications.
Purpose of DBMS
Database Management System is a software that is responsible for storing,
maintaining, and utilizing databases.
Reduces data redundancy ( Duplication of data)
Control data inconsistency to a large extent. When redundancy is not controlled, there
may be occasions on which 2 entries of same data not been agreed. This is called
inconsistent. If redundancy retained for some technical purpose then when there is a
change in one duplicate value the other one also will get changed. This concept is
called propagating updates.
Facilitates sharing of data.
Enforce standards.
Ensures data security
Integrity maintained through databases.(Conditions or rules)
o Different users
End user
Application system analyst
Physical storage system analyst
o Database Abstraction
A good DBMS system ensures easy smooth and efficient data structures .Should
be easy to access for all the 3 users.
o Various levels of database implementation
Internal level (physical level): How the data is stored in the storage medium.
Conceptual level : It describes what data are actually stored in the database. It also
describes the relationships existing among data. In this the database is described in
terms of simple data structures.
External view (view level) : In this the data is viewed by individual users. Most of the
users are not concerned with all information in the database.
o Different data models
Relational data model
Hierarchical data model
Network data model
o Relational data model
In this the data are organized into tables.
The rows are called tuples and the columns are called attributes.
A row in a table represents relationship among set of values.
The relational data model is based on collection of tables.
The user in this type can edit , delete , add tuples.
o Network data model
In this the collection of records are connected with each other by means of links.
The link is association between 2 records.
In network model we can do operations link find , insert , delete , modify etc.,
o The hierarchical data model
In this model the records are organized as trees.
The relationship is parent child relationship.
The operations in this model performed by DML(Data Manipulation Language)
1
Domain
A domain is a pool of values from which the actual values appearing in a given
column are drawn.
Tuple: The rows of relation are called tuple.
Attributes: The columns of a relation table is called attributes.
Degree: The number of attributes in a relation is called DEGREE.
Cardinality : The number of rows in a relation is called cardinality.
View
A view is a table that does not really exist in its own right but is instead derived from
one or more underlying base tables.
Keys
o Primary Key : A primary key is a set of one or more attributes that can uniquely
identify tuples within the relation
o Candidate Keys : All attribute combinations inside a relation that can serve as
primary key are candidate keys as they are candidates for the primary key
position.
o Alternate Key : A candidate key that is not the primary key is called alternate key.
Candidate Key:
A candidate key is a set of attributes (or attribute) which uniquely identify the tuples
in relation or table. As we know that Primary key is a minimal super key, so there is
one and only one primary key in any relationship but there is more than one
candidate key can take place. Candidate key’s attributes can contain a NULL value
which opposes to the primary key. For example,
Student{ID, First_name, Last_name, Age}
Here we can see the two candidate keys ID and {First_name, Last_name, DOB}.
So here, there are present more than one candidate keys, which can uniquely
identify a tuple in a relation.
o 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.
o Referential Integrity
It 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.
Relational Database
A relational database is a collection of data items organized as logically related tables.
Relational Database Management System
The software required to handle/manipulate these table/relations is know as Relational Database
Management System (RDBMS). Example - Oracle , Sybase, DB2, MSSQL, etc.
Table/Relation
A group of rows and columns from a table. The horizontal subset of the Table is known as a
Row/Tuple. The vertical subset of the Table is known as a Column/an Attribute.
A relation in a database has the following characteristics:
Every value in a relation is a atomic-i.e. it can not be further divided
Names of columns are distinct and order of columns is immaterial
The rows in the relation are not ordered
Relational algebra
Relational algebra is a formal system for manipulating relations. Set of operations that can be
carried out on a relation:
Selection : To select a horizontal subset of a relation
Projection : To select vertical subset of a relation
Cartesian Product: It operates on two relations and is denoted by X. for example
Cartesian product of two relation R1 and R2 is represented by R=R1X R2. The degree
of R is equal to sum of degrees of R1 and R2. The cardinality of R is product of
cardinality of R1 and cardinality of R2
Example cartesian Product
The table R1
Empno Ename Dept
1 Bill A
2 Sarah C
3
3 John A
The table R2
Dno Dname
A Marketing
B Sales
C Legal
R1 X R2
Empno Ename Dept Dno Dname
1 Bill A A Marketing
1 Bill A B Sales
1 Bill A C Legal
2 Sarah C A Marketing
2 Sarah C B Sales
2 Sarah C C Legal
3 John A A Marketing
3 John A B Sales
3 John A C Legal
SELECT * FROM student WHERE fess > 7000 AND fees < 8000;
rno name fees dob class
10 Alex 7800 1998-10-03 K12
12 Alisha 7800 1999-07-03 K11
5
12 Alisha 7800 1999-07-03 K11
6
name
Alex
Peter
7
SELECT class, name, dob, fees FROM student ORDER BY class, name DESC;
class name dob fees
K11 John 2000-12-13 6900
K11 Alisha 1999-07-03 7900
K12 Peter 1997-11-15 6700
K12 Alex 1998-10-03 7800
COUNT(rno)
4
SUM(fees)
29300
8
AVG(fees)
7325.000
0
Examples :
ALTER TABLE student ADD (grade CHAR(2));
ALTER COMMANDS
DROP DATABASE testDB;
10
DROP COLUMN Email;
ALTER TABLE `members` CHANGE COLUMN `full_names` `fullname` char(250) NOT NULL;
MODIFY KEYWORD
The MODIFY Keyword allows you to
The script below changes the width of “fullname” field from 250 to 50.
11
ALTER TABLE Persons
DROP INDEX UC_Person;
When a constraint is applied to a single column, it is called a column level constraint but if a
constraint is applied on a combination of columns it is called a table constraint.
Joins
Equi Join is a join having a condition where we use an While performing a natural join, we
equal operator. do not use an equal operator.
We use Equi Join if we need both tables in the output We use Natural Join if we need only
without missing any column. the unique columns without
repetition.
We can use the WHERE clause or the ON clause in Equi Just use the keyword NATURAL
join. JOIN to perform the task.
The common column comes twice if we select all columns The common column comes only
in the query. once, even if we select all columns in
the query.
SQL EQUI JOIN is a specific type comparison base join (equally comparison) not allowing
other comparison operator such as <, > <= etc. And create record set result that are combining
columns value from the tables (two or more table).
Cross JOIN
SQL> SELECT * 13
Suppose we want to get all member records against all the movie records, we can use the script
shown below to get our desired results.
The inner JOIN is used to return rows from both tables that satisfy the given condition.
Not null
ALTER TABLE emp MODIFY sal int NOT NULL;
ALTER TABLE emp MODIFY sal INT NULL;
Unique
Alter table emp add unique(dept);
alter table emp drop INDEX dept;
Check
Alter table emp add check(sal<=200000);
ALTER TABLE emp DROP CHECK emp_chk_1;
Default
Alter table emp alter address set default "Peelamedu";
ALTER TABLE emp ALTER address DROP DEFAULT;
14
CREATE TABLE A(ID INT PRIMARY KEY,NAME CHAR(10));
AUTO_INCREMENT
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,LastName archar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (Personid));
ALTER TABLE Persons AUTO_INCREMENT=100;
15
point is specified in the d parameter. The maximum
number for size is 65. The maximum number for d is 30.
The default value for size is 10. The default value for d is
0.
16
Difference between char and varchar
The candidate key is a set of attributes that uniquely identify the rows in a table. An
alternate key is a column or group of columns that uniquely identify every row in a table.
Alternate Key: In a table when more than one column is used for the identification of tuples in the
table, then that is an alternate key.
17
Each table has only one primary key, although there are several choices.
All the columns in the table other than the primary key act as an alternate key for that
table.
Candidate Key: This key is also used to identify the rows in a table.
Foreign keys - Contain one or more columns whose values match a primary or alternate key in
some other table.
In the following example, the TITLE table has a primary, alternate and foreign key:
The primary key, TITLE_ID contains the column TITLE ISBN, and uniquely identifies each book
in the table.
The alternate key, TITLE_NAME, contains the columns TITLE NAME and TITLE TYPE, and
enforces a constraint that no two titles of the same type can have the same name.
The foreign key contains the column PUBLISHER ID and references the primary key column in
the Publisher table.
18
19
20
5. MYSQL FUNCTIONS
MySQL has many built-in functions.
This reference contains string, numeric, date, and some advanced functions in MySQL.
Function Description
ASCII Returns the ASCII value for the specific character
CHAR_LENGTH Returns the length of a string (in characters)
CHARACTER_LENGTH Returns the length of a string (in characters)
CONCAT Adds two or more expressions together
Returns the position of the first occurrence of a string in another
INSTR
string
LCASE Converts a string to lower-case
LEFT Extracts a number of characters from a string (starting from left)
LENGTH Returns the length of a string (in bytes)
LOWER Converts a string to lower-case
LTRIM Removes leading spaces from a string
MID Extracts a substring from a string (starting at any position)
RIGHT Extracts a number of characters from a string (starting from right)
RTRIM Removes trailing spaces from a string
SUBSTR Extracts a substring from a string (starting at any position)
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
UPPER Converts a string to upper-case
Function Description
ABS Returns the absolute value of a number
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is >= to a number
CEILING Returns the smallest integer value that is >= to a number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records returned by a select query
FLOOR Returns the largest integer value that is <= to a number
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
pg. 21
MOD Returns the remainder of a number divided by another number
POW Returns the value of a number raised to the power of another number
POWER Returns the value of a number raised to the power of another number
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal places
SIGN Returns the sign of a number
SQRT Returns the square root of a number
SUM Calculates the sum of a set of values
TRUNCATE Truncates a number to the specified number of decimal places
Function Description
CURDATE Returns the current date
DATE Extracts the date part from a datetime expression
DAY Returns the day of the month for a given date
DAYNAME Returns the weekday name for a given date
DAYOFMONTH Returns the day of the month for a given date
DAYOFWEEK Returns the weekday index for a given date
DAYOFYEAR Returns the day of the year for a given date
MONTH Returns the month part for a given date
MONTHNAME Returns the name of the month for a given date
NOW Returns the current date and time
SYSDATE Returns the current date and time
TIME Extracts the time part from a given time/datetime
WEEKDAY Returns the weekday number for a given date
WEEKOFYEAR Returns the week number for a given date
YEAR Returns the year part for a given date
AGGREGATE FUNCTIONS
To perform such calculations in a query, you use aggregate functions. By
definition, an aggregate function performs a calculation on a set of values and
returns a single value. MySQL provides many aggregate functions that include
AVG , COUNT , SUM , MIN , MAX , etc.
1.SUM
2.AVG
3.MAX
4.MIN
5.COUNT
STRING FUNCTIONS
1.SELECT SUBSTR(COACHNAME,1,2) FROM CLUB WHERE DATEOFAPP>”1998-01-31”;
o/p : FIRST 2 CHARECTERS FROM THE COACHNAME ALSO DEPENDING UPON THE
DATE)
2.SELECT LOWER(ENAME) FROM EMP;
(WILL CONVERT ALL THE NAMES INTO LOWER CASE)
3.SELECT UPPER(ENAME) FROM EMP;
(WILL CONVERT ENAME TO UPPER CASE)
4.SELECT INSTR(“corporate floor”,”or”)
(RETURNS THE FIRST OCCURANCE POSITION OF THE GIVEN STRING);
O/P: 2
5.SELECT LENGTH(“PSG PUBLIC SCHOOLS”)
O/P : 18
6.SELECT LEFT(“USS/23/67/09”,3)
O/P: USS(RETURNS 3 CHARECTERS FROM THE LEFT)
7.SELECT RIGHT(“USS/23/67/09”,3);
O/P : /09 (RETURNS 3 CHARECTERS FROM THE RIGHT)
8.MID AND SUBSTR ARE THE SAME
1.SELECT CURDATE()
O/P : RETURNS CURRENT DATE
2. SELECT DATE('2003-12-31 01:02:03');
O/P: 2003-12-31
3. SELECT MONTH('2008-02-03');
O/P: 2
4. SELECT YEAR('1987-01-01');
pg. 23
O/P: 1987
5. SELECT DAYNAME('2007-02-03');
O/P: 'Saturday'
6. SELECT DAYOFMONTH('2007-02-03');
O/P: 3
7. SELECT DAYOFWEEK('2007-02-03');
O/P: 7
8. SELECT DAYOFYEAR('2007-02-03');
O/P: 34
9.SELECT NOW()
RETURNS CURRENT DATE AND TIME
10.SYSDATE returns the time at which it executes. This differs from the behavior for NOW(), which
returns a constant time that indicates the time at which the statement began to execute. (Within a
stored function.
pg. 24