SQL Essentials Training & Certification
- 11k Enrolled Learners
- Weekend/Weekday
- Self Paced
MySQL Tutorial is the second blog in this blog series. In the previous blog ‘What is MySQL‘ , I introduced you to all the basic terminologies that you needed to understand before you get started with this relational database. In this blog of MySQL, you will be learning all the operations and command that you need to explore your databases.
The topics covered in this blog are mainly divided into 4 categories: DDL, DML, DCL & TCL.
Apart from the commands, following are the other topics covered in the blog:
We are going to cover each of these categories one by one.
In this blog on MySQL Tutorial, I am going to consider the below database as an example, to show you how to write commands.
StudentID | StudentName | ParentName | Address | City | PostalCode | Country | Fees |
01 | Haznitiz | Emiz | Dellys Road | Afir | 35110 | Algeria | 42145 |
02 | Shubham | Narayan | MG Road | Bangalore | 560001 | India | 45672 |
03 | Salomao | Valentim | Mayo Road | Rio Claro | 27460 | Brazil | 65432 |
04 | Vishal | Ramesh | Queens Quay | Toronto | 416 | Canada | 23455 |
05 | Park Jimin | Kim Tai Hyung | Gangnam Street | Seoul | 135081 | South Korea | 22353 |
Table 1: Sample Database – MySQL Tutorial
This section consists of those commands, by which you can define your database. The commands are:
Now, before I start with the commands, let me just tell you the way to mention the comments in MySQL.
Like any other programming language, there are mainly two types of comments.
--Select all: SELECT * FROM Students;
/*Select all the columns of all the records in the Students table:*/ SELECT * FROM Students;
Now, that you know how to mention comments in MySQL, let’s continue with the DDL commands.
The create statement is used to either create a schema, tables or an index.
This statement is used to create a database.
CREATE SCHEMA Database_Name;
CREATE SCHEMA StudentsInfo;
This statement is used to create a new table in a database.
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE Students ( StudentID int, StudentName varchar(255), ParentName varchar(255), Address varchar(255), PostalCode int, City varchar(255) );
This statement is used to create a new table from an existing table. So, this table gets the same column definitions as that of the existing table.
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
CREATE TABLE ExampleTable AS SELECT Studentname, Parentname FROM Students;
The ALTER command is used to add, modify or delete constraints or columns.
This statement is used to either add, modify or delete constraints and columns from a table.
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE Students ADD DateOfBirth date;
The DROP command is used to delete the database, tables or columns.
This statement is used to drop the complete schema.
DROP SCHEMA schema_name;
DROP SCHEMA StudentsInfo;
This statement is used to drop the entire table with all its values.
DROP TABLE table_name;
DROP TABLE table_name;
This statement is used to delete the data which is present inside a table, but the table doesn’t get deleted.
TRUNCATE TABLE table_name;
TRUNCATE TABLE Students;
This statement is used to rename one or more tables.
RENAME TABLE
tbl_name TO new_tbl_name
[, tbl_name2 TO new_tbl_name2] ...
RENAME Students TO Infostudents;
Now, before I move into the further sections, let me tell you the various types of Keys and Constraints that you need to mention while manipulating the databases.
There are mainly 5 types of Keys, that can be mentioned in the database.
Refer to the image below are the constraints used in the database.
Figure 1: Constraints Used In Database – MySQL Tutorial
Now, that you know the various types of keys and constraints, let’s move on to the next section i.e Data Manipulation Commands.
This section consists of those commands, by which you can manipulate your database. The commands are:
Apart from these commands, there are also other manipulative operators/functions such as:
The USE statement is used to mention which database has to be used to perform all the operations.
USE Database_name;
USE StudentsInfo;
This statement is used to insert new records in a table.
The INSERT INTO statement can be written in the following two ways:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
--You need not mention the column names
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
INSERT INTO Infostudents(StudentID, StudentName, ParentName, Address, City, PostalCode, Country) VALUES ('06', 'Sanjana','Jagannath', 'Banjara Hills', 'Hyderabad', '500046', 'India'); INSERT INTO Infostudents VALUES ('07', 'Shivantini','Praveen', 'Camel Street', 'Kolkata', '700096', 'India');
This statement is used to modify the existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Infostudents SET StudentName = 'Alfred', City= 'Frankfurt' WHERE StudentID = 1;
This statement is used to delete existing records in a table.
DELETE FROM table_name
WHERE condition;
DELETE FROM Infostudents WHERE StudentName='Salomao';
This statement is used to select data from a database and the data returned is stored in a result table, called the result-set.
The following are the two ways of using this statement:
SELECT column1, column2, ...
FROM table_name;
--(*) is used to select all from the table
SELECT * FROM table_name;
SELECT StudentName, City FROM Infostudents; SELECT * FROM Infostudents;
Apart from the individual SELECT keyword, we will be also seeing the following statements, which are used with the SELECT keyword:
This statement is used to return only distinct or different values. So, if you have a table with duplicate values, then you can use this statement to list distinct values.
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT Country FROM Students;
This statement is used to sort the desired results in ascending or descending order. By default, the results would be sorted in ascending order. If you want the records in the result-set in descending order, then use the DESC keyword.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT * FROM Infostudents ORDER BY Country; SELECT * FROM Infostudents ORDER BY Country DESC; SELECT * FROM Infostudents ORDER BY Country, StudentName; SELECT * FROM Infostudents ORDER BY Country ASC, StudentName DESC;
This statement is used with the aggregate functions to group the result-set by one or more columns.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
SELECT COUNT(StudentID), Country FROM Infostudents GROUP BY Country ORDER BY COUNT(StudentID) DESC;
Since the WHERE keyword cannot be used with aggregate functions, the HAVING clause was introduced.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
SELECT COUNT(StudentID), City FROM Infostudents GROUP BY City HAVING COUNT(Fees) > 23000;
This set of operators consists of logical operators such as AND/OR/NOT.
The AND operator is used to filter records that rely on more than one condition. This operator displays the records, which satisfy all the conditions separated by AND, and give the output TRUE.
SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND condition3 ...;
SELECT * FROM Infostudents WHERE Country='Brazil' AND City='Rio Claro';
The OR operator displays those records which satisfy any of the conditions separated by OR and gives the output TRUE.
SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR condition3 ...;
SELECT * FROM Infostudents WHERE City='Toronto' OR City='Seoul';
This operator displays a record when the condition (s) is NOT TRUE.
SELECT column1, column2, ... FROM table_name WHERE NOT condition;
SELECT * FROM Infostudents WHERE NOT Country='India'; --You can also combine all the above three operators and write a query like this: SELECT * FROM Infostudents WHERE Country='India' AND (City='Bangalore' OR City='Canada');
Figure 2: Arithmetic, Bitwise, Comparison & Compound Operators – MySQL Tutorial
This section of the article include the following functions:
This function returns the smallest value of the selected column in a table.
SELECT MIN(column_name) FROMtable_name WHEREcondition;
SELECT MIN(StudentID) AS SmallestID FROM Infostudents;
This function returns the largest value of the selected column in a table.
SELECT MAX(column_name) FROM table_name WHERE condition;
SELECT MAX(Fees) AS MaximumFees FROM Infostudents;
This function returns the number of rows that match the specified criteria.
SELECT COUNT(column_name) FROM table_name WHERE condition;
SELECT COUNT(StudentID) FROM Infostudents;
This function returns the average value of a numeric column that you choose.
SELECT AVG(column_name) FROM table_name WHERE condition;
SELECT AVG(Fees) FROM Infostudents;
This function returns the total sum of a numeric column that you choose.
SELECT SUM(column_name) FROM table_name WHERE condition;
SELECT SUM(Fees) FROM Infostudents;
This section includes the following operators:
This operator is an inclusive operator which selects values(numbers, texts or dates) within a given range.
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2;
SELECT * FROM Infostudents WHERE Fees BETWEEN 20000 AND 40000;
Since it is not possible to test for the NULL values with the comparison operators(=, <, >), we can use IS NULL and IS NOT NULL operators instead.
--Syntax for IS NULL SELECT column_names FROM table_name WHERE column_name IS NULL; --Syntax for IS NOT NULL SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
SELECT StudentName, ParentName, Address FROM Infostudents WHERE Address IS NULL; SELECT StudentName, ParentName, Address FROM Infostudents WHERE Address IS NOT NULL;
This operator is used in a WHERE clause to search for a specified pattern in a column of a table.
The mentioned below are the two wildcards that are used in conjunction with the LIKE operator:
SELECT column1, column2, ... FROM table_name WHERE column LIKE pattern;
Refer to the following table for the various patterns that you can mention with LIKE operator.
LIKE Operator | Description |
WHERE CustomerName LIKE ‘z% | Finds any values that start with “z” |
WHERE CustomerName LIKE ‘%z’ | Finds any values that end with “z” |
WHERE CustomerName LIKE ‘%and%’ | Finds any values that have “and” in any position |
WHERE CustomerName LIKE ‘_s%’ | Finds any values that have “s” in the second position. |
WHERE CustomerName LIKE ‘d_%_%’ | Finds any values that start with “d” and are at least 3 characters in length |
WHERE ContactName LIKE ‘j%l’ | Finds any values that start with “j” and ends with “l” |
Table 2: Patterns Mentioned With LIKE Operator – MySQL Tutorial
SELECT * FROM Infostudents WHERE StudentName LIKE 'S%';
This is a shorthand operator for multiple OR conditions which allows you to specify multiple values in a WHERE clause.
SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);
SELECT * FROM Infostudents WHERE Country IN ('Algeria', 'India', 'Brazil');
Note: You can also use IN while writing Nested Queries. Consider the below syntax:
This operator is used to test if a record exists or not.
SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);
SELECT StudentName FROM Infostudents WHERE EXISTS (SELECT ParentName FROM Infostudents WHERE StudentId = 05 AND Price < 25000);
This operator is used with a WHERE or HAVING clause and returns true if all of the subquery values meet the condition.
SELECT column_name(s) FROM table_name WHERE column_name operator ALL (SELECT column_name FROM table_name WHERE condition);
SELECT StudentName FROM Infostudents WHERE StudentID = ALL (SELECT StudentID FROM Infostudents WHERE Fees > 20000);
Similar to the ALL operator, the ANY operator is also used with a WHERE or HAVING clause and returns true if any of the subquery values meet the condition.
SELECT column_name(s) FROM table_name WHERE column_name operator ANY (SELECT column_name FROM table_name WHERE condition);
SELECT StudentName FROM Infostudents WHERE StudentID = ANY (SELECT SttudentID FROM Infostudents WHERE Fees BETWEEN 22000 AND 23000);
Now, that I have told you a lot about DML commands, let me just tell you in short about Nested Queries,Joins and Set Operations.
Nested queries are those queries which have an outer query and inner subquery. So, basically, the subquery is a query which is nested within another query such as SELECT, INSERT, UPDATE or DELETE. Refer to the image below:
Fig 3: Representation Of Nested Queries – MySQL Tutorial
JOINS are used to combine rows from two or more tables, based on a related column between those tables. The following are the types of joins:
Refer to the image below.
Fig 4: Representation Of Joins – MySQL Tutorial
Let’s consider the below table apart from the Infostudents table, to understand the syntax of joins.
CourseID | StudentID | CourseName | StartDate |
1 | 10 | DevOps | 09-09-2018 |
2 | 11 | Blockchain | 07-04-2018 |
3 | 12 | Python | 08-06-2018 |
Table 3: Sample Database – MySQL Tutorial
SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
SELECT Courses.CourseID, Infostudents.StudentName FROM Courses INNER JOIN Infostudents ON Courses.StudentID = Infostudents.StudentID;
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
SELECT Infostudents.StudentName, Courses.CourseID FROM Infostudents FULL OUTER JOIN Orders ON Infostudents.StudentID=Orders.StudentID ORDER BY Infostudents.StudentName;
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
SELECT Infostudents.StudentName, Courses.CourseID FROM Infostudents LEFT JOIN Courses ON Infostudents.CustomerID = Courses.StudentID ORDER BY Infostudents.StudentName;
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
SELECT Courses.CourseID FROM Courses RIGHT JOIN Infostudents ON Courses.StudentID = Infostudents.StudentID ORDER BY Courses.CourseID;
There are mainly three set operations: UNION, INTERSECT, SET DIFFERENCE. You can refer to the image below to understand the set operations in SQL.
Now, that you guys know the DML commadsn. Let’s move onto our next section and see the DCL commands.
This section consists of those commands which are used to control privileges in the database. The commands are:
This command is used to provide user access privileges or other privileges for the database.
GRANT privileges ON object TO user;
GRANT CREATE ANY TABLE TO localhost;
This command is used to withdraw user’s access privileges given by using the GRANT command.
REVOKE privileges ON object FROM user;
REVOKE INSERT ON *.* FROM Infostudents;
Now, let’s move on to the last section of this blog i.e. the TCL Commands.
This section of commands mainly deals with the transaction of the database. The commands are:
This command saves all the transactions to the database since the last COMMIT or ROLLBACK command.
COMMIT;
DELETE FROM Infostudents WHERE Fees = 42145; COMMIT;
This command is used to undo transactions since the last COMMIT or ROLLBACK command was issued.
ROLLBACK;
DELETE FROM Infostudents WHERE Fees = 42145; ROLLBACK;
This command creates points within the groups of transactions in which to ROLLBACK. So, with this command, you can simply roll the transaction back to a certain point without rolling back the entire transaction.
SAVEPOINT SAVEPOINT_NAME; --Syntax for saving the SAVEPOINT ROLLBACK TO SAVEPOINT_NAME; --Syntax for rolling back to the Savepoint command
SAVEPOINT SP1; DELETE FROM Infostudents WHERE Fees = 42145; SAVEPOINT SP2;
You can use this command to remove a SAVEPOINT that you have created.
RELEASE SAVEPOINT SAVEPOINT_NAME;
RELEASE SAVEPOINT SP2;
This command gives a name to the transaction.
SET TRANSACTION [ READ WRITE | READ ONLY ];
I hope you enjoyed reading this blog on MySQL Tutorial blog. We have seen the different commands that will help you write queries and play around with your databases.
If you wish to learn more about MySQL and get to know this open source relational database, then check out our MySQL DBA Certification Training which comes with instructor-led live training and real-life project experience. This training will help you understand MySQL in depth and help you achieve mastery over the subject.
Got a question for us? Please mention it in the comments section of ”MySQL Tutorial” and I will get back to you.
edureka.co