0% found this document useful (0 votes)
142 views

MySQL-Full Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views

MySQL-Full Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

1.1 What is a Database?

• A database is an organized collection of data stored in a computer system and usually controlled
by a database management system (DBMS).
• Structured query language (SQL) is commonly used for data querying and writing.
• The Database is an essential part of our life. We encounter several activities that involve our
interaction with databases, for example in the bank, in the railway station, in school, in a grocery
store, etc.
• These are the instances where we need to store a large amount of data in one place and fetch
these data easily.

1.2 What is Data?

• Data is statically raw and unprocessed information.


• For example – name, class, marks, etc.
• In computer language, a piece of information that can be translated into a form for efficient
movement and processing is called data.
• It can be used in a variety of forms like text, numbers, media, bytes, etc.
• Data is interchangeable information.

Application: Company Information, Account information, manufacturing, banking, finance


transactions, telecommunications.

There are many databases available like MySQL, Sybase, Oracle, MongoDB, Informix,
PostgreSQL, SQL Server, etc.

SQL or Structured Query Language is used to operate on the data stored in a database.

1.3.1 Advantage of DBMS

Controls redundancy

It stores all the data in a single database file, so it can control data redundancy (when the same data
is stored in multiple tables. This can happen intentionally for data backup, faster access, or easier
updates).

Data Sharing

An authorized user can share the data among multiple users.

Backup

It provides a backup and recovery subsystem. This recovery system creates automatic data from
system failure and restores data if required.

Multiple user interfaces

It provides a different type of user interfaces like GUI, and application interfaces.

1.3.2 Disadvantage of DBMS

Size
1|Page
It occupies large disk space and large memory to run efficiently.

Cost

DBMS requires a high-speed data processor and larger memory to run DBMS software, so it is costly.

Complexity

DBMS creates additional complexity and requirements.

1.4 Types of Databases

There are various types of databases used for storing different varieties of data:

1.5 RDBMS (Relational Database Management System)

The word RDBMS is termed as 'Relational Database Management System.' It is represented as a table
that contains rows and columns.

A relational database contains the following components:

• Table
• Record/ Tuple
• Field/Column name /Attribute
• Instance
• Schema
• Keys

An RDBMS is a tabular DBMS that maintains the security, integrity, accuracy, and consistency of the
data.

2|Page
Following are the various terminologies of RDBMS:

1.6 Difference between DBMS and RDBMS

No. DBMS RDBMS

1) DBMS applications store data as RDBMS applications store data in a


file. tabular form.

2) In DBMS, data is generally stored in In RDBMS, the tables have an identifier


either a hierarchical form or a called primary key, and the data values
navigational form. are stored in the form of tables.

3) DBMS does not apply any RDBMS defines the integrity


security with regard to data constraint for the purpose of ACID
manipulation. (Atomocity, Consistency, Isolation, and
Durability) property.

4) DBMS uses a file system to store in RDBMS, data values are stored in the
data, so there will be no relation form of tables, so
between the tables. a relationship between these data
values will be stored in the form of a
table as well.

5) DBMS is meant to be for small RDBMS is designed to handle large


organizations and deal with small amounts of data. it supports multiple
data. it supports a single user. users.

6) Examples of DBMS are file Examples of RDBMS


systems, XML , etc. are MySQL, Postgres, SQL
server, oracle etc.

3|Page
2.1 MySQL Introduction

• MySQL is an world’s most popular open source relational database.

• MySQL is cross platform which means it runs on a number of different platforms such as
Windows, Linux, and Mac OS etc.

• MySQL is written in C and C++.


• It was released under the name of co-founder Michael Widenius daughter, ‘My‘.

2.2 MySQL Elements

• Literals
• Data types

• Nulls
• Comments

2.2.1 Literals

• It means the fixed value or constant value. It may be of character, numeric or date time type.
• Character and date/time literals are always in single quotation marks whereas numeric

literals must be without single quotation marks


• For example – ‘Virat’, 12, 12.56, ‘04-20-2018’

• Date and time values are always in the YYYY-MM-DD HH:MM:SS


• Special character like quotes is always written be preceding it back-slash (\). For example, if

we want to store value as Tom’s Cat then it should be written as Tom\’s Cat.

2.2.2 Data Type

• Means the type of value and type of operation we can perform on data. For example on

numeric value we can store numbers and perform all arithmetic operations and so on.
• MySQL support three categories of data types:

o Numeric
o Date and time

o String types

4|Page
Numeric Data Types:

Data type Description

INT Numbers without decimal. Store up to 11 digits. -2147483648 to 2147483647

TINYINT Small integer value between 0 – 255 (4 digits)

SMALLINT More than TINYINT between -32768 to 32767 (5 digit)

MEDIUMINT Integer values up to 9 digits


BIGINT Very large integer value up to 11 digits

FLOAT(M,D) Real numbers i.e. number with decimal. M specify length of numeric value
including decimal place D and decimal symbol. For example if it is given as
FLOAT(8,2) then 5 integer value 1 decimal symbol and 2 digit after decimal TOTAL
– 8. it can work on 24 digits after decimal.
DOUBLE(M,D) Real numbers with more precision up to 53 place after decimal.

DECIMAL It is used to store exact numeric value that preserve exact precision for e.g.
money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D represent no. of digit after
decimal(0-30), for e.g DECIMAL(6,2) means 4 digit before decimal and 2 digit after
decimal. Max will be 9999.99

Date and Time Types:

Data type Description


DATE A date in YYY-MM-DD format between 1000-01-01 to 9999-12-31
In oracle data format is DD-MON-YYYY for e.g 10-SEP-2019

DATETIME Combination of date and time. For example to store 4th December 2018 and time is afternoon
3:30 then it should be written as – 2018-12-04 15:30:00

TIMESTAMP Similar to DATATIME but it is written without hyphen for example the above date time is stored as
20181204153000

TIME To store time in the format HH:MM:SS

YEAR(M) To store only year part of data where M may be 2 or 4 i.e. year in 2

digit like 18 or 4 digit like 2018

5|Page
String Types:

Data type Description

CHAR(M) Fixed length string between 1 and 255. it always occupy M size for each data for example if
size is CHAR(20) and we store value ‘MOBILE’ , although the size of MOBILE is 6 but in a table
it will occupy 20 size with space padded at right side for remaining place.
Mostly use in the case where the data to be insert is of fixed size like Grade (A,B,C,..) or
Employee code as E001, E002, etc. In this case CHAR will give better performance than
varchar

VARCHAR(M) Variable length string between 1 and 65535 (from MySQL 5.0.3) , earlier it was
255. it takes size as per the data entered for example with VARCHAR(20) if the data entered is
MOBILE then it will take only 6 byte. It is useful for the data like name, address where the number
of character to be enter is not fixed.

VARCHAR2 It is supported in ORACLE, both are almost same with minor difference. The difference is in the
way they are handling Empty String and NULL, for VARCHAR these two are different where as
VARCHAR2 treats both same.
Difference between CHAR & VARCHAR

CHAR VARCHAR

Fixed length string Variable length string


Used where number of character to enter is fixed like Used where number of character to be enter is not
Grade, EmpCode, etc fixed like name, address etc.

Fast, no memory allocation every time Slow, as it take size according to data so
every time memory allocation is done
It takes more memory It takes less space

2.2.3 Comments

It is a text that is not executed, only for documentation purpose. Comments in MySQL can be
written as

• Begin the comment with /* and */


• Begin the comment with – (followed by space)
• Begin then comment with #

For example,

• /* Select * from emp where empno=4 */


• Select * from emp; -- it will fetch all details

SQL COMMAND SYNTAX

Commands Description

Keywords That have special meaning in SQL. They are the commands in MySQL

6|Page
Clause They are used to support MySQL commands like FROM, WHERE etc.

Arguments Values passed to clause like table name to FROM clause conditions to WHERE clause
for e.g.

SELECT * FROM EMP WHERE SALARY>12000;

In the above command

SELECT is keyword

FROM AND WHERE is clause EMP is an argument to FROM

SALARY>12000 is argument to WHERE

3.1 SQL STATEMENTS

SQL statements can be classified into following categories:-

1. DATA DEFINITION LANGUAGE (DDL) COMMANDS

2. DATA MANIPULATION LANGUAGE (DML) COMMANDS

3. DATA CONTROL LANGUAGE (DCL) COMMANDS

4. TRANSACTION CONTROL LANGUAGE (TCL) COMMANDS

3.1.1. DATA DEFINITION LANGUAGE (DDL) COMMANDS

Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. Following are the commands that fall under DDL category: -

• CREATE TABLE
• DROP TABLE
• ALTER TABLE
• TRUNCATE
• RENAME
• COMMENT

3.1.2. DATA MANIPULATION LANGUAGE (DML) COMMANDS

The SQL commands that deal with the manipulation of data are DML Commands. The following
commands fall under the DML Commands category:-

• SELECT
• INSERT
• UPDATE
• DELETE
• MERGE
• CALL

3.1.3. DATA CONTROL LANGUAGE (DCL) COMMANDS

7|Page
DCL is the short name of Data Control Language mostly concerned with rights, permissions, and
other controls of the database system. The following commands fall under the DML Commands
category:-.

• GRANT
• REVOKE

3.1.4. TRANSACTION CONTROL LANGUAGE (TCL) COMMANDS

TCL is the short name of Transaction Control Language which deals with a transaction within a
database. The following commands fall under the DML Commands category:-.

• COMMIT
• ROLLBACK
• SAVEPOINT
• SET TRANSACTION

8|Page
4.1 MySQL Constraints

The constraint in MySQL is used to specify the rule that allows or restricts what values/data will be
stored in the table. They provide a suitable method to ensure data accuracy and integrity inside the
table. It also helps to limit the type of data that will be inserted inside the table. If any interruption
occurs between the constraint and data action, the action is failed.

4.1.1.Types of MySQL Constraints

Constraints in MySQL is classified into two types:

Column Level Constraints: These constraints are applied only to the single column that limits the
type of particular column data.

Table Level Constraints: These constraints are applied to the entire table that limits the type of
data for the whole table.

How to create constraints in MySQL

We can define the constraints during a table created by using the CREATE TABLE statement. MySQL
also uses the ALTER TABLE statement to specify the constraints in the case of the existing table
schema.

Syntax:

The following are the syntax to create a constraints in table:

CREATE TABLE new_table_name (

col_name1 datatype constraint,

col_name2 datatype constraint,

col_name3 datatype constraint,

.........

);

4.1.2. Constraints used in MySQL

• NOT NULL
• CHECK
• DEFAULT
• PRIMARY KEY
• AUTO_INCREMENT
• UNIQUE
• INDEX
• ENUM
• FOREIGN KEY

9|Page
4.1.2.1. NOT NULL Constraint

This constraint specifies that the column cannot have NULL or empty values. The below statement
creates a table with NOT NULL constraint.

1. mysql> CREATE TABLE Student(Id INT, LastName VARCHAR


(50) NOT NULL, FirstName VARCHAR (50) NOT NULL, City VARCHAR(35));

Execute the queries listed below to understand how it works:

1. mysql> INSERT INTO Student VALUES(1, 'Hanks', 'Peter', 'New York');


2.
3. mysql> INSERT INTO Student VALUES(2, NULL, 'Amanda', 'Florida');

Output

4.1.2.2. UNIQUE Constraint

This constraint ensures that all values inserted into the column will be unique. It means a column
cannot stores duplicate values. MySQL allows us to use more than one column with UNIQUE
constraint in a table.

1. mysql> CREATE TABLE ShirtBrands(Id INT, BrandName VARCHAR(40) UNIQUE, Size VAR
CHAR(30));

Execute the queries listed below to understand how it works:

1. mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Pantaloons', 38), (2, 'Ca
ntabil', 40);
2.
3. mysql> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Raymond', 38), (2, 'Cant
abil', 40);

Output

In the below output, we can see that the first INSERT query executes correctly, but the second
statement fails and gives an error that says: Duplicate entry 'Cantabil' for key BrandName.

10 | P a g e
4.1.2.3. CHECK Constraint

Let us understand how a CHECK constraint works in MySQL. For example, the following statement
creates a table "Persons" that contains CHECK constraint on the "Age" column. The CHECK constraint
ensures that the inserted value in a column must be satisfied with the given condition means the
Age of a person should be greater than or equal to 18:

1. mysql> CREATE TABLE Persons (


2. ID int NOT NULL,
3. Name varchar(45) NOT NULL,
4. Age int CHECK (Age>=18)
5. );

Execute the listed queries to insert the values into the table:

1. mysql> INSERT INTO Persons(Id, Name, Age)


2. VALUES (1,'Robert', 28), (2, 'Joseph', 35), (3, 'Peter', 40);
3.
4. mysql> INSERT INTO Persons(Id, Name, Age) VALUES (1,'Robert', 15);

Output

11 | P a g e
4.1.2.4. DEFAULT Constraint

This constraint is used to set the default value for the particular column where we have not
specified any value. It means the column must contain a value, including NULL.

For example, the following statement creates a table "Persons" that contains DEFAULT constraint on
the "City" column. If we have not specified any value to the City column, it inserts the default value:

1. mysql> CREATE TABLE Persons (


2. ID int NOT NULL,
3. Name varchar(45) NOT NULL,
4. Age int,
5. City varchar(25) DEFAULT 'New York'
6. );

Execute the listed queries to insert the values into the table:

1. mysql> INSERT INTO Persons(Id, Name, Age, City)


2. VALUES (1,'Robert', 15, 'Florida'),
3. (2, 'Joseph', 35, 'California'),
4. (3, 'Peter', 40, 'Alaska');
5.
6. mysql> INSERT INTO Persons(Id, Name, Age) VALUES (1,'Brayan', 15);

Output

Now, executes the following statement to validate the default value for the 4th column:

1. mysql> SELECT * FROM Persons;


12 | P a g e
We can see that it works perfectly. It means default value "New York" stored automatically in the
City column.

4.1.2.5. PRIMARY KEY Constraint

This constraint is used to identify each record in a table uniquely. If the column contains primary key
constraints, then it cannot be null or empty. A table may have duplicate columns, but it can contain
only one primary key. It always contains unique value into a column.

The following statement creates a table "Person" and explains the use of this primary key more
clearly:

1. CREATE TABLE Persons (


2. ID int NOT NULL PRIMARY KEY,
3. Name varchar(45) NOT NULL,
4. Age int,
5. City varchar(25));

Next, use the insert query to store data into a table:

1. INSERT INTO Persons(Id, Name, Age, City)


2. VALUES (1,'Robert', 15, 'Florida') ,
3. (2, 'Joseph', 35, 'California'),
4. (3, 'Peter', 40, 'Alaska');
5.
6. INSERT INTO Persons(Id, Name, Age, City)
7. VALUES (1,'Stephen', 15, 'Florida');

Output

In the below output, we can see that the first insert query executes successfully. While the second
insert statement fails and gives an error that says: Duplicate entry for the primary key column.

13 | P a g e
4.1.2.6. AUTO_INCREMENT Constraint

This constraint automatically generates a unique number whenever we insert a new record into the
table. Generally, we use this constraint for the primary key field in a table.

1. mysql> CREATE TABLE Animals(


2. id int NOT NULL AUTO_INCREMENT,
3. name CHAR(30) NOT NULL,
4. PRIMARY KEY (id));

Next, we need to insert the values into the "Animals" table:

1. mysql> INSERT INTO Animals (name) VALUES


2. ('Tiger'),('Dog'),('Penguin'),
3. ('Camel'),('Cat'),('Ostrich');

Now, execute the below statement to get the table data:

1. mysql> SELECT * FROM Animals;

Output

In the output, we can see that I have not specified any value for the auto-increment column, so
MySQL automatically generates a unique number in the sequence order for this field.

14 | P a g e
4.1.2.7. Foreign Key Constraint

This constraint is used to link two tables together. It is also known as the referencing key. A foreign
key column matches the primary key field of another table. It means a foreign key field in one table
refers to the primary key field of another table.

Let us consider the structure of these tables: Persons and Orders.

Table: Persons

1. CREATE TABLE Persons (


2. Person_ID int NOT NULL PRIMARY KEY,
3. Name varchar(45) NOT NULL,
4. Age int,
5. City varchar(25)
6. );

Table: Orders

1. CREATE TABLE Orders (


2. Order_ID int NOT NULL PRIMARY KEY,
3. Order_Num int NOT NULL,
4. Person_ID int,
5. FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID)
15 | P a g e
6. );

In the above table structures, we can see that the "Person_ID" field in the "Orders" table points to
the "Person_ID" field in the "Persons" table. The "Person_ID" is the PRIMARY KEY in the "Persons"
table, while the "Person_ID" column of the "Orders" table is a FOREIGN KEY.

Output

Our table contains the following data:

4.1.2.9 ENUM Constraint

The ENUM data type in MySQL is a string object. It allows us to limit the value chosen from a list of
permitted values in the column specification at the time of table creation. It is short for enumeration,
which means that each column may have one of the specified possible values.

1. mysql> CREATE TABLE Shirts (


2. id INT PRIMARY KEY AUTO_INCREMENT,
3. name VARCHAR(35),
4. size ENUM('small', 'medium', 'large', 'x-large')
5. );

Next, we need to insert the values into the "Shirts" table using the below statements:

1. mysql> INSERT INTO Shirts(id, name, size)


2. VALUES (1,'t-shirt', 'medium'),
3. (2, 'casual-shirt', 'small'),

16 | P a g e
4. (3, 'formal-shirt', 'large');

Now, execute the SELECT statement to see the inserted values into the table:

1. mysql> SELECT * FROM Shirts;

Output

We will get the following output:

4.1.2.10 INDEX Constraint

This constraint allows us to create and retrieve values from the table very quickly and easily. An index
can be created using one or more than one column. It assigns a ROWID for each row in that way
they were inserted into the table.

The following illustration creates a table named "shirts" that contains three columns: id, name, and
size.

1. mysql> CREATE TABLE Shirts (


2. id INT PRIMARY KEY AUTO_INCREMENT,
3. name VARCHAR(35),
4. size ENUM('small', 'medium', 'large', 'x-large')
5. );

Next, we need to insert the values into the "Shirts" table using the below statements:

17 | P a g e
1. mysql> INSERT INTO Shirts(id, name, size)
2. VALUES (1,'t-shirt', 'medium'),
3. (2, 'casual-shirt', 'small'),
4. (3, 'formal-shirt', 'large');

Now, execute this statement for creating index:

1. mysql> CREATE INDEX idx_name ON Shirts(name);

We can use the query below to retrieve the data using the index column:

1. mysql> SELECT * FROM Shirts USE INDEX(idx_name);

Output

The following output appears:

5.1 MySQL Show/List Tables

The show or list table is very important when we have many databases that contain various tables.
Sometimes the table names are the same in many databases;

1. mysql> SHOW TABLES;


1. mysql> USE mystudentdb;
2. mysql>SHOW TABLES;

18 | P a g e
The following output explains it more clearly:

MySQL allows us to use the FROM or IN clause followed by the database name. The following
statement explains it more clearly:

1. mysql> SHOW TABLES IN database_name;

The above statement can also be written as:

1. mysql> SHOW TABLES FROM database_name;

When we execute the below statements, we will get the same result:

1. mysql> SHOW TABLES FROM mystudentdb;


2. OR,
3. mysql> SHOW TABLES IN mystudentdb;

Output:

19 | P a g e
1. mysql> SHOW TABLES FROM mystudentdb LIKE "stud%";

The above statement will give the following output:

1. mysql> SHOW TABLES In mystudentdb WHERE Tables_in_mystudentdb= "employees";

It will give the following output:

5.2 The MySQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

Syntax

CREATE DATABASE databasename;

CREATE DATABASE Example

The following SQL statement creates a database called "testDB":

Example

CREATE DATABASE testDB;

5.3 The MySQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

20 | P a g e
Syntax

CREATE TABLE table_name (

column1 datatype,

column2 datatype,

column3 datatype,

....

);

Example

CREATE TABLE Persons (


PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

CREATING and USING DATABASE


Syntax: CREATE DATABASE <DATABASE NAME>
CREATE DATABASE MYDB;
TO SEE LIST OF DATABASES:
SHOW DATABASES;
TO OPEN ANY DATABASE TO WORK
Syntax: USE DATABASENAME
USE MYDB
CREATING TABLE

Syntax:-

Create Table TableName(ColumnName ColumnName datatype(size),…..);

Example:-

Create Table Employee(empno int, name varchar(20), dept varchar(20), salary int);

Create table Student(roll int, name varchar(20), stream varchar(20), per int);

21 | P a g e
5.4 INSERTING RECORDS IN TABLE

Syntax:-

Insert into tablename values(value1,value2,…)

Note:-

1) char, varchar and date value must be in single quotes

2) Values must be passed in the order of their column

3) Date values are passed in the format dd-mon-yyyy i.e. 20-Sep-2015 (in oracle) yyyy-mm-dd
(in mysql)

Syntax:-

Insert into emp values(1, ‘Rakesh’,’Sales’,34000) Insert into student values(1,’Mahi’,’Science’,89);

Inserting in selected columns

Insert into emp (empno, name, dept ) values (2,’dipanker’,’IT’)

5.5 SELECTING RECORD

Select statement allows to send queries to table and fetch the desired record. Select can be used
to select both horizontal and vertical subset.

Syntax:-

Select */columnnames FROM tablename [where condition ]

Selecting all record and all columns

Select * from emp;

Selecting desired columns

select empno, name from emp;

Changing the order of columns

select dept, name from emp;

5.6 DISTINCT keyword

DISTINCT keyword is used to eliminate the duplicate records from output. For e.g. if we select dept
from employee table it will display all the department from the table including duplicate rows.

Select dept from emp;

Output will be:-

22 | P a g e
Dept

--------

Sales

Sales

IT

IT

HR

If we don’t want to see the duplicate rows in output we have to use DISTINCT keyword.

Select DISTINCT dept from emp;

Output will be:-

Dept
--------
Sales
IT
HR

5.6 PERFORMING SIMPLE CALCULATION


While performing SQL operations sometimes simple calculations are required, SQL provides
facility to perform simple arithmetic operations in query. In MySQL we can give these queries
without FROM clause i.e. table name is not required for these queries,

For Example

Select 10*2;

Select 10*3/6;

MySQL also provides DUAL table to provide compatibility with other DBMS. It is dummy table used
for these type queries where table name is not required. It contains one row and one column. For
example:

Select 100+200 from DUAL;

Select curdate() from dual;

CALCULATION WITH TABLE DATA

Select name, salary, salary * 12 Annual_Salary from emp;

Select empno, salary+1000 from emp

Update student set total=phy+chem+maths+cs+eng;

23 | P a g e
5.7 COLUMN ALIAS

It is a temporary name/label given to column that will appear in output. For example if column
name is dept and you want Department to appear as column heading then we have to give
Column Alias. If we want alias name of multiple words then it should be enclosed in double
quotes. Its format is :

ColumnName [AS] ColumnAlias

Example

(i) Select empno Employee_Number, name, dept Department, Salary Income from emp;

(ii) Select name, Salary*12 as “Annual Income” from emp;

5.8 HANDLING NULL

From the above table we can observe that salary of Shaban is NULL i.e. not assigned, Now
if we want 0 or “not assigned” for the salary information of shaban, we have to use IFNULL()

Select empno,name,IFNULL(Salary,”not assigned”) from emp;

Column value to substitute if NULL found

5.9 PUTTING TEXT IN QUERY OUTPUT

SQL allows to put user defined symbols or text with table output. Like ‘Rs’ with Salary or ‘%’ symbol
with commission

For e.g.

Select name, dept, ‘Rs.’, salary from emp;

Select name, ‘ works in department’, dept, ‘ and getting salary rs. ‘, salary from emp;

Select name, concat(‘Rs. ‘, salary) from emp;

24 | P a g e
6.0 WHERE clause

WHERE clause is used to select specified rows. It allows to select only desired rows by applying
condition. We can use all comparison(>, <, >=, <=, =, <>) and logical operator (AND, OR, NOT).

AND ( &&), OR (||) , NOT (!)

For example

Select * from emp where salary>4000;

Select * from emp where empno=1;

Select name,dept from emp where dept=‘HR’;

AND(&&) means both conditions must be true, OR(||) means any condition must be true to
produce output. NOT(!) will do the reverse checking.

Select * from emp where salary>4000 and salary<8000;

Select * from emp where dept=‘Sales’ and salary<30000;

Select name,dept from emp where dept=‘HR’ and salary>=20000 and salary<=40000;

Select * from emp where dept=‘HR’ or dept=‘IT’;

Select * from emp where NOT empno=4;

6.1 SQL operators

1) BETWEEN

2) IN

3) LIKE

4) IS NULL

6.1.1 BETWEEN

BETWEEN allows to specify range of values to search in any column. It is used with AND clause and
it will include the specified values during the searching. For e.g.

Select * from emp where salary between 18000 and 30000;

Select name from emp where empno between 2 and 5;

Select * from emp where salary NOT between 25000 and 35000

6.1.2 IN

IN allows to specify LIST of values in which searching will be performed. It will return all those
record that matches any value in a given list of values. It can be thought as an alternative of
multiple ORs

Select * from emp where dept IN(‘sales’,’it’);


25 | P a g e
Select name from emp where empno IN (2,4,5);

Select * from emp where dept NOT IN(‘sales’,’it’)

6.1.3 LIKE

LIKE allows to search based on pattern. It is used when we don’t want to search an exact value or
we don’t know that exact value, and we know only the pattern of value like name starting from any
particular letter, or ending with and containing any particular letter or word.

LIKE is used with two wildcard characters:

a) % : used when we want to substitute multiple characters. With %


length is not fixed

b) _ (underscore) : used when we want to substitute Single character

Search for employee whose name begins from ‘s’

Select * from emp where name like ‘s%’;

Search for employee whose name ends with ‘r’

Select * from emp where name like ‘%r’;

Search for employee whose name contains ‘a’ anywhere

Select * from emp where name like ‘%a%’

Search for employee whose dob is in feb

Select * from emp where dob like ‘%-02-%’

Search employee whose name is of 5 letters begins from ‘s’

Select * from emp where name like ‘s_ _ _ _ ’;

6.1.4 IS NULL

IS NULL is used to compare NULL values present in any column. Because NULL is not considered as
value so we cannot compare with = sign, so to compare with NULL SQL provides IS NULL.

Select * from emp where salary is null;

Select * from emp where salary is not null;

26 | P a g e
OPERATOR PRECEDENCE

When multiple operators are used in expression, then evaluation of expression takes place in
the order of precedence. Higher precedence operator will execute first

7.0 SORTING OUTPUT

By default records will come in the output in the same order in which it was entered. To see the
output rows in sorted or arranged in ascending or descending order SQL provide ORDER BY
clause. By default output will be ascending order(ASC) to see output in descending order we
use DESC clause with ORDER BY.

Select * from emp order by name; (ascending order)

Select * from emp order by salary desc;

Select * from emp order by dept asc, salary desc;

8.0 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".

The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(),
AVG()) to group the result-set by one or more columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

27 | P a g e
Example:
SELECT * FROM Customers GROUP BY Country;

9.0 HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.

HAVING Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition;

Example:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

10.0 MYSQL FUNCTIONS

A function is built – in code for specific purpose that takes value and returns a single value. Values
passed to functions are known as arguments/parameters.

There are various categories of function in MySQL:-

1) String Function

2) Mathematical function

3) Date and time function

28 | P a g e
10.1 String Function

29 | P a g e
10.2 Numeric Function

10.3 Date and Time Function

30 | P a g e
Difference Between NOW() and SYSDATE() :

NOW() function return the date and time at which function was executed even if we execute
multiple NOW() function with select. whereas SYSDATE() will always return date and time at which
each SYDATE() function started execution. For example.

mysql> Select now(), sleep(2), now();

Output: 2018-12-04 10:26:20, 0, 2018-12-04 10:26:20

mysql> Select sysdate(), sleep(2), sysdate();

Output: 2018-12-04 10:27:08, 0, 2018-12-04 10:27:10

11. 1 AGGREGATE FUNCTIONS:

Aggregate function is used to perform calculation on group of rows and return the calculated
summary like sum of salary, average of salary etc.

Available aggregate functions are –

1. SUM()
2. AVG()
3. COUNT()
4. MAX()
5. MIN()
6. COUNT(*)

Select SUM(salary) from emp;

Output – 161000

Select SUM(salary) from emp where dept=‘sales’;

31 | P a g e
Output – 59000

Select AVG(salary) from emp;

Output – 32200

Select AVG(salary) from emp where dept=‘sales’;

Output - 29500

Select COUNT(name) from emp;

Output – 5

Select COUNT(salary) from emp where dept=‘HR’;

Output - 1

Select COUNT(DISTINCT dept) from emp;

Output - 3

Select MAX(Salary) from emp;

Output – 45000

Select MAX(salary) from emp where dept=‘Sales’;

Output - 35000

Select MIN(Salary) from emp;

Output – 24000

Select MIN(salary) from emp where dept=‘IT’;

Output - 27000

Select COUNT(*) from emp;

Output – 6

Select COUNT(salary) from emp;

Output - 5

11.2 count(*) Vs count()

Count(*) function is used to count the number of rows in query output whereas count() is used to
count values present in any column excluding NULL values.

Note:

All aggregate function ignores the NULL values.

Aggregate functions by default takes the entire table as a single group that’s why we are getting
the sum(), avg(), etc output for the entire table. Now suppose organization wants the sum() of all
32 | P a g e
the job separately, or wants to find the average salary of every job. In this case we have to logically
divide our table into groups based on job, so that every group will be passed to aggregate
function for calculation and aggregate function will return the result for every group.

Group by clause helps up to divide the table into logical groups based on any column value. In
those logically divided records we can apply functions.

For. E.g.

SELECT SUM(SAL) FROM EMP GROUP BY DEPT;

SELECT JOB,SUM(SAL) FROM EMP GROUP BY DEPT;

SELECT JOB,SUM(SAL),AVG(SAL),MAX(SAL),COUNT(*) EMPLOYEE_COUNT FROM EMP;

NOTE :- when we are using GROUP BY we can use only aggregate function and the column on
which we are grouping in the SELECT list because they will form a group other than any column
will gives you an error because they will be not the part of the group.

For e.g.

SELECT ENAME,JOB,SUM(SAL) FROM EMP GROUP BY JOB;

Error -> because Ename is not a group expression

12.0 HAVING with GROUP BY

• If we want to filter or restrict some rows from the output produced by GROUP BY then we
use HAVING clause. It is used to put condition of group of rows. With having clause we can
use aggregate functions also.

• WHERE is used before the GROUP BY. With WHERE we cannot use aggregate function.

E.g.

• SELECT DEPT,AVG(SAL) FROM EMP GROUP BY DEPT HAVING JOB IN (‘HR’,’SALES’)

• SELECT DEPT,MAX(SAL),MIN(SAL),COUNT(*) FROM EMP GROUP BY DEPT HAVING


COUNT(*)>2

• SELECT DEPT,MAX(SAL),MIN(SAL) FROM EMP WHERE SAL>=2000 GROUP BY DEPT


HAVING DEPT IN(‘IT’,’HR’)

13.1 UPDATE STATEMENT

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

33 | P a g e
UPDATE – Example

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;

UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';

Update Warning!

Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!

UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';

Wrong Query:

UPDATE Customers
SET PostalCode = 00000;

14.1 DELETE STATEMENT


The DELETE statement is used to delete existing records in a table.

DELETE Syntax

34 | P a g e
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE
clause, all records in the table will be deleted!

SQL DELETE Example:


DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records:

It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
DELETE FROM Customers;

15.1 MYSQL ALTER TABLE STATEMENT

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.

15.1.1 ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example

ALTER TABLE Customers


ADD Email varchar(255);

15.1.2 ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:
ALTER TABLE Customers
DROP COLUMN Email;

35 | P a g e
15.1.3 ALTER TABLE - MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Example:
ALTER TABLE Persons
ADD DateOfBirth date;
Change Data Type Example
ALTER TABLE Persons
MODIFY COLUMN DateOfBirth year;

15.1.4 DROP COLUMN Example

Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:


ALTER TABLE Persons
DROP COLUMN DateOfBirth;

16.1 MYSQL DROP TABLE STATEMENT

The DROP TABLE statement is used to drop an existing table in a database.

Syntax:
DROP TABLE table_name;

Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!

MySQL DROP TABLE Example:

The following SQL statement drops the existing table "Shippers":


DROP TABLE Shippers;

17.1 MySQL TRUNCATE TABLE

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.

Syntax:
TRUNCATE TABLE table_name;

18.1 Delete Vs Truncate Vs Drop

In MySQL, the DELETE, TRUNCATE, and DROP statements are used to modify and delete data in a
table. The main difference between these statements is how they work:

36 | P a g e
DELETE

Deletes a record or records from a table. If you don't specify a WHERE condition, it will delete all
rows in the table. Data can be rolled back with the DELETE command

TRUNCATE

Deletes all rows or data in a table. It's similar to a DELETE statement without a WHERE condition.
TRUNCATE drops the table and recreates it. Data cannot be rolled back with the TRUNCATE
command

DROP

Deletes the table structure and all data. It permanently deletes a table and its data.

You cannot roll back a DROP TABLE statement.

Create the following table and add the records

Write down the following queries based on the given table:

1. Select all record of table


2. Select ItemNo, name and Unitprice
3. Select all item record where Unitprice is more than 20
4. Select Item name of those items which are quantity between 100-200
5. Select all record of Items which contains pen word in it
6. Select unique dcode of all items
7. Display all record in the descending order of UnitPrice
8. Display all items which are stocked in the month of March
9. Change the unitprice to 20 for itemno 5005
10. Delete the record of itemno 5001
11. Display all the item name in capital letters
12. Display first 4 character of every item name
13. Display all record whose dcode is not assigned

37 | P a g e
19.1 KEYS:

o Keys play an important role in the relational database.


o It is used to uniquely identify any record or row of data from the table. It is also used to
establish and identify relationships between tables.

For example, ID is used as a key in the Student table because it is unique for each student. In the
PERSON table, passport_number, license_number, SSN are keys since they are unique for each
person.

Types of keys:

1. Primary key

o It is the first key used to identify one and only one instance of an entity uniquely. An entity
can contain multiple keys, as we saw in the PERSON table. The key which is most suitable
from those lists becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each employee. In the
EMPLOYEE table, we can even select License_Number and Passport_Number as primary keys
since they are also unique.
o For each entity, the primary key selection is based on requirements and developers.

38 | P a g e
2. Candidate key

o A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
o Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.

For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the attributes,
like SSN, Passport_Number, License_Number, etc., are considered a candidate key.

3. Super Key

Super key is an attribute set that can uniquely identify a tuple. A super key is a superset of a candidate
key.

39 | P a g e
For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this combination can
also be a key.

The super key would be EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-NAME), etc.

4. Foreign key

• Foreign keys are the column of the table used to point to the primary key of another table.
• Every employee works in a specific department in a company, and employee and department
are two different entities. So we can't store the department's information in the employee
table. That's why we link these two tables through the primary key of one table.
• We add the primary key of the DEPARTMENT table, Department_Id, as a new attribute in the
EMPLOYEE table.
• In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.

5. Alternate key

There may be one or more attributes or a combination of attributes that uniquely identify each
tuple in a relation. These attributes or combinations of the attributes are called the candidate keys.
One key is chosen as the primary key from these candidate keys, and the remaining candidate key,
40 | P a g e
if it exists, is termed the alternate key. In other words, the total number of the alternate keys is the
total number of candidate keys minus the primary key. The alternate key may or may not exist. If
there is only one candidate key in a relation, it does not have an alternate key.

For example, employee relation has two attributes, Employee_Id and PAN_No, that act as candidate
keys. In this relation, Employee_Id is chosen as the primary key, so the other candidate key, PAN_No,
acts as the Alternate key.

6. Composite key

Whenever a primary key consists of more than one attribute, it is known as a composite key. This
key is also known as Concatenated Key.

For example, in employee relations, we assume that an employee may be assigned multiple roles,
and an employee may work on multiple projects simultaneously. So the primary key will be
composed of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in combination. So these
attributes act as a composite key since the primary key comprises more than one attribute.

41 | P a g e
Difference between different Keys in SQL

Key type Purpose Characteristics

Cannot be NULL, and must


Primary Key Used to uniquely identify a row in a table
be a unique one per table

Foreign Key Used to maintain referential integrity between tables It can be NULL

It is a combination of
Composite Used to uniquely identify a row when a single column
columns, however, they
Key is not sufficient
must be unique.

Unique Key Used to prevent duplicate values in a column It can be NULL

It can be unique and can


Candidate
Used to identify potential Primary Keys uniquely identify each row
Key
in a table

It can contain additional


Super Key Used to uniquely identify rows in a broad sense
non-unique columns

42 | P a g e
20.1 MySQL Joins

MySQL Joining Tables

A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Let's look at a selection from the "Orders" table:

Then, look at a selection from the "Customers" table:

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in
the "Customers" table. The relationship between the two tables above is the "CustomerID"
column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:

43 | P a g e
20.2 Supported Types of Joins in MySQL

• INNER JOIN: Returns records that have matching values in both tables
• LEFT JOIN: Returns all records from the left table, and the matched records from
the right table
• RIGHT JOIN: Returns all records from the right table, and the matched records from
the left table
• CROSS JOIN: Returns all records from both tables

20.3 MySQL INNER JOIN Keyword

The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

44 | P a g e
Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

And a selection from the "Customers" table:

MySQL INNER JOIN Example

The following SQL statement selects all orders with customer information:

Example:

SELECT Orders.OrderID, Customers.CustomerName


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Note: The INNER JOIN keyword selects all rows from both tables as long as there is a
match between the columns. If there are records in the "Orders" table that do not have
matches in "Customers", these orders will not be shown!

JOIN Three Tables

The following SQL statement selects all orders with customer and shipper information:

Example

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName


FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

45 | P a g e
20.4 MySQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all records from the left table (table1), and the matching
records (if any) from the right table (table2).

LEFT JOIN Syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

And a selection from the "Orders" table:

46 | P a g e
MySQL LEFT JOIN Example

The following SQL statement will select all customers, and any orders they might have:

Example

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if
there are no matches in the right table (Orders).

20.5 MySQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all records from the right table (table2), and the matching
records (if any) from the left table (table1).

RIGHT JOIN Syntax

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

And a selection from the "Employees" table:

MySQL RIGHT JOIN Example

The following SQL statement will return all employees, and any orders they might have
placed:

47 | P a g e
Example

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName


FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even
if there are no matches in the left table (Orders).

20.6 SQL CROSS JOIN Keyword

The CROSS JOIN keyword returns all records from both tables (table1 and table2).

CROSS JOIN Syntax

SELECT column_name(s)
FROM table1
CROSS JOIN table2;

Note: CROSS JOIN can potentially return very large result-sets!

Demo Database

In this tutorial, we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

And a selection from the "Orders" table:


48 | P a g e
MySQL CROSS JOIN Example

The following SQL statement selects all customers, and all orders:

Example

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders;

Note: The CROSS JOIN keyword returns all matching records from both tables whether the
other table matches or not. So, if there are rows in "Customers" that do not have
matches in "Orders", or if there are rows in "Orders" that do not have matches in
"Customers", those rows will be listed as well.

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:

Example

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders
WHERE Customers.CustomerID=Orders.CustomerID;

20.7 The MySQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.

• 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

UNION Syntax

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

49 | P a g e
UNION ALL Syntax

The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

And a selection from the "Suppliers" table:

SQL UNION Example

The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

Example

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDER BY City;

50 | P a g e
Note: If some customers or suppliers have the same city, each city will only be listed
once, because UNION selects only distinct values. Use UNION ALL to also select duplicate
values!

SQL UNION ALL Example

The following SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:

Example

SELECT City FROM Customers


UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

SQL UNION With WHERE

The following SQL statement returns the German cities (only distinct values) from both
the "Customers" and the "Suppliers" table:

Example

SELECT City, Country FROM Customers


WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

51 | P a g e

You might also like