DBMS Day1 1
DBMS Day1 1
DBMS Day1 1
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
ID NAME AGE
1001 ABHI 23
1002 ARYAN 25
Field: Row / Record
Entity: Column
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.
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.
Eid Phne_no
Employee
Ename Age
b. Composite Key : An Attribute composed of many other attributes is known as a
composite attribute.
Ename
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:
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
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:
select @NAME;
EXAMPLE 2:
empId name dept
1 Clark Sales
2 Dave Accounting
3 Ava Sales
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:
System variables:
MYSQL>show variables;
—--------------------***--------------------
To disconnect the opened MySQL database server, you need to use the exit
command.
mysql> EXIT;
DATABASE CREATION
DATABASE CREATION:
We can review the newly created database using the below query that returns the
database name, character set, and collation of the database:
mysql>USE database_name;
—--------------------------------
show/list Database
mysql>SHOW DATABASE;
DROP DATABASE
OR
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.
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.
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
date_of_birth DATETIME
);
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
DESC EMPLOYEE;
ALTER TABLES
–CHANGING TABLE NAME
desc EMP;
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 (
DESC EMPLOYEE;
TABLE EMPLOYEE (
);
DESC EMPLOYEE;
—---
COPY/CLONE/DUPLICATE A TABLE
CREATE TABLE EMPLOYEE (
);
CREATE TABLE EMP SELECT dept,name FROM EMPLOYEE where dept='sales'; select
* FROM EMPLOYEE;
CREATE TABLE EMP SELECT dept,name FROM EMPLOYEE where dept='sales'; select
* FROM EMPLOYEE;
LIKE EMPLOYEE;
LIKE source_db.existing_table_name;
FROM source_db.existing_table_name;
SHOW COLUMNS
SYNTAX: SHOW [EXTENDED] [FULL] {COLUMNS | FIELDS}
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}
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
OR,
–FROM PRESENT DB
);
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 (
);
);
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
( Id INT NOT NULL, INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales');
Message VARCHAR(80) NOT NULL, INSERT INTO EMPLOYEE VALUES (0002, 'Clark', 'Sales');
primary key(id)
);
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.
example:
—AND—
example:
UPDATE EMPLOYEE SET name='SRAVYA' where (dept ='Sales' AND empId > 4);
DELETE TABLE
– single row
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
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
(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
- AND OR –
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
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
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 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 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
empId INTEGER ,
e_salary int,
DOB date
);
studentid INT,
age VARCHAR(3),
pass BOOLEAN
);
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');
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');
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
INSERT INTO EMPLOYEE VALUES (0001, 'Clark', SELECT name, IF(e_salary > 23000,
'Sales',23000,'1892-01-11'); "good","still_good")
EX 5:SELECT
NAME
FROM EMPLOYEE;
EX 6:
SELECT NAME,
IFNULL(empId,dept) new_name
FROM EMPLOYEE;
CONTROL FLOW-NULLIF
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
CASE class
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
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,
e_salary int,
DOB date,
no_hours int);
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()
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()
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()
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
FROM table_name(s)
[WHERE conditions];
.
Aggregate Functions- MAX()
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
FROM table_name
LIMIT 1;
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 (
name TEXT ,
dept TEXT ,
branch text,
w_hours int);
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;
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
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');
(1002,'RAVALI',35000),
(1003,'SATHYA',52000),
(1004,'MANASI',32000);
ON
EMPLOYEE.empId=EMP.I
d;
LEFT OUTER JOIN
CREATE TABLE TABLEA(
unique key:A column cannot stores duplicate values.It can accept a null value, but
MySQL allowed only one null value per column.
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
CREATE TABLE
... );
(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_NAME VARCHAR(50),
EMP_MAIL VARCHAR(50),
);
(2,'KAVYA','[email protected]',1234567899),
(3,'SRAVYA','[email protected]',1234567898),
(4,'RIYA','[email protected]',1234567896),
(5,'SATHYA','[email protected]',1234567897);
KEYS- UNIQUE KEY
datatype, …)
(OR)
( col1 col_definition,
[constraint_name]
);
KEYS- PRIMARY KEY
CREATE TABLE EMPLOYEE(
EMP_NAME VARCHAR(50),
EMP_MAIL VARCHAR(50),
EMP_PH BIGINT);
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_NAME VARCHAR(50),
EMP_MAIL VARCHAR(50),
EMP_PH BIGINT,
PRIMARY
KEY(EMP_ID,EMP_MAIL));
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);
(2,'KAVYA','[email protected]',1234567899),
(3,'SRAVYA','[email protected]',1234567898),
(4,'RIYA','[email protected]',1234567896),
(5,'SATHYA','[email protected]',1234567897);
syntax:
[CONSTRAINT constraint_name]
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.
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_NAME VARCHAR(30),
DEPT char(7),
COURSE_ID INT
);
CREATE TABLE
C_NAME VARCHAR(20),
Credit INT,
STD_ID INT
);
KEYS- FOREGIN KEY
ALTER TABLE COURSE ADD CONSTRAINT fk_ID
ON UPDATE CASCADE;
-- DESC STUDENT;
-- DESC COURSE;
SET
foreign_key_checks
= 1;
(
2
KEYS- FOREGIN KEY
select * from STUDENT;
(1002,'MATLAB',4,2),
(1003,'C',5,3),
(1005,'AUTOCAD',5,4),
(1006,'IOT',5,4),
(1003,'C',5,1);
DELETE
FROM STUDENT WHERE
S_ID=3;
-- SELECT *
FROM COURSE;
CREATE TABLE COURSE( C_ID INT PRIMARY KEY, C_NAME VARCHAR(20), Credit INT, STD_ID INT);
ALTER TABLE COURSE ADD CONSTRAINT fk_ID
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
Name varchar(45),
Manufacturer varchar(45),
PRIMARY KEY(Name,
Manufacturer)
);
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
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
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.
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