DBMS Day1 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 174

WHAT IS DBMS

The database is a collection of inter-related data which is used to retrieve, insert and
delete the data efficiently.

DBMS provides an interface to perform various operations like database creation, storing
data in it, updating data, creating a table in the database and a lot more.

It provides protection and security to the database. In the case of multiple users, it also
maintains data consistency.
DBMS TASKS
Data Definition : creation, modification, and removal of definition in DB
Data Updation: insertion, modification, and deletion of the actual data in the
database.
Data Retrieval: It is used to retrieve the data from the database which can be used by
applications for various purposes.
User Administration: It is used for registering and monitoring users, maintain data
integrity, enforcing data security, dealing with concurrency control, monitoring
performance and recovering information corrupted by unexpected failure.
Advantages of DBMS
1 Controls database redundancy

2 Data sharing

3 Easily Maintenance:

4 Back up

5. Multiple User Interface


DBMS Architecture
1. Tier- Architecture: user can directly access the database
2. 2- Tier Architecture: user will access the the database through API: JDBC,ODBC
The server side is responsible to provide the functionalities like: query processing and
transaction management.
To communicate with the DBMS, client-side application establishes a connection with
the server side.
DBMS Architecture
3-Tier Architecture

The application on the client-end interacts

with an application server which further

communicates with the database system.


Data Models
Data models define how data is connected to each other and how they are processed and stored
inside the system.
1 Relational data model
2Semistructured Data Model 3
Entity Relational MODEL
4. Object-Based Data model
What is RDBMS
Relational Database Management System

The RDBMS USES TABLES to store data

ID NAME AGE

1001 ABHI 23

1002 ARYAN 25
Field: Row / Record

Entity: Column

NULL VALUES: BLANK FIELD

Data Integrity:
● Entity Integrity :no duplicate rows in a table.
● Domain Integrity : It enforces valid entries for a given column by restricting the type,
the format, or the range of values.
● Referential Integrity : It specifies that rows cannot be deleted, which are used by
other records.
● User-Defined Integrity :It enforces some specific business rules that are
defined by users.
Data Model Schema and Instance
Instance :The data which is stored in the database at a particular moment of time is
called an instance of the database.

Schema:The overall design of a database is called schema.(ex:able, foreign key, primary


key, views, columns, data types, stored procedure, etc.)
Data Model Schema and Instance
ER MODEL
In ER modeling, the database structure is portrayed as a diagram called an entity-
relationship diagram
ADDRESS

ENAME

EMPLOYEE AGE

EID
Components of ER Diagram
1) Entity a) One to many
a) Weak Entity b) Many to one
2) Attribute
c) Many to many
a) Key Attribute
b) Composite Attribute
c) Multivalued Attribute
d) Derived Attribute
3) Relation
a) one to one
Components of ER Diagram.
Entity: Entity can be any object ex: person,place .Represented using Rectangles.

a.Week Entity: an Entity that depends on another entity.

flats belongs to Apartments


Attribute : Describes the property of Entity.

Eid Phne_no

Employee

Ename Age
b. Composite Key : An Attribute composed of many other attributes is known as a

composite attribute.

Ename

first_name Middle_name last_name


b. Multivalued Attribute: An Attribute can have more than one value

Phone _no

d. Derived Attribute:An attribute that can be derived from other attribute is known as a
derived attribute. It can be represented by a dashed ellipse.
Relations
Database Language
A DBMS has appropriate languages and interfaces to express database queries and
updates.
Database languages can be used to read, store and update the data in the database
1.DDL
2.DCL
3.DML
4.TCL
Data Definition Language
It is used to create schema, tables, indexes, constraints, etc. in the database.
Here are some tasks that come under DDL: Create: It is
used to create objects in the database.
Alter: It is used to alter the structure of the database. Drop:
It is used to delete objects from the database. Truncate: It is
used to remove all records from a table. Rename: It is used
to rename an object.
Comment: It is used to comment on the data dictionary.
Data Manipulation Language
It is used for accessing and manipulating data in a database. It handles user requests.
Select: It is used to retrieve data from a database.
Insert: It is used to insert data into a table.
Update: It is used to update existing data within a table.
Delete: It is used to delete all records from a table.
Merge: It performs UPSERT operation, i.e., insert or update operations. Call: It
is used to call a structured query language or a Java subprogram. Explain Plan:
It has the parameter of explaining data.
Lock Table: It controls concurrency.
Data Control Language
It is used to retrieve the stored or saved data.
The DCL execution is transactional. It also has rollback parameters. Here
are some tasks that come under DCL:

Grant: It is used to give user access privileges to a database.


Revoke: It is used to take back permissions from the user.
There are the following operations which have the authorization of
Revoke:

CONNECT, INSERT, USAGE, EXECUTE, DELETE, UPDATE


Transactional Control Language
TCL is used to run the changes made by the DML statement. TCL can be grouped into a
logical transaction.

Here are some tasks that come under TCL:

Commit: It is used to save the transaction on the database.

Rollback: It is used to restore the database to original since the last Commit.
Keys
Keys play an important role in Relational Database ,key are used to identify any record
and identify relationships between the tables.

KEYS:

1. Primary Key
2. Candidate Key
3. Super Key
4. Foreign Key
Primary Key

EMPLOYEE Primary Key: It is used to identify one and only one


instance of an entity uniquely.
E_ID
Here E_ID can be primary key since it is unique for each
E_NAME E_ADDRESS
employee, we can even select
E_PHONE_NO E_PHONE_NO,PASSPORT_ NUMBER, DEPT_ID as
PASSPORT_NUMBER primary key since they are also unique.

DEPT_ID Primary key is based on requirements of developers.


SSN
Super Key

EMPLOYEE Super Key: Super key is a superset of a candidate key.


Super key is a set of attributes which uniquely identifies
E_ID
a tuple.
E_NAME E_ADDRESS
E_ID, E_NAME) the name of two employees can be the
E_PHONE_NO same, but their EMPLYEE_ID can't be the same.
PASSPORT_NUMBER Hence, this combination can also be a key.

DEPT_ID

SSN
Foreign Key

EMPLOYEE Foreign keys are the column of the table which is used to
point to the primary key of another table.
E_ID

E_NAME E_ADDRESS
Department
E_PHONE_NO

PASSPORT_NUMBER DEPT_ID

DEPT_ID DEPT_NAME

SSN
VARIABLES
Variables are used for storing data or information during the execution of a
program.
MySQL can use variables in three different ways, which are given below: User-
Defined Variable
Local Variable
System Variable
User-Defined Variable: MySQL provides a SET and SELECT statement to
declare and initialize a variable. The user-defined variable name starts with @
symbol.
VARIABLES
EXAMPLE 1:

SET @NAME ='byteXL';

select @NAME;

EXAMPLE 2:
empId name dept

1 Clark Sales

2 Dave Accounting

3 Ava Sales

MYSQL>select @last_emp_id := max(empId) FROM EMPLOYEE;

OUTPUT:

@last_emp_id := max(empId) 3
VARIABLES
EXAMPLE 3: If you try to access undeclared variable ,it will give NULL O/P

select @AGE;;

output:

@AGE

NULL
LOCAL VARIABLES:

mysql> DECLARE total_price Oct(8,2) DEFAULT 0.0;

System variables:

MYSQL>show variables;

—--------------------***--------------------

To check the already existing databases use the following command.

Mysql> show databases;

To disconnect the opened MySQL database server, you need to use the exit
command.

mysql> EXIT;
DATABASE CREATION
DATABASE CREATION:

mysql>CREATE DATABASE COLLEGE;

We can review the newly created database using the below query that returns the
database name, character set, and collation of the database:

mysql> SHOW CREATE DATABASE COLLEGE;

We can check the created database using the following query:

mysql> SHOW DATABASE;


DATABASE SELECTION
To select particular database use SQL command ‘ USE’.

mysql>USE database_name;

—--------------------------------

show/list Database

mysql>SHOW DATABASE;
DROP DATABASE

mysql> DROP DATABASE DATABASE_NAME;

OR

mysql> DROP SCHEMA DATABASE_NAME;


CREATE TABLE
-- create
CREATE TABLE EMPLOYEE
( E_ID INT,
E_NAME TEXT,
E_ADDRESS TEXT,
E_PHONE_NO INT,
DEPT_ID INT
);
TO display tables in the database
mysql> SHOW TABLES;
mysql>DESCRIBE EMPLOYEE;
Output:

Field Type Null Key Default Extra

E_ID int YES NULL

E_NAME text YES NULL

E_ADDRESS text YES NULL

E_PHONE_NO int YES NULL

DEPT_ID int YES NULL


Data Types.
Numeric DataType:
DATA TYPE DESCRIPTION

TINYINT IF SIGNED RANGES FROM -128 TO 127


IF UNSIGNED RANGES FROM 0 TO 255

SMALLINT IF SIGNED RANGES FROM -32768 TO


32767
IF UNSIGNED RANGES FROM 0 TO
65535

MEDIUMINT IF SIGNED RANGES FROM -8388608 to


8388607
IF UNSIGNED RANGES FROM 0 to
16777215
DATA TYPE DESCRIPTION

INT IF SIGNED RANGES FROM -2147483648


to 2147483647
IF UNSIGNED RANGES FROM 0 to
4294967295

BIGINT IF SIGNED RANGES FROM


-9223372036854775808 to
9223372036854775807.
IF UNSIGNED RANGES FROM 0 to
18446744073709551615.
We can specify a width of up to 20 digits. It
requires 8 bytes for storage.

BIT(M) M determines the number of bit per value


that has a range of 1 to 64.
DATA TYPE DESCRIPTION

FLOAT(m,d) It is a floating-point number that cannot be


unsigned. You can define the display length
(m) and the number of decimals (d). This is
not required and will default to 10,2, where 2
is the number of decimals, and 10 is the total
number of digits (including decimals).
Decimal precision can go to 24 places for a
float type. It requires 2 bytes for storage.

BOOL It is used only for the true and false condition.


It considered numeric value 1 as true and 0 as
false

BOOLEAN It is similar to the BOOL.


DATE AND TIME DATA TYPE

Data Type Maximum size Explanation

YEAR[(2|4)] Year value as 2 digits or 4 The default is 4 digits. It


digits. takes 1 byte for storage.

DATE Values range from '1000-01-01' Displayed as 'yyyy-mm-dd'.


It
to '9999-12-31'.
takes 3 bytes for storage.
TIME Values range from '-838:59:59' to Displayed as 'HH:MM:SS'.
It
'838:59:59'.
takes 3 bytes plus
fractional seconds for storage.

DATETIME Values range from '1000-01-01 Displayed as 'yyyy-mm-dd


00:00:00' to '9999-12-31 hh:mm:ss'. It takes 5 bytes plus

23:59:59'. fractional seconds for storage.


TIMESTAMP(m) Values range from Displayed as 'YYYY-MM-DD HH:MM:SS'. It
'1970-01-01 00:00:01' takes 4 bytes plus fractional seconds for storage.
UTC to '2038-01-19
03:14:07' TC.
STRING DATA TYPE
Data Type Maximum size Explanation

CHAR(size) It can have a maximum size of 255 Here size is the number of characters to
characters. store. Fixed-length strings. Space padded on the
right to equal size characters.

VARCHAR(size) It can have a maximum size of 255 Here size is the number of characters to
characters. store. Variable-length string.

TINYTEXT(size) It can have a maximum size of 255 Here size is the number of characters to
characters. store.

TEXT(size) Maximum size of 65,535 Here size is the number of characters to


characters. store.
ENUM It takes 1 or 2 bytes that It is short for enumeration, which means
depend on the number of that each column may have one of the specified
enumeration values. An possible values. It uses numeric indexes (1, 2,
ENUM can have a 3…) to represent string values.
maximum of 65,535
values.

SET It takes 1, 2, 3, 4, or 8 It can hold zero or more, or any number of

bytes that depends on string values. They must be chosen from a

the number of set predefined list of values specified during

members. It can store a table creation.

maximum of 64

members.
Data Type Maximum size Explanation

MEDIUMTEXT(size) It can have a maximum size of Here size is the number of characters to
16,777,215 characters. store.

LONGTEXT(size) It can have a maximum size of Here size is the number of characters to
4GB or 4,294,967,295 characters. store.

BINARY(size) It can have a maximum size of 255 Here size is the number of binary characters
characters. to store. Fixed-length strings. Space padded on
the right to equal size characters.

VARBINARY(size) It can have a maximum size of 255 Here size is the number of characters to
characters. store. Variable-length string.
(introduced in MySQL 4.1.2)
ALTER TABLES
Alter is used to change the name of the table or any field,it is used to add or delete an existing column
in a table.

Alter is used with ADD,DROP,MODIFY


Syntax:ALTER TABLE table_name
ADD new_column_name column_definition [
FIRST | AFTER column_name ];
Ex:alter table EMPLOYEE add e_age int;
2: alter table EMPLOYEE add e_age int FIRST;
DESCRIBE EMPLOYEE;
ALTER TABLES
To display the table:
SYNTAX: SELECT * FROM TABLE_NAME;
mysql> SELECT * FROM EMPLOYEE;
Adding multiple columns in the table:
ALTER TABLE table_name
ADD new_column_name column_definition [
FIRST | AFTER column_name ],
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
... ;
ALTER TABLES
eXAMPLE: alter table EMPLOYEE add e_age int FIRST,ADD EPH_NO BIGINT ;

DESCRIBE EMPLOYEE;
ALTER TABLES
Example 2:
-CREATE TABLE EMPLOYEE
( empId INTEGER PRIMARY
KEY, name TEXT NOT NULL,
dept TEXT NOT NULL,
date_of_birth DATETIME
);
ALTER TABLES
Example 2: — ALTER AND ADD

CREATE TABLE EMPLOYEE

( empId INTEGER PRIMARY

KEY, name TEXT NOT NULL,

dept TEXT NOT NULL,

date_of_birth DATETIME

);

ALTER TABLE EMPLOYEE ADD E_AGE INT NOT NULL,

ADD E_SALARY INT NOT NULL,

ADD E_ADDRESS VARCHAR(100);

DESC EMPLOYEE;
ALTER TABLES
– ALTER and MODIFY
ALTER TABLE table_name
MODIFY column_name column_definition [
FIRST | AFTER column_name ];
EXAMPLE 1:;
ALTER TABLE EMPLOYEE MODIFY
empId BIGINT NOT NULL;
Example 2:
ALTER TABLE EMPLOYEE MODIFY
name varchar(50) NOT NULL AFTER
empId;
ALTER TABLES
–DROP TABLES USING ALTER
Syntax:ALTER TABLE table_name DROP COLUMN column_name;
Example 1: ALTER TABLE EMPLOYEE DROP COLUMN E_ADDRESS;
DESC EMPLOYEE;
EXAMPLE 2:-- MULTIPLE COLUMNS
ALTER TABLE Test
DROP COLUMN Mobile_number,
DROP COLUMN Email;
ALTER TABLES
– CHANGE COLUMN NAME IN TABLE USING ALTER

Syntax: ALTER TABLE table_name

CHANGE COLUMN old_name new_name column_definition [ FIRST | AFTER


column_name ]

EX 1:ALTER TABLE EMPLOYEE CHANGE COLUMN date_of_birth E_dob DATE


NOT NULL;

DESC EMPLOYEE;
ALTER TABLES
–CHANGING TABLE NAME

Syntax:ALTER TABLE table_name RENAME TO new_table_name;

Example 1: ALTER TABLE EMPLOYEE RENAME TO EMP;

desc EMP;

–TO DISPLAY TABLES IN THE DATABASE.

Syntax: show tables;

–FULL MODIFIER– To get the type of table (Base or View) .

show FULL TABLES;


TRUNCATE TABLES
We cannot use the WHERE clause with this command so that filtering of records is not
possible.

We cannot rollback the deleted data after executing this command because the log is
not maintained while performing this operation.

We cannot use the truncate statement when a table is referenced by a foreign key or
participates in an indexed view.

The TRUNCATE command doesn't fire DELETE triggers associated with the table that is
being truncated because it does not operate on individual rows.
TRUNCATE TABLES
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

DESC EMPLOYEE;

SELECT * FROM EMPLOYEE;

TRUNCATE TABLE EMPLOYEE;

SELECT * FROM EMPLOYEE;


SELECT,SHOW,EXPLAIN TABLES
CREATE TABLE EMPLOYEE (
empId INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT NOT NULL);
INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT
INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT
INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales'); SELECT * FROM
EMPLOYEE;
SHOW COLUMNS FROM EMPLOYEE;
EXPLAIN SELECT *FROM EMPLOYEE;
The EXPLAIN keyword is synonyms to the DESCRIBE statement, which is used to obtain information about how MySQL executes the
queries. It can work with INSERT, SELECT, DELETE, UPDATE, and REPLACE queries.

– TO GET FULL INFO CREATE

TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL

);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

DESC EMPLOYEE;

EXPLAIN SELECT *FROM EMPLOYEE;

SHOW FULL COLUMNS FROM EMPLOYEE;


DROP
DROP TABLE EMPLOYEE;

SELECT * FROM EMPLOYEE;

—---
COPY/CLONE/DUPLICATE A TABLE
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL

);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales'); CREATE TABLE

EMP SELECT empId,name FROM EMPLOYEE;

select * FROM EMPLOYEE;

SELECT *FROM EMP;


COPY/CLONE/DUPLICATE A TABLE-using WHERE
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales'); INSERT INTO

EMPLOYEE VALUES (0004, 'Clark', 'Sales'); INSERT INTO

EMPLOYEE VALUES (0005, 'Dave', 'Accounting'); INSERT INTO

EMPLOYEE VALUES (0006, 'Ava', 'Sales');

CREATE TABLE EMP SELECT dept,name FROM EMPLOYEE where dept='sales'; select

* FROM EMPLOYEE;

SELECT *FROM EMP;


COPY/CLONE/DUPLICATE A TABLE-using WHERE
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales'); INSERT INTO

EMPLOYEE VALUES (0004, 'Clark', 'Sales'); INSERT INTO

EMPLOYEE VALUES (0005, 'Dave', 'Accounting'); INSERT INTO

EMPLOYEE VALUES (0006, 'Ava', 'Sales');

CREATE TABLE EMP SELECT dept,name FROM EMPLOYEE where dept='sales'; select

* FROM EMPLOYEE;

SELECT *FROM EMP;


COPY/CLONE/DUPLICATE A TABLE-IF NOT EXIST
SYNTAX:CREATE TABLE IF NOT EXISTS new_table_name SELECT column1, column2,
column3 FROM existing_table_name WHERE condition;
EX1: (emp)IF NOT PRESENT
CREATE TABLE EMP SELECT dept,name FROM EMPLOYEE where dept='sales';
SELECT *FROM EMP;
–ERROR
EX1: IF PRESENT
CREATE TABLE EMP SELECT dept,name FROM EMPLOYEE where dept='sales';
SELECT *FROM EMP;
–ALREADY EXIST
COPY/CLONE/DUPLICATE A TABLE- AS IT IS
CREATE TABLE EMPLOYEE ( empId INTEGER PRIMARY KEY, name TEXT NOT NULL, dept TEXT NOT NULL)

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales'); INSERT INTO

EMPLOYEE VALUES (0004, 'Clark', 'Sales'); INSERT INTO

EMPLOYEE VALUES (0005, 'Dave', 'Accounting'); INSERT INTO

EMPLOYEE VALUES (0006, 'Ava', 'Sales'); CREATE TABLE EMP

LIKE EMPLOYEE;

SELECT * FROM EMP;

INSERT EMP SELECT * FROM EMPLOYEE;

SELECT * FROM EMP;


COPY/CLONE/DUPLICATE A TABLE- FROM ANOTHER DB

CREATE TABLE destination_db.new_table_name

LIKE source_db.existing_table_name;

INSERT destination_db.new_table_name SELECT *

FROM source_db.existing_table_name;
SHOW COLUMNS
SYNTAX: SHOW [EXTENDED] [FULL] {COLUMNS | FIELDS}

{FROM | IN} table_name

[{FROM | IN} db_name]

[LIKE 'pattern' | WHERE


expr]

The EXTENDED is an optional keyword to display the information, including hidden columns. MySQL uses hidden columns
internally that are not accessible by users.

The FULL is also an optional keyword to display the column information, including collation, comments, and the
privileges we have for each column.

The table_name is the name of a table from which we are going to show column information.

The db_name is the name of a database containing a table from which we will show column information. The

LIKE or WHERE clause is used to display only the matched column information in a given table.
SHOW COLUMNS
SYNTAX: SHOW [EXTENDED] [FULL] {COLUMNS | FIELDS}

{FROM | IN} table_name

[{FROM | IN} db_name]

[LIKE 'pattern' | WHERE


expr]

The EXTENDED is an optional keyword to display the information, including hidden columns. MySQL uses hidden columns
internally that are not accessible by users.

The FULL is also an optional keyword to display the column information, including collation, comments, and the
privileges we have for each column.

The table_name is the name of a table from which we are going to show column information.

The db_name is the name of a database containing a table from which we will show column information. The

LIKE or WHERE clause is used to display only the matched column information in a given table.
SHOW COLUMNS

–DISPLAY COLUMNS OF A TABLE FROM PARTICULAR DB

SHOW COLUMNS FROM mytable_name FROM mydb_name;

OR,

SHOW COLUMNS FROM mydb_name.mytable_name;

–FROM PRESENT DB

mysql>SHOW COLUMNS FROM EMPLOYEE;


SHOW COLUMNS-using like ‘% ‘
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

e_name TEXT NOT NULL,

e_dept TEXT NOT NULL

);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

SHOW COLUMNS FROM EMPLOYEE like 'e_%';


VIEW
CREATE [OR REPLACE] VIEW view_name AS
SELECT columns
FROM tables
[WHERE conditions];

The view syntax


contains the following
parameters:

OR REPLACE: It is optional. It is used when a VIEW already exists. If you do not specify this clause and the
VIEW already exists, the CREATE VIEW statement will return an error.
view_name: It specifies the name of the VIEW that you want to create in MySQL.

WHERE conditions: It is also optional. It specifies the conditions that must be met for the records to be
included in the VIEW.
VIEW
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

e_name TEXT NOT NULL,

e_dept TEXT NOT NULL

);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

CREATE VIEW FRIENDS AS SELECT e_dept, e_name from EMPLOYEE;

SELECT * FROM FRIENDS;


DROP-VIEW
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

e_name TEXT NOT NULL,

e_dept TEXT NOT NULL

);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales'); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

CREATE VIEW FRIENDS AS SELECT e_dept, e_name from EMPLOYEE;

SELECT * FROM FRIENDS;

Drop view IF EXISTS friends;

Drop view IF EXISTS FRIENDS;


TABLE LOCKING

MySQL allows a client session to acquire a table lock explicitly to cooperate with other
sessions to access the table's data. MySQL also allows table locking to prevent it from
unauthorized modification into the same table during a specific period.A session in
MySQL can acquire or release locks on the table only for itself. Therefore, one session
cannot acquire or release table locks for other sessions. It is to note that we must have a
TABLE LOCK and SELECT privileges for table locking.
Table Locking in MySQL is mainly used to solve concurrency problems. It will be
used while running a transaction, i.e., first read a value from a table (database) and then
write it into the table (database)
READ LOCK: This lock allows a user to only read the data from a table.
WRITE LOCK: This lock allows a user to do both reading and writing into a table.
TABLE LOCKING

MySQL allows a client session to acquire a table lock explicitly to cooperate with other
sessions to access the table's data. MySQL also allows table locking to prevent it from
unauthorized modification into the same table during a specific period.A session in
MySQL can acquire or release locks on the table only for itself. Therefore, one session
cannot acquire or release table locks for other sessions. It is to note that we must have a
TABLE LOCK and SELECT privileges for table locking.
Table Locking in MySQL is mainly used to solve concurrency problems. It will be
used while running a transaction, i.e., first read a value from a table (database) and then
write it into the table (database)
READ LOCK: This lock allows a user to only read the data from a table.
WRITE LOCK: This lock allows a user to do both reading and writing into a table.
TABLE LOCKING

syntax: LOCK TABLES table_name [READ | WRITE];


CREATE TABLE info_table (
Id INT NOT NULL,
Name VARCHAR(50) NOT NULL,
Message VARCHAR(80) NOT NULL,
primary key(id)
);
lock tables info_table read;;
insert into info_table values(1,'asd','adf');
TABLE LOCKING
– LOCKING MULTIPLE TABLES lock tables info_table read,EMPLOYEE write;;

CREATE TABLE info_table UNLOCK TABLES;

( Id INT NOT NULL, INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales');

Name VARCHAR(50) NOT NULL, select * from EMPLOYEE;

Message VARCHAR(80) NOT NULL, INSERT INTO EMPLOYEE VALUES (0002, 'Clark', 'Sales');

primary key(id)

);

CREATE TABLE EMPLOYEE

( empId INTEGER PRIMARY KEY,

name TEXT NOT NULL,

dept TEXT NOT NULL);


TABLE LOCKING
– LOCKING MULTIPLE TABLES CREATE TABLE info_table (

Id INT NOT NULL,


syntaxLOCK TABLES tab_name1 [READ | WRITE],
Name VARCHAR(50) NOT NULL,
tab_name2 [READ | WRITE],...... ;
Message VARCHAR(80) NOT NULL,
CREATE TABLE info_table
primary key(id)
( Id INT NOT NULL,
);

Name VARCHAR(50) NOT NULL, CREATE TABLE EMPLOYEE

Message VARCHAR(80) NOT NULL, ( empId INTEGER PRIMARY KEY,

primary key(id) name TEXT NOT NULL,

dept TEXT NOT NULL


);
);
lock tables info_table read;;
lock tables info_table
insert into info_table values(1,'asd','adf'); read,EMPLOYEE read;;

INSERT INTO EMPLOYEE VALUES


(0001, 'Clark', 'Sales');
UNLOCK TABLE

SYNTAX: UNLOCK TABLES;


INSERTION INTO TABLE
–INSERT RECORD INTO SINGLE ROW

SYNTAX:INSERT INTO table_name ( field1, field2,...fieldN )

VALUES ( value1, value2,...valueN );

EX: CREATE TABLE EMPLOYEE

( empId INTEGER PRIMARY KEY,

e_name TEXT NOT NULL,

e_dept TEXT NOT NULL);

INSERT INTO EMPLOYEE VALUES (0001, 'charan', 'Sales');

INSERT INTO EMPLOYEE VALUES (0002, 'mahesh', 'Accounting');

INSERT INTO EMPLOYEE VALUES (0003, 'prashanth', 'Sales');


INSERTION INTO TABLE
–INSERT RECORD INTO MULTIPLE ROW’S
INSERT INTO EMPLOYEE (empId,e_name,e_dept) VALUES (0004, 'SWETHA', 'Sales'),(0005,
'ATUL', 'Sales');
–INSERTING DATE INTO THE TABLE
ALTER TABLE EMPLOYEE ADD E_DOB DATE ;
INSERT INTO EMPLOYEE (empId,e_name,e_dept,E_DOB) VALUES
(0006,'APALAYA','MANAGAER','2008-7-04');
–TO INSERT CURRENT DATE
INSERT INTO EMPLOYEE (empId,e_name,e_dept,E_DOB) VALUES
(0006,'APALAYA','MANAGAER',current_date());
SELECT * FROM EMPLOYEE;
UPDATE TABLE
– UPDATE MULTIPLE COLUMNS
UPDATE EMPLOYEE SET E_DOB='1989-02-11',e_name='kiran' WHERE
empId=1;
SELECT * FROM EMPLOYEE;
– replace
UPDATE Trainer_table
SET email = REPLACE(email,'@learning.com','@bytexlELearning.com')
WHERE course_name = 'Testing';
UPDATE TABLE

The UPDATE statement is used with the SET and WHERE clauses. The SET clause is used to
change the values of the specified column. We can update single or multiple columns at a time.

SYNTAX:UPDATE table_name SET


column_name1 = new-value1,
column_name2=new-value2, ...
[WHERE Clause]
example:
UPDATE EMPLOYEE SET E_DOB='1989-02-11' WHERE empId=1;
SELECT * FROM EMPLOYEE;
UPDATE TABLE
– IS NULL – USED IN INSERT,UPDATE,AND DELETE

example:

UPDATE EMPLOYEE SET joining_date = CURRENT_DATE() WHERE joining_date IS NULL;

select *from EMPLOYEE;

—AND—

example:

UPDATE EMPLOYEE SET name='SRAVYA' where (dept ='Sales' AND empId > 4);
DELETE TABLE

– single row

DELETE FROM EMPLOYEE WHERE empId=5;

-- DELETE FROM EMPLOYEE ORDER BY e_name LIMIT 2;

SELECT *FROM EMPLOYEE;

DELETE FROM EMPLOYEE ORDER BY e_name LIMIT 2;

SELECT *FROM EMPLOYEE;


DELETE TABLE

DELETE FROM EMPLOYEE ORDER BY e_name LIMIT 2;

SELECT *FROM EMPLOYEE;

DELETE FROM EMPLOYEE e_name LIMIT 2;

SELECT *FROM EMPLOYEE;


CLAUSES

Clause are inbuit functions, which help in filter and analyze data quickly when we have
large amount data stored in the database.
1. WHERE CLAUSE
2. DISTINCT CLAUSE
3. FROM
4. ORDER BY
5. GROUP BY
6. HAVING
WHERE CLAUSES

SYNTAX : WHERE CONDITION; 11. IS NULL


CONDITIONS: 12 IS NOT NULL
1. AND
13. BETWEEN.
2. OR
3. AND OR
4. BOOLEAN
5. LIKE
6. IN
7. ANY
8. EXISTS
9. NOT
10. Not Equal
AND CONDITION

AND condition is used with SELECT, INSERT, UPDATE or DELETE statements to test two or more conditions in an individual query.

CREATE TABLE EMPLOYEE ( e_id INTEGER , e_name TEXT, e_dept TEXT, e_dob date, e_salary bigint, e_address varchar(20)); insert into

EMPLOYEE (e_id,e_name,e_dept,e_dob,e_salary,e_address values

(1,'yashwini','training','1982-03-23',23000,'chenni'),

(2,'ramani','accounts','1987-03-23',28000,'pune'),

(3,NULL,'developer','1999-04-23',30000,'hyderabad'),

(4,'sathya','training','1997-11-06',20500,'karnataka'),

(5,'samhitha','training','1982-03-23',25000,'chenni'),

(6,NULL,'accounts','1989-03-23',23000,'pune'),

(7,'sreya','developer','1991-04-23',33000,'hyderabad'),

(8,'sathyabhama','training','2000-11-25',12000,'karnataka');

select * from EMPLOYEE;


– AND
–SELECT
select * from EMPLOYEE WHERE e_salary= 23000 AND e_id<6;
– UPDATE
UPDATE EMPLOYEE SET e_name='hyma' where e_id=3 and e_address =
'hyderabad';;
select * from EMPLOYEE;
–DELETE
DELETE FROM EMPLOYEE WHERE e_id= 4 AND e_name= 'sathya';
SELECT * FROM EMPLOYEE;
– OR
–SELECT
select * from EMPLOYEE WHERE e_salary= 23000 AND e_id<6;
– UPDATE
UPDATE EMPLOYEE SET e_name='hyma' where e_id=3 and e_address =
'hyderabad';;
select * from EMPLOYEE;
–DELETE
DELETE FROM EMPLOYEE WHERE e_id= 4 AND e_name= 'sathya';
SELECT * FROM EMPLOYEE;
– OR

–SELECT

SELECT * FROM EMPLOYEE WHERE e_salary< 30000 or e_salary >50000;

- AND OR –

SELECT * FROM EMPLOYEE WHERE e_salary< 30000 AND (e_address


='hyderabad or e_address= 'chennai');
– LIKE

expression LIKE pattern [ ESCAPE 'escape_character' ]

expression: It specifies a column or field.

pattern: It is a character expression that contains pattern matching. select

e_address FROM EMPLOYEE WHERE e_address like 'h%';

select e_address FROM EMPLOYEE WHERE e_address like '%e';

select e_address FROM EMPLOYEE WHERE e_address like 'hy

de';
– LIKE
WHERE e_address NOT LIKE 'ka%';
IN
IN condition is used to reduce the use of multiple OR conditions
select * from EMPLOYEE
WHERE e_address IN ('hyderabad','karnataka');
NOT IN
select * from EMPLOYEE
WHERE e_address IN ('hyderabad','karnataka');
– ANY :returns the Boolean value TRUE

The ANY operator works like comparing the value of a table to each value in
the result set provided by the subquery condition

SYNTAX :operand comparison_operator ANY (subquery)

COMPARISON OPERATORS: = > < >= <= <> !=

SELECT column_lists FROM table_name1 WHERE column_name Operator ANY


(SELECT column_name FROM table_name2 WHERE condition);
CREATE TABLE JUNIOR ( INSERT INTO JUNIOR VALUES (0001, 'Clark',
'Sales',23000);
empId INTEGER PRIMARY KEY,
INSERT INTO JUNIOR VALUES (0002, 'Dave',
name TEXT NOT NULL,
'Accounting',24000);
dept TEXT NOT NULL,
INSERT INTO JUNIOR VALUES (0003, 'Ava',
salary int 'Sales',23500);
); INSERT INTO SENIORS VALUES (0001, 'SAM',
'Sales',23000);
CREATE TABLE SENIORS
INSERT INTO SENIORS VALUES (0002, 'LUCY',
( empId INTEGER PRIMARY
'Accounting',45000);
KEY, name TEXT NOT NULL,
INSERT INTO SENIORS VALUES (0003, 'RITA',
dept TEXT NOT NULL, 'Sales',36000);
salary int SELECT * FROM JUNIOR WHERE salary <=
ANY
);
(select salary from SENIORS where empId =
2);
EXITS

The EXISTS operator in MySQL is a type of Boolean operator which returns the true or false result. It is used in
combination with a subquery and checks the existence of data in a subquery. It means if a subquery returns any record, this
operator returns true.

SYNTAX:

SELECT col_names

FROM tab_name

WHERE [NOT] EXISTS (

SELECT col_names

FROM tab_name

WHERE condition

);
CREATE TABLE JUNIOR ( –

empId INTEGER PRIMARY KEY, INSERT INTO JUNIOR VALUES (0001, 'Clark', 'Sales',23000);

name TEXT NOT NULL, INSERT INTO JUNIOR VALUES (0002, 'Dave',
'Accounting',24000);
dept TEXT NOT NULL,
INSERT INTO JUNIOR VALUES (0003, 'Ava', 'Sales',23500);
salary int
--
);

CREATE TABLE SENIORS INSERT INTO SENIORS VALUES (0001, 'SAM', 'Sales',23000);

( empId INTEGER PRIMARY INSERT INTO SENIORS VALUES (0002, 'LUCY',


'Accounting',45000);
KEY, name TEXT NOT NULL,
INSERT INTO SENIORS VALUES (0003, 'RITA', 'Sales',24000);
dept TEXT NOT NULL,
SELECT * FROM JUNIOR WHERE
salary int
EXISTS (select * from SENIORS
);
where JUNIOR.salary=SENIORS.salary);
CREATE TABLE JUNIOR ( –

empId INTEGER PRIMARY KEY, INSERT INTO JUNIOR VALUES (0001, 'Clark', 'Sales',23000);

name TEXT NOT NULL, INSERT INTO JUNIOR VALUES (0002, 'Dave',
'Accounting',24000);
dept TEXT NOT NULL,
INSERT INTO JUNIOR VALUES (0003, 'Ava', 'Sales',23500);
salary int
--
);

CREATE TABLE SENIORS INSERT INTO SENIORS VALUES (0001, 'SAM', 'Sales',23000);

( empId INTEGER PRIMARY INSERT INTO SENIORS VALUES (0002, 'LUCY',


'Accounting',45000);
KEY, name TEXT NOT NULL,
INSERT INTO SENIORS VALUES (0003, 'RITA', 'Sales',24000);
dept TEXT NOT NULL,
SELECT * FROM JUNIOR WHERE
salary int
NOT EXISTS (select * from SENIORS
);
where JUNIOR.salary=SENIORS.salary);
CREATE TABLE JUNIOR ( INSERT INTO JUNIOR VALUES (0001, 'Clark', 'Sales',23000);

empId INTEGER PRIMARY KEY, INSERT INTO JUNIOR VALUES (0002, 'Dave',
'Accounting',24000);
name TEXT NOT NULL,
INSERT INTO JUNIOR VALUES (0003, 'Ava', 'Sales',23500);
dept TEXT NOT NULL,
--
salary int

); INSERT INTO SENIORS VALUES (0001, 'SAM', 'Sales',23000);

CREATE TABLE SENIORS INSERT INTO SENIORS VALUES (0002, 'LUCY',


'Accounting',45000);
( empId INTEGER PRIMARY
INSERT INTO SENIORS VALUES (0003, 'RITA', 'Sales',24000);
KEY, name TEXT NOT NULL,
DELETE FROM JUNIOR WHERE
dept TEXT NOT NULL,
EXISTS (select * from SENIORS
salary int
where JUNIOR.salary=SENIORS.salary);
);
select * from JUNIOR;
INSERT INTO JUNIOR VALUES (0001, 'Clark', 'Sales',23000);
CREATE TABLE JUNIOR (
INSERT INTO JUNIOR VALUES (0002, 'Dave',
empId INTEGER PRIMARY KEY, 'Accounting',24000);
name TEXT NOT NULL, INSERT INTO JUNIOR VALUES (0003, 'Ava', 'Sales',23500);

dept TEXT NOT NULL, --

salary int INSERT INTO SENIORS VALUES (0001, 'SAM', 'Sales',23000);

); INSERT INTO SENIORS VALUES (0002, 'LUCY',


'Accounting',45000);
CREATE TABLE SENIORS
INSERT INTO SENIORS VALUES (0003, 'RITA', 'Sales',24000);
( empId INTEGER PRIMARY
SELECT
KEY, name TEXT NOT NULL,
EXISTS (select * from SENIORS
dept TEXT NOT NULL,
where salary=26000)
salary int
AS SAME_SALARY;
); –It does not perform a comparison between parent query
and child query or subquery.
– BETWEEN

CREATE TABLE EMPLOYEE (

empId INTEGER ,

name TEXT NOT NULL,

dept TEXT NOT NULL,

e_salary int,

DOB date

);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales',23000,'1892-01-11');

INSERT INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting',24000,'1899-04-30');

INSERT INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales',23500,'1992-07-31');

INSERT INTO EMPLOYEE VALUES (0004, 'Clark', 'Sales',23000,'197-06-23');

INSERT INTO EMPLOYEE VALUES (0005, 'Dave', 'Accounting',24000,'1972-04-15');

INSERT INTO EMPLOYEE VALUES (0006, 'Ava', 'Sales',23500,'1995-07-31');


– BETWEEN

SELECT * FROM EMPLOYEE WHERE empId BETWEEN 2 AND 5;


– NOT

SELECT * FROM EMPLOYEE WHERE empId BETWEEN 2 AND 5;


— FOR DATES -BETWEEN
SELECT * FROM EMPLOYEE WHERE DOB BETWEEN
CAST('1990-01-30'AS DATE) AND CAST('2000-12-30'AS DATE);
–FOR NOT- BETWEEN
SELECT * FROM EMPLOYEE WHERE DOB NOT BETWEEN
CAST('1990-01-30'AS DATE) AND CAST('2000-12-30'AS DATE);
– NOT EQUAL

SELECT * FROM EMPLOYEE WHERE dept <> " sales";

SELECT * FROM EMPLOYEE WHERE dept != " sales";


CREATE TABLE student (

studentid INT,

name VARCHAR(40) NOT NULL,

age VARCHAR(3),

pass BOOLEAN

);

INSERT INTO student (name, pass) VALUES('Peter',true), ('John',false);

SELECT studentid, name, pass FROM student;


DISTINCT CLAUSE

If you use a single expression then the INSERT INTO EMPLOYEE VALUES (0001, 'Clark',
'Sales',23000,'1892-01-11');
MySQL DISTINCT clause will return a
single field with unique record INSERT INTO EMPLOYEE VALUES (0002, 'Dave',
'Accounting',24000,'1899-04-30');
CREATE TABLE EMPLOYEE ( INSERT INTO EMPLOYEE VALUES (0003, 'Ava',
'Sales',23500,'1992-07-31');
empId INTEGER , name
INSERT INTO EMPLOYEE VALUES (0004, 'Clark',
TEXT NOT NULL, dept 'Sales',23000,'197-06-23');

TEXT NOT NULL, INSERT INTO EMPLOYEE VALUES (0005, 'Dave',


'Accounting',24000,'1972-04-15');
e_salary int, INSERT INTO EMPLOYEE VALUES (0006, 'Ava',
'Sales',23500,'1995-07-31');
DOB date
SELECT DISTINCT dept from EMPLOYEE;
);
DISTINCT CLAUSE

If you use a single expression then the INSERT INTO EMPLOYEE VALUES (0001, 'Clark',
'Sales',23000,'1892-01-11');
MySQL DISTINCT clause will return a
single field with unique record INSERT INTO EMPLOYEE VALUES (0002, 'Dave',
'Accounting',24000,'1899-04-30');
CREATE TABLE EMPLOYEE ( INSERT INTO EMPLOYEE VALUES (0003, 'Ava',
'Sales',23500,'1992-07-31');
empId INTEGER , name
INSERT INTO EMPLOYEE VALUES (0004, 'Clark',
TEXT NOT NULL, dept 'Sales',23000,'197-06-23');

TEXT NOT NULL, INSERT INTO EMPLOYEE VALUES (0005, 'Dave',


'Accounting',24000,'1972-04-15');
e_salary int, INSERT INTO EMPLOYEE VALUES (0006, 'Ava',
'Sales',23500,'1995-07-31');
DOB date
SELECT DISTINCT dept from EMPLOYEE;
);
ORDER BY CLAUSE

The MYSQL ORDER BY Clause is used Parameters


to sort the records in ascending or expressions: It specifies the columns that you want to
descending order retrieve.
tables: It specifies the tables, from where you want to
SYNTAX: retrieve records. There must be at least one table listed
in the FROM clause.
SELECT expressions
WHERE conditions: It is optional. It specifies
FROM tables conditions that must be fulfilled for the records to be
selected.
[WHERE conditions] ASC: It is optional. It sorts the result set in
ascending order by expression (default, if no
ORDER BY modifier is provider).
expression [ ASC | DESC: It is also optional. It sorts the result set in
DESC ]; descending order by expression.
ORDER BY CLAUSE

EX1: EX 3:
SELECT * FROM EMPLOYEE SELECT name FROM EMPLOYEE
WHERE e_salary >23000 WHERE dept= 'Sales'
order by name; order by name DESC;
EX 2: EX 4:
SELECT name FROM SELECT name FROM
EMPLOYEE EMPLOYEE
WHERE e_salary >23000 WHERE dept= 'Sales'
order by name ASC;; order by name
DESC,name ASC;
CONTROL FLOW-IF

IF function is used for validating a function.This ex1:SELECT IF(5<6 and 5>3,'yes','no')


function is known as IF-ELSE and IF THAN
ELSE function. ex2: SELECT
SYTAX: IF ( expression 1, expression 2, IF(strcmp('ashu','ASHU')=0,'yes','no')
expression 3)
Expression 1 Required It is a value, which is
used for validation.
Expression 2 Optional It returns a value
when the condition evaluates to true.
Expression 3 Optional It returns a value
when the condition evaluates to false.
CONTROL FLOW-IF

CREATE TABLE EMPLOYEE ( INSERT INTO EMPLOYEE VALUES (0003,


'Ava', 'Sales',23500,'1992-07-31');
empId INTEGER , name
TEXT NOT NULL, dept INSERT INTO EMPLOYEE VALUES (0004,
'Clark', 'Sales',23000,'197-06-23');
TEXT NOT NULL,
INSERT INTO EMPLOYEE VALUES (0005,
e_salary int, 'Dave', 'Accounting',24000,'1972-04-15');
DOB date INSERT INTO EMPLOYEE VALUES (0006,
);
'Ava', 'Sales',23500,'1995-07-31');

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', SELECT name, IF(e_salary > 23000,
'Sales',23000,'1892-01-11'); "good","still_good")

INSERT INTO EMPLOYEE VALUES (0002, 'Dave', As output


'Accounting',24000,'1899-04-30');
FROM EMPLOYEE;
CONTROL FLOW-IF NULL

IF NULL - used for handling NULL EX:1


values.
SELECT IFNULL(NULL,'SECOND');
IFNULL function accepts two
EX2:
expressions, and if the first expression is
not null, it returns the first arguments. If SELECT IFNULL(NULL,NULL);
the first expression is null, it returns the
EX 3:
second argument.
SELECT IFNULL(0,'HEY');
SYNTAX :
EX 4:
IFNULL (Expression1, Expression2)
SELECT IFNULL(NOT
NULL,'HEY');
CONTROL FLOW-IF NULL

EX 5:SELECT
NAME
FROM EMPLOYEE;
EX 6:
SELECT NAME,
IFNULL(empId,dept) new_name
FROM EMPLOYEE;
CONTROL FLOW-NULLIF

It also helps in preventing the division SELECT name,


by zero error in a SQL statement.
NULLIF(dept,'sales') sales_people
The NULLIF function accepts two
FROM EMPLOYEE;
expressions, and if the first expression is
equal to the second expression, it returns
the NULL. Otherwise, it returns the first
expression.
CONTROL FLOW-NULLIF

that provides us to write an if-else or if- ex 1:


then-else logic to a query. This SELECT name, NULLIF(dept,'sales')
expression can be used anywhere that uses sales_people FROM EMPLOYEE;
a valid program or query, such as
ex :2
SELECT, WHERE, ORDER BY clause,
SELECT name,
etc.
NULLIF(dept,'cot') sales_people
FROM EMPLOYEE;
ex 3:
SELECT 1/NULLIF(0,0);
CONTROL FLOW-CASE

This expression can be used anywhere that uses a valid program or query, such as SELECT, WHERE, ORDER
BY clause, etc
The CASE expression validates various conditions and returns the result when the first condition is true. Once
the condition is met, it stops traversing and gives the output. If it will not find any condition true, it executes the
else block. When the else block is not found, it returns a NULL value. The main goal of MySQL CASE statement
is to deal with multiple IF statements in the SELECT clause.
SYNTAX:
CASE value
WHEN [compare_value] THEN result
[WHEN [compare_value] THEN result ...]
[ELSE result]
END
CONTROL FLOW-CASE

EX 1:

SELECT CASE 2 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END; EX

2:

SELECT CASE 0 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END; EX

3:

SELECT CASE 'F' 'B' WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
CONTROL FLOW-CASE

SELECT studentid, firstname,

CASE class

WHEN 'CS' THEN 'Computer Science'

WHEN 'EC' THEN 'Electronics and Communication'

ELSE 'Electrical Engineering'

END AS department from students;


CONTROL FLOW-CASE

EX 1:

SELECT CASE 2 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END; EX

2:

SELECT CASE 0 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END; EX

3:

SELECT CASE 'F' 'B' WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
Aggregate Functions

function_name (DISTINCT | ALL expression)

First, we need to specify the name of the aggregate function.

Second, we use the DISTINCT modifier when we want to calculate the result based on
distinct values or ALL modifiers when we calculate all values, including duplicates.
The default is ALL.

Third, we need to specify the expression that involves columns and arithmetic
operators.
Aggregate Functions

Count() Function:
COUNT(*) Function: This function uses the SELECT statement to returns the count of rows
in a result set. The result set contains all Non-Null, Null, and duplicates rows.
COUNT(expression) Function: This function returns the result set without containing Null rows
as the result of an expression.

COUNT(distinct expression) Function: This function returns the count of distinct rows
without containing NULL values as the result of the expression.
MySQL count() function returns the total number of values in the expression.
SYNTAX: SELECT COUNT(name) FROM employee;
Aggregate Functions
CREATE TABLE EMPLOYEE (empId INTEGER NOT NULL ,name TEXT NOT NULL,

dept TEXT NOT NULL,

e_salary int,

DOB date,

no_hours int);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales',23000,'1892-01-11',12); INSERT

INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting’,24000,'1899-04-30',15); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales',23500,'1992-07-31',NULL); INSERT INTO

EMPLOYEE VALUES (0004, 'Clark', 'Sales',23000,'197-06-23',12); INSERT INTO EMPLOYEE

VALUES (0005, 'Dave', 'Accounting',24000,'1972-04-15',11); INSERT INTO EMPLOYEE

VALUES (0006, 'Ava', 'Sales',23500,'1995-07-31',NULL);


Aggregate Functions

EX 1:SELECT COUNT(no_hours) as 'working hours' from EMPLOYEE ;

EX 2:SELECT COUNT(no_hours) as 'working hours' from EMPLOYEE WHERE


no_hours>13;

EX 3: SELECT COUNT(DISTINCT no_hours) FROM EMPLOYEE;

EX 4: SELECT COUNT(DISTINCT no_hours) FROM EMPLOYEE WHERE


no_hours<13;

Ex 5: SELECT COUNT(DISTINCT no_hours)as working_work FROM EMPLOYEE


WHERE no_hours<13;
Aggregate Functions- sum()
The MySQL sum() function is used to return the total summed value of an expression
SYNTAX:
SELECT SUM(aggregate_expression)
FROM tables
[WHERE conditions];
aggregate_expression:
It specifies the column
or expression that we
are going to calculate
the sum.

table_name: It specifies the tables from where we want to retrieve records. There must be at least one table
listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the records to be
selected.
Aggregate Functions- sum()

EX 1:SELECT SUM(DISTINCT no_hours)as working_work FROM EMPLOYEE;;

EX 2: SELECT SUM(no_hours)as working_work FROM EMPLOYEE;;

EX 3: SELECT SUM(no_hours)as working_work FROM EMPLOYEE WHERE


no_hours>13;
Aggregate Functions- AVG()

The MySQL avg() is an aggregate function used to return the average value of an
expression in various records.
SYNTAX:SELECT AVG(aggregate_expression)
FROM tables
[WHERE conditions];
aggregate_expression: It specifies the column or expression that we are going to find the average
result.
table_name: It specifies the tables from where we want to retrieve records. There must be at
least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the
records to be selected.
Aggregate Functions- AVG()

EX 1:SELECT AVG(no_hours)as working_work FROM EMPLOYEE;

EX 2:SELECT AVG(no_hours)as working_work FROM EMPLOYEE WHERE


dept='Sales';

EX 3: SELECT AVG(no_hours) working_work FROM EMPLOYEE WHERE


dept='Sales';
Aggregate Functions- MIN()

The MIN() function in MySQL is used to return the minimum value in a set of values
from the table. It is an aggregate function that is useful when we need to find the
smallest number, selecting the least expensive product, etc
SYNTAX:
SELECT MIN ( DISTINCT aggregate_expression)
FROM table_name(s)
[WHERE conditions];
aggregate_expression: It is the required expression. It specifies the column or
expression name from which the minimum value will be returned.
Aggregate Functions- MIN()

EX 1: SELECT MIN(no_hours) as least_hours from EMPLOYEE;

EX 2: SELECT MIN(no_hours) as least_hours from EMPLOYEE WHERE


e_salary=23000;

EX 3: SELECT MIN(DISTINCT no_hours) as least_hours from EMPLOYEE


WHERE;
Aggregate Functions- MAX()

The MySQL MAX() function is used to return the maximum value in a set of values of an
expression. This aggregate function is useful when we need to find the maximum number,
selecting the most expensive product, or getting the largest payment to the customer from
your table

SELECT MAX(DISTINCT aggregate_expression)

FROM table_name(s)

[WHERE conditions];

.
Aggregate Functions- MAX()

EX 1: SELECT MAX(no_hours) as HEIGHEST_HOURSE from EMPLOYEE;

EX 2: SELECT MAX(no_hours) as HEIGHEST_HOURSE from EMPLOYEE;


Aggregate Functions- FIRST

The MySQL first function is used to return the first value of the selected column. Here,
we use limit clause to select first record or more.
SYNTAX:
SELECT column_name
FROM table_name
LIMIT 1;
To SELECT FIRST
element:
Consider a table named "officers", having the following data. EX
1: SELECT name FROM EMPLOYEE LIMIT 1;
Aggregate Functions- FIRST

The MySQL first function is used to return the first value of the selected column. Here,
we use limit clause to select first record or more.
SYNTAX:
SELECT column_name
FROM table_name
LIMIT 1;
To SELECT FIRST
element:
Consider a table named "officers", having the following data. EX
1: SELECT name FROM EMPLOYEE LIMIT 1;
Aggregate Functions- last

SYNTAX: SELECT column_name

FROM table_name

ORDER BY column_name DESC

LIMIT 1;

SELECT name FROM EMPLOYEE


ORDER BY name desc limit 1;
GROUP BY CLAUSE

The MYSQL GROUP BY Clause is used to collect data from multiple records and group the
result by one or more column. It is generally used in a SELECT statement.
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the
grouped column.
SYNTAX:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY
expression1,
GROUP BY CLAUSE- COUNT

ex1: find out count of the employes who belong to same department with same name?

select name,dept,count(*)

from EMPLOYEE

group by dept,name;
GROUP BY CLAUSE- sum
CREATE TABLE EMPLOYEE (

empId INTEGER PRIMARY KEY,

name TEXT ,

dept TEXT ,

branch text,

w_hours int);

INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales','cse',12); INSERT

INTO EMPLOYEE VALUES (0002, 'kavya', 'Accounting','me',13); INSERT

INTO EMPLOYEE VALUES (0003, 'Ava', 'development','ds',14); INSERT

INTO EMPLOYEE VALUES (0005, 'Clark', 'traning','cse',12); INSERT INTO

EMPLOYEE VALUES (0006, 'kavya', 'Accounting','me',15); INSERT INTO

EMPLOYEE VALUES (0007, 'Ava', 'Sales','ds',15);


GROUP BY CLAUSE- sum

ex 2: print the total number of hours worked by each employee in each dept? select
name,dept,sum(w_hours)
from EMPLOYEE
group by dept,name;
or
select name,dept,sum(w_hours) AS “WORKING HOURS”
from EMPLOYEE
group by dept,name;
GROUP BY CLAUSE- sum

ex 2: print the total number of hours worked by each employee in each dept? select
name,dept,sum(w_hours)
from EMPLOYEE
group by dept,name;
or
select name,dept,sum(w_hours) AS “WORKING HOURS”
from EMPLOYEE
group by dept,name;
GROUP BY CLAUSE- MIN

select name,dept,min(w_hours)

from EMPLOYEE

group by name,dept;

GROUP BY CLAUSE- MAX

select name,dept,min(w_hours)

from EMPLOYEE

group by name,dept;
select dept,AVG(w_hours)

from EMPLOYEE

group by dept;
HAVING CLAUSE- sum
MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where
condition is TRUE

COUNT, MIN, MAX and AVG functions.


Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
HAVING CLAUSE- sum

ex: print sum of working hours of the individual departments whose sum is more than 15
hours.

select dept,sum(w_hours)

from EMPLOYEE

group by dept

having sum(w_hours)>15;
INNER JOIN
CREATE TABLE EMPLOYEE (
empId INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT NOT NULL
);
CREATE TABLE EMP
( Id INTEGER ,
e name TEXT NOT
NULL, SALARY INT NOT
NULL
);
INNER JOIN
insert into EMPLOYEE VALUES(1001,'RAVI','CSE'),

(1002,'SRAVYA','CSE'),

(1003,'KAVYA','ECE'),

(1004,'RAMYA','ECE'),

(1005,'SATHYA','EEE');

INSERT INTO EMP VALUES(1001,'MANASI',32000),

(1002,'RAVALI',35000),

(1003,'SATHYA',52000),

(1004,'MANASI',32000);

select * from EMPLOYEE

INNER JOIN EMP

ON
EMPLOYEE.empId=EMP.I
d;
LEFT OUTER JOIN
CREATE TABLE TABLEA(

empId INTEGER PRIMARY KEY, name TEXT , dept TEXT);

CREATE TABLE TABLEB (

emp_Id INTEGER PRIMARY KEY,B_name TEXT , dept TEXT );

INSERT INTO TABLEA VALUES (0001, 'Clark', 'Sales');

INSERT INTO TABLEA VALUES (0002, 'Dave', 'Accounting');

INSERT INTO TABLEA VALUES (0004, NULL, 'Sales');

INSERT INTO TABLEB VALUES (0001, 'Clark', 'Sales'); INSERT

INTO TABLEB VALUES (0002, 'Dave', 'Accounting'); INSERT

INTO TABLEB VALUES (0003, 'Ava', NULL);

select empId,name from TABLEA left join TABLEB ON


TABLEA.empId=TABLEB.emp_Id;
RIGHT OUTER JOIN
CREATE TABLE TABLEA(
empId INTEGER PRIMARY KEY,name TEXT ,dept TEXT );
CREATE TABLE TABLEB (emp_Id INTEGER PRIMARY KEY,B_name TEXT ,dept TEXT );
INSERT INTO TABLEA VALUES (0001, 'Clark', 'Sales');
INSERT INTO TABLEA VALUES (0002, 'Dave', 'Accounting');
INSERT INTO TABLEA VALUES (0004, NULL, 'Sales');
INSERT INTO TABLEB VALUES (0001, 'Clark', 'Sales'); INSERT
INTO TABLEB VALUES (0002, 'Dave', 'Accounting'); INSERT
INTO TABLEB VALUES (0003, 'Ava', NULL);
select empId,name from TABLEA RIGHT join TABLEB ON
TABLEA.empId=TABLEB.emp_Id;
KEYS- UNIQUE KEY

unique key:A column cannot stores duplicate values.It can accept a null value, but
MySQL allowed only one null value per column.

Needs of Unique Key

It is useful in preventing the two records from storing identical values into the
column.

It stores only distinct values that maintain the integrity and reliability of the
database for accessing the information in an organized way.

It also works with a foreign key in preserving the uniqueness of a table. It can

contain null value into the table.


KEYS- UNIQUE KEY
SYNTAX:

CREATE TABLE

table_name( col1 datatype,

col2 datatype UNIQUE,

... );

(OR)

CREATE TABLE

table_name( col1

col_definition,

col2 col_definition,

...

[CONSTRAINT constraint_name]

UNIQUE(column_name(s)) );
KEYS- UNIQUE KEY
CREATE TABLE EMPLOYEE(

EMP_ID INT UNIQUE,

EMP_NAME VARCHAR(50),

EMP_MAIL VARCHAR(50),

EMP_PH BIGINT UNIQUE

);

INSERT INTO EMPLOYEE VALUES(1,'RAMYA','[email protected]',1234567890),

(2,'KAVYA','[email protected]',1234567899),

(3,'SRAVYA','[email protected]',1234567898),

(4,'RIYA','[email protected]',1234567896),

(5,'SATHYA','[email protected]',1234567897);
KEYS- UNIQUE KEY

TO CHECK UNIQUE COLUMNS

SHOW INDEX FROM EMPLOYEE;

TO DELETE UNIQUE KEY FROM THE TABLE

SYNTAX :ALTER TABLE table_name DROP INDEX constraint_name; EX

1: ALTER TABLE EMPLOYEE DROP INDEX EMP_ID;

EX 2: MORE THAN ONE COLUMN

ALTER TABLE EMPLOYEE DROP INDEX EMP_ID, DROP INDEX


EMP_PH;
KEYS- UNIQUE KEY

ADDING A UNIQUE KEY TO THE COLUMN IN THE TABLE


SYNTAX:
ALTER TABLE table_name ADD CONSTRAINT constraint_name
UNIQUE(column_list);
EX 1:
ALTER TABLE EMPLOYEE ADD CONSTRAINT UNIQUE(EMP_ID,EMP_MAIL);
SHOW INDEX FROM EMPLOYEE;
ALTER TABLE EMPLOYEE ADD CONSTRAINT UNIQUE(EMP_NAME);
SHOW INDEX FROM EMPLOYEE;
KEYS- PRIMARY KEY
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
primary key column can also use the AUTO_INCREMENT attribute to generate a sequential number for
that row automatically
Rules for Primary key
Following are the rules for the primary key:
The primary key column value must be unique.
Each table can contain only one primary key.
The primary key column cannot be null or empty.
MySQL does not allow us to insert a new row with
the existing primary key.
It is recommended to use INT or BIGINT data
KEYS- PRIMARY KEY
SYNTAX:

CREATE TABLE table_name( col1

datatype PRIMARY KEY, col2

datatype, …)

(OR)

CREATE TABLE table_name

( col1 col_definition,

col2 col_definition, CONSTRAINT

[constraint_name]

PRIMARY KEY (column_name(s))

);
KEYS- PRIMARY KEY
CREATE TABLE EMPLOYEE(

EMP_ID INT AUTO_INCREMENT PRIMARY KEY,

EMP_NAME VARCHAR(50),

EMP_MAIL VARCHAR(50),

EMP_PH BIGINT);

INSERT INTO EMPLOYEE (EMP_NAME,EMP_MAIL,EMP_PH)

VALUES('RAMYA','[email protected]',1234567890),

('KAVYA','[email protected]',1234567899),

('SRAVYA','[email protected]',1234567898),

('RIYA','[email protected]',1234567896),

('SATHYA','[email protected]',1234567897);
KEYS- PRIMARY KEY
CREATE TABLE EMPLOYEE(

EMP_ID INT AUTO_INCREMENT,

EMP_NAME VARCHAR(50),

EMP_MAIL VARCHAR(50),

EMP_PH BIGINT,

PRIMARY
KEY(EMP_ID,EMP_MAIL));

INSERT INTO EMPLOYEE (EMP_NAME,EMP_MAIL,EMP_PH)

VALUES('RAMYA','[email protected]',1234567890),

('KAVYA','[email protected]',1234567899),

('SRAVYA','[email protected]',1234567898),

('RIYA','[email protected]',1234567896),

('SATHYA','[email protected]',1234567897);
KEYS- PRIMARY KEY
CREATE TABLE EMPLOYEE(

EMP_ID INT,

EMP_NAME VARCHAR(50),

EMP_MAIL VARCHAR(50),

EMP_PH BIGINT);

INSERT INTO EMPLOYEE VALUES(1,'RAMYA','[email protected]',1234567890),

(2,'KAVYA','[email protected]',1234567899),

(3,'SRAVYA','[email protected]',1234567898),

(4,'RIYA','[email protected]',1234567896),

(5,'SATHYA','[email protected]',1234567897);

ALTER TABLE EMPLOYEE ADD PRIMARY KEY(EMP_ID);


KEYS- PRIMARY KEY

TO DELETE PRIMARY KEY

ALTER TABLE EMPLOYEE DROP PRIMARY KEY;


KEYS- FOREGIN KEY
The foreign key is used to link one or more than one table together. It is also known as the referencing
key. A foreign key matches the primary key field of another table. It means a foreign key field in one
table refers to the primary key field of the other table. It identifies each row of another table uniquely
that maintains the referential integrity in MySQL.
A foreign key makes it possible to create a parent-child relationship with the tables. In this relationship,
the parent table holds the initial column values, and column values of child table reference the parent
column values. MySQL allows us to define a foreign key constraint on the child table.

MySQL defines the foreign key in two ways:


Using CREATE TABLE Statement
Using ALTER TABLE Statement
KEYS- FOREGIN KEY

syntax:

[CONSTRAINT constraint_name]

FOREIGN KEY [foreign_key_name] (col_name, ...)

REFERENCES parent_tbl_name (col_name,...) ON

DELETE referenceOption

ON UPDATE referenceOption
KEYS- FOREGIN KEY
constraint_name: It specifies the name of the foreign key constraint. If we have not provided the
constraint name, MySQL generates its name automatically.
col_name: It is the names of the column that we are going to make foreign key.
parent_tbl_name: It specifies the name of a parent table followed by column names that
reference the foreign key columns.
Refrence_option: It is used to ensure how foreign key maintains referential integrity using ON
DELETE and ON UPDATE clause between parent and child table.
MySQL contains five different referential options, which are given below:
CASCADE: It is used when we delete or update any row from the parent table, the values of the
matching rows in the child table will be deleted or updated automatically.
SET NULL: It is used when we delete or update any row from the parent table, the values of the foreign
key columns in the child table are set to NULL.
KEYS- FOREGIN KEY

RESTRICT: It is used when we delete or update any row from the parent table that has a
matching row in the reference(child) table, MySQL does not allow to delete or update
rows in the parent table.

NO ACTION: It is similar to RESTRICT. But it has one difference that it checks


referential integrity after trying to modify the table.

SET DEFAULT: The MySQL parser recognizes this action. However, the InnoDB and
NDB tables both rejected this action.
KEYS- FOREGIN KEY
CREATE TABLE STUDENT(

S_ID INT PRIMARY KEY,

S_NAME VARCHAR(30),

DEPT char(7),

COURSE_ID INT

);

CREATE TABLE

COURSE( C_ID INT,

C_NAME VARCHAR(20),

Credit INT,

STD_ID INT

);
KEYS- FOREGIN KEY
ALTER TABLE COURSE ADD CONSTRAINT fk_ID

FOREIGN KEY ( STD_ID ) REFERENCES

STUDENT ( S_ID ) ON DELETE CASCADE

ON UPDATE CASCADE;

-- DESC STUDENT;

-- DESC COURSE;

SET
foreign_key_checks
= 1;

insert into STUDENT


values
(1,'ravi','cse',1001),

(
2
KEYS- FOREGIN KEY
select * from STUDENT;

insert into COURSE VALUES (1001,'JAVA',5,1),

(1002,'MATLAB',4,2),

(1003,'C',5,3),

(1005,'AUTOCAD',5,4),

(1006,'IOT',5,4),

(1003,'C',5,1);

SELECT * FROM COURSE;

DELETE
FROM STUDENT WHERE
S_ID=3;

-- SELECT *
FROM COURSE;

UPDATE STUDENT SET S_ID=7 WHERE


KEYS- FOREGIN KEY

DROP FOREGIN KEY

ALTER TABLE table_name DROP FOREIGN KEY fk_constraint_name;

SHOW CREATE TABLE contact;

ALTER TABLE contact DROP FOREIGN KEY fk_customer;


KEYS- FOREGIN KEY-AT RUN TIME
CREATE TABLE Person (
ID INT NOT NULL AUTO_INCREMENT, Name varchar(50) NOT NULL, City
varchar(50) NOT NULL, PRIMARY KEY (ID) );
CREATE TABLE Contact (
ID INT, Person_Id INT, Info varchar(50) NOT NULL, Type varchar(50) NOT
NULL
);
ALTER TABLE Contact ADD CONSTRAINT fk_person
FOREIGN KEY ( Person_Id ) REFERENCES Person ( ID ) ON DELETE CASCADE ON
UPDATE RESTRICT;
KEYS- FOREGIN KEY-AT RUN TIME
CREATE TABLE STUDENT( S_ID INT PRIMARY KEY,S_NAME VARCHAR(30), DEPT CHAR(4), C_ID
INT);

CREATE TABLE COURSE( C_ID INT PRIMARY KEY, C_NAME VARCHAR(20), Credit INT, STD_ID INT);
ALTER TABLE COURSE ADD CONSTRAINT fk_ID

FOREIGN KEY ( STD_ID ) REFERENCES


STUDENT ( S_ID ) ON DELETE CASCADE
ON UPDATE RESTRICT;
DESC STUDENT;
DESC COURSE;
KEYS- COMPOSITE KEY

A composite key in MySQL is a combination of two or more than two columns in a table that
allows us to identify each row of the table uniquely. It is a type of candidate key which is
formed by more than one column.
Any key such as primary key, super key, or candidate key can be called composite key when they
have combined with more than one attribute. A composite key is useful when the table needs to
identify each record with more than one attribute uniquely. A column used in the composite key
can have different data types. Thus, it is not required to be the same data type for the columns to
make a composite key in MySQL.
A composite key can be added in two ways:
Using CREATE Statement
Using ALTER Statement
KEYS- COMPOSITE KEY

CREATE TABLE Product (

Prod_ID int NOT NULL,

Name varchar(45),

Manufacturer varchar(45),

PRIMARY KEY(Name,
Manufacturer)

);

– composite primary with the


column names Name and
Manufacturer.
KEYS- COMPOSITE KEY

INSERT INTO Product (Prod_ID, Name, Manufacturer)


VALUES (101, 'Soap', 'Hamam'),
(102, 'Shampoo', 'Teresme'),
(103, 'Oil', 'Daber Almond');
SELECT * FROM Product;
INSERT INTO Product (Prod_ID, Name, Manufacturer)
VALUES (101, 'Soap', 'Hamam');
INSERT INTO Product (Prod_ID, Name, Manufacturer)
VALUES (101, 'Soap', 'LUX');
MYSQL GRANT PRIVILEGES

The grant statement enables system administrators to assign privileges and roles to the
MySQL user accounts so that they can use the assigned permission on the database
whenever required.

Syntax:

GRANT privilege_name(s)

ON object

TO user_account_name;
MYSQL GRANT PRIVILEGES

Parameter Name Descriptions

privilege_name(s)It specifies the access rights or grant privilege to user accounts. If we


want to give multiple privileges, then use a comma operator to separate them.

object It determines the privilege level on which the access rights are being granted.
It means granting privilege to the table; then the object should be the name of the
table.

user_account_name It determines the account name of the user to whom the access
rights would be granted.
MYSQL GRANT PRIVILEGES

Global GRANT ALL ON *.*TO bytexl@localhost;

It applies to all databases on MySQL server. We need to use *.* syntax for applying
global privileges. Here, the user can query data from all databases and tables of the
current server.

Database GRANT ALL ON mydb.*TO bytexl@localhost;

It applies to all objects in the current database. We need to use the db_name.* syntax for
applying this privilege. Here, a user can query data from all tables in the given database.
MYSQL GRANT PRIVILEGES

TableGRANT DELETE ON mydb.employees TO bytexl@localhsot;

It applies n all columns in a specified table. We need to use db_name.table_name syntax


for assigning this privilege. Here, a user can query data from the given table of the
specified database.

You might also like