MySQL Database Management Basics
MySQL Database Management Basics
Data:
Data are individual facts, statistics, or items of information, often numeric.
Information:
Information is processed, organized and structured data.
Database:
A database is a collection of information that is organized so that it can be
easily accessed, managed and updated.
OR
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system.
Database Table:
Tables are database objects that contain all the data in a database. In
tables, data is logically organized in a row-and-column format similar to a spreadsheet.
Each row represents a unique record, and each column represents a field in the record.
What is SQL?
SQL is a standard language for storing, manipulating and retrieving data in
databases.
OR:
SQL language used in programming and designed for managing data held in a
relational database management system
SQL stands for Structured Query Language.
SQL lets you access and manipulate databases.
SQL is an ANSI (American National Standards Institute) Standard
Data Management:
Data management deals with managing large amount of information, which
involves:
the storage of information
the provision of mechanisms for the manipulation of information
providing safety of information stored under various circumstances
1. File-based systems
2. Database systems
File-Based Systems:
In a file-based systems data is stored in discrete files and a collection of such files is stored
on a computer.
Rows in the table were called records and columns were called fields.
Database Systems:
Database Systems evolved in the late 1960s to address common issues in
applications handling large volumes of data, which are also data intensive.
At any point of time, data can be retrieved from the database, added, and searched
based on some criteria in these databases.
Databases are used to store data in an efficient and organized manner. A database
allows quick and easy management of data.
Data stored in this form is not permanent. Records in such manual files can only
be maintained for a few months or few years
What is Entity?
An entity is something that exists as itself, as a subject or as an object.
An entity is a person, place, thing, object, event, or even a concept, which can be
distinctly identified.
Each entity has certain characteristics known as attributes.
For example, the student entity might include attributes like student number,
name, and grade. Each attribute should be named appropriately.
For example: the entities in a university are students, faculty members, and
courses.
A grouping of related entities becomes an entity set. Each entity set is given a
name. The name of the entity set reflects the contents.
Examples:
tinyint 0 255
bit 0 1
char
1
Maximum length of 8,000 characters.( Fixed length non-Unicode characters)
varchar
2
Maximum of 8,000 characters.(Variable-length non-Unicode data).
varchar(max)
3
Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server
2005 only).
text
4
Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.
Syntax:
CREATE DATABASE databasename;
Syntax:
create table table_name(
id int,
f_name varchar(20),
l_name varchar(20),
age int
)
Syntax:
TRUNCATE TABLE table_name;
Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO Customers(CustomerName, ContactName, Address, City, PostalCode,
Country)VALUES ('Cardinal', '[Link]', 'Skagen 21', 'Stavanger', '4006', 'Norway');
Syntax:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO usertbl VALUES ('[value-1]','[value-2]','[value-3]')
Syntax:
SELECT * FROM table_name;
* means ALL.
Or
The SELECT DISTINCT statement is used to return only distinct (different) values.
Syntax:
SELECT DISTINCT column1, column2,
FROM table_name;
Example:
SELECT DISTINCT * FROM usertbl
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
SELECT * FROM Customers
WHERE Country='Mexico'
OR
WHERE CustomerID=1;
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
Example of Like:
WHERE CustomerName LIKE Finds any values that start with "a"
'a%'
WHERE CustomerName LIKE Finds any values that end with "a"
'%a'
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 2
'a_%' characters in length
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3
'a__%' characters in length
WHERE ContactName LIKE Finds any values that start with "u" and ends with "a"
'u%a'
Example of IN:
SELECT * FROM Customers
WHERE City IN ('Paris','London');
AND EXAMPLE:
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
OR EXAMPLE:
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
NOT EXAMPLE:
SELECT * FROM Customers
WHERE NOT Country='Germany';
Example:
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
Another Example:
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
Example (Ascending):
SELECT * FROM Customers
ORDER BY Country;
Example (Descending):
SELECT * FROM Customers
ORDER BY Country DESC;
Another Example:
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
Example:
UPDATE Customers
SET ContactName = 'Arif Alvi', City= 'Frankfurt'
WHERE CustomerID = 1;
Here where clause is mandatory if you will not write where condition so all data will have updated.
Syntax:
DELETE FROM table_name WHERE condition;
Here where clause is mandatory if you will not write where condition so all data will have deleted.
Example:
DELETE FROM Customers WHERE CustomerName='ali';
Aggregate Functions:
SQL MIN(), MAX(), COUNT , AVG,SUM FUNCTIONS
Min()
SELECT MIN(column_name) FROM table_name;
Example:
Max()
SELECT MAX(Price) FROM product;
COUNT()
SELECT COUNT(P_ID) FROM products;
AVG()
SELECT AVG(Price) FROM Products;
SUM()
SELECT SUM(price) FROM products;
Syntax:
CONSTRAINTS:
Constraints are the rules enforced on the data columns of a table. These are used to limit
the type of data that can go into a table. This ensures the accuracy and reliability of the data
in the database.
Example:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
);
SQL Default CONTSTRAINTS:
Provides a default value for a column when none is specified.
Example:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
SALARY DEFAULT 5000,
);
RELATION:
Syntax:
CREATE TABLE CUSTOMERS(
C_ID INT primary key auto_increment,
C_NAME VARCHAR (20) NOT NULL,
C_AGE INT NOT NULL,
C_ADDRESS CHAR (25)
);
Examples:
Another Example:
The following SQL statement creates two aliases, one for the CustomerID column
and one for the CustomerName column:
Example:
SELECT CustomerID AS ID,CustomerName AS Customer
FROM Customers;
JOINS:
INNER JOINS:
The INNER JOIN keyword selects records that have matching values in both tables.
Example:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
General Example:
select * from employee as em INNER JOIN department as dp on em.dept_id = dp.dept_id
Join Three Tables:
SELECT [Link],[Link],[Link]
FROM ((Orders
INNER JOIN Customers ON [Link] = [Link])
INNER JOIN Shippers ON [Link] = [Link]);
LEFT JOINS:
The LEFT JOIN keyword returns all records from the left table (table1), and the matching
records (if any) from the right table (table2).
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT [Link],[Link]
FROM Customers LEFT JOIN Orders ON [Link] = [Link]
ORDER BY [Link];
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even
if there are no matches in the right table (Orders).
RIGHT JOINS:
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records (if any) from the left table (table1).
Syntax:
SELECT column_name(s)FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT [Link],[Link],[Link]
FROM Orders RIGHT JOIN Employees ON [Link] =
[Link] ORDER BY [Link];
Note: The RIGHT JOIN keyword returns all records from the right table (Employees),
even if there are no matches in the left table (Orders).
CROSS JOINS:
The CROSS JOIN keyword returns all records from both tables (table1 and table2).
Syntax:
SELECT column_name(s)FROM table1
CROSS JOIN table2;
Example:
SELECT [Link],[Link] FROM Customers
CROSS JOIN Orders;
Note:
If you add a WHERE clause (if table1 and table2 has a relationship), the CROSS JOIN will
produce the same result as the INNER JOIN clause:
Another Example:
SELECT [Link],[Link]
FROM CustomersCROSS JOIN Orders
WHERE [Link]=[Link];
Group by Statement:
The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of customers in each country".
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
Example:
SELECT COUNT(CustomerID), Country FROM Customers
GROUP BY Country;
Syntax:
SELECT column_name(s) FROM table_name WHERE condition
GROUP BY column_name(s) HAVING condition ORDER BY column_name(s);
Example:
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country
HAVING COUNT(CustomerID) > 5;
UNION JOINS:
Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Example:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Example:
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers
ORDER BY City;
Example:
SELECT City, Country FROM Customers WHERE Country='Germany' UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
A MySQL subquery is called an inner query while the query that contains the subquery is
called an outer query.
Example:
select * from employee where c_id = (select c_id from city where name = 'karachi');
Not Exist:
select * FROM employee where not EXISTS (SELECT c_id FROM city where name =
'hyd');
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example:
Example:
ALTER TABLE employee
DROP COLUMN Email;
Alter Table Rename Column Name:
ALTER TABLE table_name
CHANGE email email _address varchar(20);
Syntax:
ALTER TABLE table_name
ADD UNIQUE(email) ;
IF Clause:
The IF() function returns a value if a condition is TRUE, or another value if a condition is
FALSE.
Syntax:
IF(condition, value_if_true, value_if_false)
Example:
SELECT OrderID, Quantity, IF(Quantity>10, "MORE", "LESS")
FROM OrderDetails;
Another Example:
SELECT P_name , price , if(price>2000,"High Rate Product","Low Rate Product") as
Stage from product
Case Clause:
The CASE statement goes through conditions and returns a value when the first condition
is met (like an if-then-else statement). So, once a condition is true, it will stop reading
and return the result. If no conditions are true, it returns the value in the ELSE clause.
Example:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
Another Example:
SELECT P_id, price,
CASE
WHEN price > 4000 THEN 'The quantity is greater than All'
Another Example:
SELECT id,stname,percentage,
CASE
ELSE "FAIL"
END as Grade
FROM studentresult
Function Description
POW Returns the value of a number raised to the power of another number
Function Description
ADDDATE Adds a time/date interval to a date and then returns the date
ADDTIME Adds a time interval to a time/datetime and then returns the time/datetime
SUBDATE Subtracts a time/date interval from a date and then returns the date
QUARTER Returns the quarter of the year for a given date value
User Defined functions are useful when you want to extend the functionalities of your
MySQL server.
1. User-defined functions take zero or more input parameters, and return a single
value such as a string, integer, or real values.
2. You can define simple function that operate on a single row at a time or an
aggregate functions that operate on groups of rows.
3. You can indicate that a function returns NULL or that an error occurred.
User defined function syntax is very similar to stored procedures in MySQL. Here I have
created simple user-defined functions which are to calculate available credits in the user
account.
END //
DELIMITER;
END //
DELIMITER ;
When we perform any changes with the physical structure of the table in the database,
then we need DDL commands. CREATE, ALTER, RENAME, DROP, TRUNCATE, etc
commands come into this category. Those commands can’t be rolled back.
As we can see the name Data Manipulation language, so once the tables/database are
created, to manipulate something inside that stuff we require DML commands. Merits of
using these commands are if incase any wrong changes happened, we can roll back/undo
it.
Example:
Example:
This manages the issues related to the transaction in any database. This is used to rollback
or commit in the database.
Example:
ROLLBACK;
COMMIT;
Conclusion:
These commands and clauses we have discussed above are very useful in real-time
scenarios as it provides the basic concepts of how to use SQL queries to fetch and
manipulate data in the database. Apart from this, while using advance and analytical
queries like window function etc, these clauses are very important.
ER Diagram stands for Entity Relationship Diagram, also known as ERD is a diagram
that displays the relationship of entity sets stored in a database. In other words, ER
diagrams help to explain the logical structure of databases. ER diagrams are created
based on three basic concepts: entities, attributes and relationships.
ER Diagrams contain different symbols that use rectangles to represent entities, ovals to
define attributes and diamond shapes to represent relationships.
There are three main types of relationships in a database expressed using cardinality
notation in an ER diagram.
one-to-one
one-to-many
many-to-many
What is Normalization?
Normalization is the process to eliminate data redundancy and enhance data integrity in the
table. Normalization also helps to organize the data in the database. It is a multi-step
process that sets the data into tabular form and removes the duplicated data from the
relational tables.
Normalization organizes the columns and tables of a database to ensure that database
integrity constraints properly execute their dependencies. It is a systematic technique of
decomposing tables to eliminate data redundancy (repetition) and undesirable
characteristics like Insertion, Update, and Deletion anomalies.
A table is referred to as being in its First Normal Form if atomicity of the table is 1.
Here, atomicity states that a single cell cannot hold multiple values. It must hold only
a single-valued attribute.
The First normal form disallows the multi-valued attribute, composite attribute, and
their combinations.
Now you will understand the First Normal Form with the help of an example.
Below is a students’ record table that has information about student roll number, student
name, student course, and age of the student.
In the studentsrecord table, you can see that the course column has two values. Thus it
does not follow the First Normal Form. Now, if you use the First Normal Form to the
above table, you get the below table as a result.
By applying the First Normal Form, you achieve atomicity, and also every column has
unique values.
Before proceeding with the Second Normal Form, get familiar with Candidate Key and
Super Key.
Candidate Key
A candidate key is a set of one or more columns that can identify a record uniquely in a
table, and YOU can use each candidate key as a Primary Key.
Super Key:
Super key is a set of over one key that can identify a record uniquely in a table, and the
Primary Key is a subset of Super Key.
The first condition for the table to be in Second Normal Form is that the table has to be in
First Normal Form. The table should not possess partial dependency. The partial
dependency here means the proper subset of the candidate key should give a non-prime
attribute.
Now understand the Second Normal Form with the help of an example.
The Location table possesses a composite primary key cust_id, storeid. The non-key
attribute is store_location. In this case, store_location only depends on storeid, which is a
part of the primary key. Hence, this table does not fulfill the second normal form.
To bring the table to Second Normal Form, you need to split the table into two parts. This
will give you the below tables:
As you have removed the partial functional dependency from the location table, the
column store_location entirely depends on the primary key of that table, storeid.
Now that you understood the 1st and 2nd Normal forms, you will look at the next part of
this Normalization in SQL tutorial.
The first condition for the table to be in Third Normal Form is that the table should be
in the Second Normal Form.
The second condition is that there should be no transitive dependency for non-prime
attributes, which indicates that non-prime attributes (which are not a part of the
candidate key) should not depend on other non-prime attributes in a table. Therefore, a
transitive dependency is a functional dependency in which A → C (A determines C)
indirectly, because of A → B and B → C (where it is not the case that B → A).
The third Normal Form ensures the reduction of data duplication. It is also used to
achieve data integrity.
Below is a student table that has student id, student name, subject id, subject name, and
address of the student as its columns.
In the above student table, stu_id determines subid, and subid determines sub. Therefore,
stu_id determines sub via subid. This implies that the table possesses a transitive
functional dependency, and it does not fulfill the third normal form criteria.
Now to change the table to the third normal form, you need to divide the table as shown
below:
As you can see in both the tables, all the non-key attributes are now fully functional,
dependent only on the primary key. In the first table, columns name, subid, and addresses
only depend on stu_id. In the second table, the sub only depends on subid.
The first condition for the table to be in Boyce Codd Normal Form is that the table should
be in the third normal form. Secondly, every Right-Hand Side (RHS) attribute of the
functional dependencies should depend on the super key of that particular table.
For Example:
You have a functional dependency X → Y. In the particular functional dependency, X
has to be the part of the super key of the provided table.
Another important point to be noted here is that one professor teaches only one subject,
but one subject may have two professors.
Which exhibit there is a dependency between subject and professor, i.e. subject depends
on the professor's name.
to
The table is in 1st Normal form as all the column names are unique, all values are atomic,
and all the values stored in a particular column are of the same domain.
The table also satisfies the 2nd Normal Form, as there is no Partial Dependency.
And, there is no Transitive Dependency; hence, the table also satisfies the 3rd Normal
Form.
This table follows all the Normal forms except the Boyce Codd Normal Form.
As you can see stuid, and subject forms the primary key, which means the subject
attribute is a prime attribute.
BCNF does not follow in the table as a subject is a prime attribute, the professor is a non-
prime attribute.
To transform the table into the BCNF, you will divide the table into two parts. One table
will hold stuid which already exists and the second table will hold a newly created
column profid.
And in the second table will have the columns profid, subject, and professor, which
satisfies the BCNF.
With this, you have reached the conclusion of the ‘Normalization in SQL’ tutorial.
Conclusion:
In this tutorial, you have seen Normalization in SQL and understood the different Normal
forms of Normalization. Now, you can organize the data in the database and remove the
data redundancy and promote data integrity. This tutorial also helps beginners for their
interview processes to understand the concept of Normalization in SQL.
MYSQL CREATE VIEW STATEMENT:
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if the data
were coming from one single table.
Syntax:
Syntax:
Indexes are used to retrieve data from the database more quickly than otherwise. The
users cannot see the indexes; they are just used to speed up searches/queries.
Create Index Syntax:
Example:
MYSQL TRIGGERS:
A trigger in MySQL is a set of SQL statements stored in the database. It is a special type
of stored procedure that is invoked automatically in response to an event. Each trigger
is associated with a table, which is activated on any DML statement such as INSERT,
UPDATE, or DELETE.
A trigger is called a special procedure because it cannot be called directly like a stored
procedure. The main difference between the trigger and procedure is that a trigger is called
automatically when a data modification event is made against a table. In contrast, a stored
procedure must be called explicitly.
Statement-Level Trigger: It is a trigger, which is fired once for each event that occurs on
a table regardless of how many rows are inserted, updated, or deleted.
NOTE: We should know that MySQL doesn't support statement-level triggers. It provides
supports for row-level triggers only.
Syntax:
Example:
Delimiter //
CREATE TRIGGER Trigger_Name AFTER Insert
ON student
FOR EACH ROW
Begin
Insert into st_audit values(null,concat(‘A row is inserted in student table at’ , now()));
End //
Delimiter ;
Mysql Triggers provide us 2 magical or virtual tables called NEW and OLD.
When we inert a row in a table then that row is also inserted in NEW table.
When we delete a row from a table then that row is also inserted in OLD table.
DELIMITER //
CREATE TRIGGER idgenerator BEFORE INSERT
on product FOR EACH ROW
BEGIN
INSERT INTO pseqid VALUES(null);
SET [Link] = concat('PD-',LAST_INSERT_ID());
END //
DELIMITER ;
Transactions have the following four standard properties, usually referred to by the
acronym ACID −
Atomicity − This ensures that all operations within the work unit are completed
successfully; otherwise, the transaction is aborted at the point of failure and previous
operations are rolled back to their former state.
Consistency − This ensures that the database properly changes states upon a
successfully committed transaction.
Isolation − This enables transactions to operate independently on and transparent to
each other.
Durability − This ensures that the result or effect of a committed transaction persists
in case of a system failure.
In MySQL, the transactions begin with the statement BEGIN WORK and end with either
a COMMIT or a ROLLBACK statement. The SQL commands between the beginning
and ending statements form the bulk of the transaction.