DBMS TUTORIALS
1) Installation of Mysql Software:
a) Type Mysql download in google – Click on first link.
b) Click on MySQL Community Downloads.
c) After clicking on MYSQL Community downloads. The below page
is found where MSSQL Installer for Windows should be selected.
d) After Selecting the MYSQL installer for Windows, select the
download option in the below figure
e) After downloading in the below figure select the custom
f) After Custom is selected, MYSQL Server, MYSQL Workbench and
MYSQL Shell has to be selected.
g) After this all the components are downloaded and installed. Next
the strong password has to be given to MYSQL.
h) After that select Next options and finally select execute option to
install MYSQL Successfully.
i) Next go to the path given in the below figure and copy the given
path
j) After copying the path search for system variables and follow the
below images for next steps:
Click here
Click on the path
and select edit option
Paste the link
and select OK
h) Finally go the command prompt and write the command
mysql -u root -p to connect to the MYSQL.
2) Installing ssms:
Downloading and exploring another database – download SQL
server by clicking on the first link.
Select express edition in the and download it
Select basic version in the express edition and install.
Click on connect now and below screen will appear
Click on install ssms and ssms is installed successfully
Commands executing on MYSQL
1) Command for logging into MySQL Using CMD:
MySQL -u root -p
2) Command to show the current databases in the MySQL
show databases;
3) Command to create a database if it doesn’t exist
CREATE DATABASE IF NOT EXISTS database_name;
4) Command for creating database
CREATE DATABASE college;
5) Command to use the database
Use college;
6) Write a Query to create a simple table in the database
create table student (
student_id int,
Last_name varchar(255),
First_name varchar(255)
Address varchar (255),
Country varchar(255));
7) Write a query to show all the tables in the database
show tables from database_name;
8) Write a query for describing any table present in the database
desc table_name ;
9) Write a query to insert the values in the table.
insert into student values(1,’guptha’,’swathi’,’Mysore’,’India’);
10) Write a query to insert more than one values at once.
insert into student
values(1,’guptha’,’swathi’,’Mysore’,’India’),(2,’guptha’,’sushma’,’Mysore’,’Ind
ia’);
11) Write a query to select all the values from the table student
select * from student;
12) Write a query to select only a particular column from the table student
select student_id from student;
select Country from student;
13) Write a query to select top 2 rows from the table student
select * from student limit 2;
14) Write a query to select a column country from the table student including only
first 2 rows.
select country from student limit 2;
15) Write a query to create the table employee
create table employee (
ID int,
Last_name varchar(255),
First_name varchar(255),
Address varchar(255));
16) Write a query to create the table employees with emp_no as primary key
and emp_name
create table employees(
emp_no int not null,
emp_name varchar(25),
PRIMARY KEY(emp_no));
17) Write a query to create a table dept_manager with emp_no as foreign
key which references the employees table, from_date and to_date.
CREATE TABLE dept_manager (
emp_no INT NOT NULL,
from_date DATE NOT NULL,
to_date DATE NOT NULL,
FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE
CASCADE,
PRIMARY KEY (emp_no));
18) Write a query to delete all the rows in the table
truncate table student;
19) Write a Query to delete the table if it exists
Drop table if exists table_name;
20) Write a Query to delete the database if it exists
DROP DATABASE IF EXISTS database_name;
DDL Commands
1) Create – CREATE DATABASE college;
create table student (
student_id int,
Last_name varchar (255),
First_name varchar(255)
Address varchar (255),
Country varchar(255));
2) Drop –
DROP DATABASE college;
DROP TABLE student;
3) Truncate –
TRUNCATE table student;
4) ALTER -
ALTER TABLE students
ADD student_dob date;
ALTER TABLE students
DROP COLUMN student_dob;
ALTER TABLE students
RENAME COLUMN student_lastname to std_lastname;
ALTER TABLE students
MODIFY COLUMN std_lastname char (60);
ALTER TABLE employees
ADD PRIMARY KEY (emp_no);
ALTER TABLE dept_manager
ADD FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON
DELETE CASCADE;
ALTER TABLE dup_students
DROP foreign key dup_students_fk; // dup_students_fk is the name
given to the foreign key
ALTER TABLE employees
DROP primary key;
DML Commands:
1) Insert – Insert into student values (1, ‘abc’,’xyz’,’mysore’,’India’);
2) Update –
→ UPDATE student
SET last_name ='efg', First_name='hij'
WHERE student_id = 1;
→UPDATE student
SET last_name = ‘efg’;
3) Delete
Delete from student
Where student_id = 1;
DQL Commands
1) Select
select * from student;
DCL Commands:
//Command to create a user:
Create user ‘sandhya’@’localhost’ identified by ‘sandhya’;
// To switch from default root user to different user created(sandhya) then
use the below command:
system mysql -u sandhya -p
//To check the current user in mysql:
Select user();
// To get the list of all the users in mysql
Select user from mysql.user;
// To drop the created user:
drop user 'sandhya1'@'localhost';
GRANT:
// To grant all permissions on all the tables of all the databases:
grant select on *.* to 'sandhya'@'localhost';
// To grant permission to specific database and to specifc table:
grant select on employees.departments to ‘sandhya’@’localhost’;
grant insert on employees.departments to 'sandhya'@'localhost';
// granting a permissions for particular column in the particular table of the
database
grant update(emp_no), select(emp_no) on employees.employees to
'sandhya'@'localhost';
// granting permission to particular table in the database
grant delete on employees.departments to 'sandhya'@'localhost';
grant drop on employees.departments to 'sandhya'@'localhost';
grant alter on employees.departments to 'sandhya'@'localhost';
grant delete,drop on employees.departments to 'sandhya'@'localhost';
// To view the given grants
show grants for 'sandhya'@'localhost';
// granting all permissions on all databases
grant all privileges on *.* to 'sandhya'@'localhost' with grant option;
REVOKE:
revoke update(emp_no) on employees.employees from
'sandhya'@'localhost';
revoke insert on employees.departments from 'sandhya'@'localhost';
revoke all privileges on *.* from 'sandhya'@'localhost';
TCL Commands:
Here we come across three main commands i.e., Commit, Rollback and
Savepoint.
Start Transaction – To turn off the auto correct feature.
Use database_name; // to select the particular database
Use mca; //here mca database is selected
1) Insert into person values (1,’abc’),(2,’efg’),(3,’hij’),(4,’uvw’),(5,’xyz’);
2) Delete from person
Where p_id = 1;
3) Update person
SET p_id = 1
Where p_id = 2;
Rollback; // This is basically used to rollback the transaction meaning the insertion,
deletion and updation operations which are done to a person
table will be taken back and the table will come back to its
previous condition
Commit; // After the commit is used, the insertion, updation and delete
transactions cannot be taken back, once the commit is used, The insert,
update and delete transactions are stored in the mysql database will be
stored in the mysql server and once the commit option is used, After this
rollback cannot be used.
Savepoint is created to basically rollback to a particular transaction.
Savepoint savepoint_name;
Savepoint init;
Savepoint ins;
Insert into person values (4,’abc’),(5,’efg’),(6,’hij’),(7,’uvw’),(8,’xyz’);
Savepoint del;
Delete from person
Where p_id = 1;
Savepoint upd;
Update person
SET p_id = 1
Where p_id = 2;
Here for each and every transaction there is a savepoint created, that is ins
savepoint
is used for insert operation, savepoint del is used for delete transaction and
savepoint
upd is created for update operation.
For example if I have to rollback the update transaction, I have to use the
command:
Rollback to del; // So that all the transactions after the deletion is taken
back successfully by using the above command.
WHERE CLAUSE:
1) Write all the queries with all the possibilities of where clause:
use asection; //creating the database
CREATE TABLE students (
student_id int primary key AUTO_INCREMENT,
student_lastname varchar (255) NOT NULL,
student_firstname varchar(255)
); // creating a table students
Insert into students (student_lastname,student_firstname) values ('abc','xyz');
//insert values
select * from students;
select * from students
where student_id in(2,3,4,5,6); // this query gives the information
about only the student id’s 2,3,4,5,6
select * from students
where student_id = 2 and student_lastname = 'abc'; //gives the info about
students
whose id is 2 and lastname is abc
select * from students
where student_id = 2 or student_lastname = 'abc'; //gives the
info about all the students whose id is 2 or lastname is abc
select * from students
where student_id > 4; // gives the info about students whose id is greater than
4
select * from students
where student_id <= 4; // gives the info about students whose id is less or
equal to 4
select * from students
where student_id <> 4; // gives the info about the students whose id is not
equal to 4
select * from students
where student_id between 2 and 12; // gives the info about the
students whose id is in the range between 2 and 12
delete from students where student_id = 1; // delete the particular
student record where student_id = 1
Like operator:
1) Write the query with all the possibilities of like operator:
SELECT std_lastname
FROM students
WHERE std_lastname LIKE 'xyz';
CREATE Table dup_students
Like students;
select * from students
where std_lastname like 'a%';
select * from students
where std_lastname like '%a';
select * from students
where std_lastname like '%a%';
select * from students
where std_lastname like '_a%';
select * from students
where std_lastname like 'a_%';
select * from students
where std_lastname like 'a__%';
select * from students
where std_lastname like 'a%c';
Composite Primary keys:
CREATE TABLE branch_supplier (
branch_id INT,
supplier_name VARCHAR(40),
supply_type VARCHAR(40),
PRIMARY KEY(branch_id, supplier_name)
);
insert into branch_supplier (branch_id, supplier_name, supply_type) values
(1,'abc','xyz');
select * from branch_supplier;
DEFAULT:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
Insert into Persons (ID, LastName, FirstName,Age) values(1,’efg’,’abc’,’20);
ALIAS AS:
SELECT ID AS Persons_ID
FROM Persons;
UNIQUE KEY:
create table person(
ID int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
UNIQUE(ID));
insert into person values(NULL,'abc','efj');
select * from person;
// creating a table by creating a table with foreign key which references the
unique key column
create table person1(
P_id int,
p_name varchar(25),
FOREIGN KEY (P_id) REFERENCES person (ID));
insert into person1 values(null,'xyz');
create table personss2(
ID int,
person_ssn int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
UNIQUE(ID),
UNIQUE(person_ssn));
insert into personss2 values(2,1002,'abc','efj');
create table personss1(
ID int,
person_ssn int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
UNIQUE(ID,person_ssn));
insert into personss2 values(2,1002,'abc','efj');
insert into personss2 values(1,1002,'abc','efj');
Creating the tables with multiple unique keys:
create table personss2(
ID int,
person_ssn int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
UNIQUE(ID) ,
UNIQUE(person_ssn)); /* creating a table with multiple unique keys */
insert into personss2 values(2,1002,'abc','efj');
Important Queries for searching particular columns, tables stored in different
databases:
select * from information_schema.tables
where table_name like '%cust%';
select * from information_schema.tables
where table_name = 'customers';
select * from information_schema.columns
where column_name = 'ID';
Queries Using different Types of Attributes and Datatypes
Derived Attributes Examples:
create table sales(
customer_id int,
product_id int,
quantity_bought int,
cost_per_unit int,
total_cost int as ( quantity_bought * cost_per_unit));
insert into sales (customer_id, product_id, quantity_bought, cost_per_unit)
values(1,2,3,25);
select * from sales;
create table emp_info(
emp_no int,
dob date);
insert into emp_info values (1, '2019-10-01');
select * , timestampdiff(year, dob , curdate()) AS age
from emp_info;
create table emp_info(
emp_no int,
dob date);
insert into emp_info values (1, '2019-10-25');
select * from emp_info;
select * , timestampdiff(day, dob , curdate()) AS age
from emp_info; /* creating a derived attribute age*/
CREATE TABLE memberships (
id INT,
email VARCHAR(355) NOT NULL,
plan VARCHAR(255) NOT NULL,
expired_date DATE NOT NULL,
remaining_days int as (timestampdiff(DAY,'2017-07-01', expired_date))
); /* using timestamp */
INSERT INTO memberships(email, plan, expired_date)
VALUES('
[email protected]','Gold','2017-07-13'),
('
[email protected]','Platinum','2017-07-10'),
('
[email protected]','Silver','2017-07-15'),
('
[email protected]','Gold','2017-07-20'),
('
[email protected]','Silver','2017-07-08'); /* inserting values to
memberships table */
select * from memberships;
CAST :
CREATE TABLE castTest(
firstName CHAR(20),
lastName CHAR(20)
);
INSERT INTO castTest(firstName, lastName)
VALUES('Smith', CAST('2020-02-02' AS DATETIME)); /* using cast to change the
datatype of a column during insertion of values */
INSERT INTO castTest(firstName, lastName)
VALUES('Smith','john');
select * from castTest;
UPDATE castTest
SET lastname = CAST('2021-03-03' AS DATETIME)
WHERE lastname = 'john'; /* using cast during the update statement */
Decimal Datatype:
create table money(
salary decimal (5,2)
); /* using decimal datatype */
insert into money values(100.00);
select * from money;
BLOB, LONGBLOB AND MEDIUM BLOB :
create table image_table1(
img_id int,
image blob); /* storing images in the database using blob datatype */
insert into image_table1 (img_id,image)
values(1,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL Server
8.0\\Uploads\\scenary.jpg'));
insert into image_table1 (img_id,image)
values(2,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL Server
8.0\\Uploads\\scenary1.jpg'));
select * from image_table1;
create table image_table2(
img_id int,
image longblob); /*storing videos and large size images using blob */
insert into image_table2 (img_id,image)
values(2,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL Server
8.0\\Uploads\\scenary1.jpg'));
insert into image_table2
values(2,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL Server
8.0\\Uploads\\video.mp4'));
select * from image_table2;
create table doc_table(
doc_id int,
document blob); /* storing documents in using blob datatype */
insert into doc_table values(2,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL
Server 8.0\\Uploads\\document.docx'));
insert into doc_table values(2,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL
Server 8.0\\Uploads\\document.pdf'));
create table image_table3(
img_id int,
image mediumblob);
insert into image_table3
values(2,LOAD_FILE('C:\\ProgramData\\MySQL\\MySQL Server
8.0\\Uploads\\image.jpg'));
select * from image_table3;
CHECK CONSTRAINT:
CREATE TABLE Person1 (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)); /* using check constraint */
insert into person1 values(1,'gupta','swathi',17);
select * from person1;
Views
create view students_view AS
select student_id , student_firstname
from students;
/* creating the view student_view */
Select * from students_view;
/* executing the view */
Date and Time Functions:
CREATE TABLE test_timestamp (
t1 timestamp
); /* creating a table with datatype timestamp */
INSERT INTO test_timestamp(t1) VALUES('2008-01-01 00:00:01'); /*
inserting values to timestamp table */
SELECT '2020-01-01' + INTERVAL 1 DAY; /* using intreval */
SELECT DATE_ADD('2020-01-01', INTERVAL 1 MONTH); /* using
intreval */
SELECT DATE_SUB('2020-01-01',INTERVAL 1 MONTH) AS
1_MONTH_BEFORE; /* usimg intreval */
SELECT '2020-01-01' + INTERVAL 1 year;
SELECT '2020-01-01' + INTERVAL 14 month;
Queries related to recursive relationships, different options that come with
foreign keys, join conditions and Union.
CREATE TABLE DEPARTMENT
(
Dnumber int,
CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
Dept_name VARCHAR(25) NOT NULL
);
insert into department values(1,'HR'),(2,'Finance'),(3,'recruitment');
INSERT INTO DEPARTMENT VALUES(4,'Sales'),(5,'production');
CREATE TABLE EMPLOYEE
(
Emp_no int,
Dno INT DEFAULT 1,
SSN varchar(9) primary key,
Super_ssn varchar(9),
CONSTRAINT EMPSUPERFK FOREIGN KEY (Super_ssn) REFERENCES
EMPLOYEE(Ssn) ON DELETE SET NULL,
CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno) REFERENCES
DEPARTMENT(Dnumber)ON DELETE SET NULL ON UPDATE CASCADE);
insert into employee values(101,1,'123456789', '123456789');
insert into employee values(102,2,'345678230', '123456789');
insert into employee values(103,3,'789023456', '345678230');
insert into employee values(104,4,'678923451', '666679999');
insert into employee values(105,6,'111111111', '123456789');
insert into employee values(105,7,'111111117', '123456789');
select * from department;
select * from employee;
Delete from employee
where Ssn = '345678230';
delete from department
where Dnumber = 1;
update department
set Dnumber = 6
where Dnumber = 5;
CREATE TABLE DEPARTMENT1
(
Dnumber int,
CONSTRAINT DEPTPK1 PRIMARY KEY(Dnumber),
Dept_name VARCHAR(25) NOT NULL
);
select * from employee1;
insert into department1 values(1,'HR'),(2,'Finance'),(3,'recruitment');
INSERT INTO DEPARTMENT1 VALUES(4,'Sales'),(5,'production');
select * from department1;
CREATE TABLE EMPLOYEE1
(
Emp_no int,
Dno INT DEFAULT 1,
SSN varchar(9) primary key,
Super_ssn varchar(9),
CONSTRAINT EMPDEPTFK1 FOREIGN KEY(Dno) REFERENCES
DEPARTMENT1(Dnumber) ON DELETE RESTRICT );
select * from employee1;
insert into employee1 values(101,1,'123456789', '123456789');
insert into employee1 values(102,2,'345678230', '123456789');
insert into employee1 values(103,3,'789023456', '345678230');
insert into employee1 values(105,5,'111111111', '123456789');
insert into employee1 values(106,5,'111111100', '111111111');
delete from department1
where Dnumber = 1;
create table employee2(
fname varchar(20),
lname varchar(20),
Address varchar(50),
Dno int);
insert into employee2 values('swathi','Guptha','Mysore',1);
insert into employee2 values('swathi','Guptha','Mysore',2);
insert into employee2 values('Anand','Guptha','Mysore',1);
insert into employee2 values('Anand','Guptha','Mysore',1);
create table department2(
Dnumber int,
Dname varchar(25));
insert into department2 values(1,'Research');
insert into department2 values (2, 'Finance');
SELECT * FROM department2;
SELECT * FROM employee2;
/* Retrieve all the infomormation of all employees who work for the
‘Research’ department */
SELECT *
FROM employee2,department2
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and Dname = 'Research';
/* Retrieve the name and address of all employees who work for the ‘Research’
department */
SELECT fname,lname,address
FROM employee2,department2
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and Dname = 'Research';
create table emp_dept as
SELECT fname,lname,address
FROM employee2,department2
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and Dname = 'Research';
select * from emp_dept;
select fname,lname,address
from employee2,department2;
create table project(
Dept_no int,
Project_no int);
insert into project values(1, 1001);
insert into project values(2, 1002);
select * from project;
SELECT fname,lname,address,project_no
FROM employee2,department2,project
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and project.Dnumber =
department2.Dnumber and Dname = 'Research';
select employee2.fname,employee2.lname,project.project_no
from employee2,department2,project
WHERE DEPARTMENT2.Dnumber = EMPLOYEE2.Dno and project.Dnumber =
department2.Dnumber and Dname = 'Research';
SELECT *
FROM employee2 as e, department2 as d
WHERE e.Dno = d.Dnumber and Dname = 'Research';
select *
from employee2,department2;
SELECT employee.Dno, department.Dept_name
FROM employee ,DEPARTMENT
where department.Dept_name = employee.Dno;
select distinct Dno
from employee;
select * from employee2;
create table emp_hr(
emp_id int,
location varchar(20));
alter table emp_hr
add emp_name varchar(25);
insert into emp_hr values(1001,'Mysore');
insert into emp_hr values(1002,'Mysore');
create table emp_finance(
emp_id int,
location char(20));
insert into emp_finance values(1001,'Bangalore');
insert into emp_finance values(1002,'Bangalore');
create table emp_research(
emp_id int,
location char(20));
insert into emp_research values(1001,' Mysore');
insert into emp_research values(1003,' Tumkur');
select distinct emp_hr.location, emp_hr.emp_id
from emp_hr , emp_finance
where emp_hr.emp_id = emp_finance.emp_id
UNION
select distinct emp_research.location,emp_research.emp_id
from emp_finance , emp_research
where emp_research.emp_id = emp_finance.emp_id;
select * from emp_hr
union
select * from emp_finance;
( SELECT DISTINCT Dname
FROM DEPARTMENT2, EMPLOYEE2
WHERE employee2.Dno = department2.Dnumber AND employee2.lname =
'Guptha' )
UNION
(SELECT DISTINCT Dno
FROM employee2, project
WHERE employee2.Dno = project.Dnumber AND employee2.lname = 'Guptha'
);
alter table department2
modify column Dnumber varchar(25);
SELECT *
FROM employee2, department2
where employee2.Dno = department2.Dnumber
order by employee2.fname;
SELECT *
FROM employee2, department2
where employee2.Dno = department2.Dnumber
order by employee2.fname DESC;
create table customers1(
Customername varchar(20),
City varchar(20),
Country varchar(20),
cust_id varchar(20));
select * from customers1;
create table Suppliers(
supplierName varchar(20),
City varchar(20),
County varchar(20));
insert into suppliers values ('abc','mysore','india');
select * from suppliers;
insert into customers1(Customername,city,Country)
(select Suppliername, city, country from suppliers
where county = 'germany');
INSERT INTO Customers1
(SELECT SupplierName, City, County,cust_id FROM Suppliers
WHERE County='india');
INSERT INTO Customers1
(SELECT SupplierName, City, County,cust_id FROM Suppliers
WHERE County='india');
alter table suppliers
add cust_id int;
update suppliers
set cust_id = 1
where suppliername = 'abc';
update department
set Dept_name = 'research'
where Dnumber = 2;
select * from department;
select * from employee2;
select Dno, from Employee2
Union
select Dnumber from department; // In the union Same number of columns
have to be taken from both the tables.
Joins In SQL
create table emp(
emp_id int,
emp_name varchar(40),
address varchar(40),
ssn char(9),
mgr_ssn char(9),
Dno int);
insert into emp values(1001,'abc','mysore','123456789','123456789',1);
insert into emp values(1002,'efg','bangalore','123456788','123456789',1);
insert into emp values(1003,'hij','tumkur','123456780','123456780',2);
insert into emp values(1003,'klm','tumkur','123456787','123456780',2);
insert into emp values(1004,'nop','tumkur','126789450','345673459',3);
create table dept(
dnumber int,
dname varchar(40));
insert into dept values(1,'Research');
insert into dept values(2,'HR');
insert into dept values(4,'Sales');
create table dept1(
dnumber int,
dname varchar(40));
insert into dept1 values(1,'Research');
insert into dept1 values(2,'HR');
insert into dept1 values(4,'Sales');
create table emp1(
emp_id int,
emp_name varchar(40),
address varchar(40),
ssn char(9),
mgr_ssn char(9),
dnumber int);
drop table emp1;
insert into emp1 values(1001,'abc','mysore','123456789','123456789',1);
insert into emp1 values(1002,'efg','bangalore','123456788','123456789',1);
insert into emp1 values(1003,'hij','tumkur','123456780','123456780',2);
insert into emp1 values(1003,'klm','tumkur','123456787','123456780',2);
insert into emp1 values(1004,'nop','tumkur','126789450','345673459',3);
/* find the employee names who is working in a department */
select e.emp_name , e.dno from emp e
join dept d on d.dnumber = e.dno;
select e.emp_name , e.dno from emp e
inner join dept d on d.dnumber = e.dno;
/* find the employee names who are not working in the prescribed department
mentioned in the department table */
select e.emp_name , e.dno from emp e
left join dept d on d.dnumber = e.dno;
/* find the number of employees who are not working in the departments
specified in the departments table */
select d.dname , count(e.emp_id) as count_of_emp
from emp e
left join dept d on d.dnumber = e.dno
group by d.dname;
/* find the count of the employees from each department */
select d.dname , count(e.emp_id) as count_of_emp
from emp e
right join dept d on d.dnumber = e.dno
group by d.dname;
/*natural join */
select * from dept1
natural join emp1;
select * from dept1
inner join emp1 on emp1.dnumber = dept1.dnumber
Having clause: Having clause is used to in place with where clause when the
aggregate functions with group by clause are used.
HAVING WHERE
1. The HAVING clause is used in database 1. The WHERE clause is used in database
systems to fetch the data/values from the systems to fetch the data/values from the
groups according to the given condition. tables according to the given condition.
2. The HAVING clause is always executed 2. The WHERE clause can be executed
with the GROUP BY clause. without the GROUP BY clause.
SELECT COUNT(dept_no), dept_name
FROM departments
GROUP BY dept_name
HAVING COUNT(dept_no) = 1;
Joins
Inner Join: The inner join is used to select all matching rows or
columns in both tables or as long as the defined condition is valid in
SQL.
Left Join: The LEFT JOIN is used to retrieve all records from the left table
(table1) and the matched rows or columns from the right table (table2). If both
tables do not contain any matched rows or columns, it returns the NULL.
Right Join: The RIGHT JOIN is used to retrieve all records from the right table
(table2) and the matched rows or columns from the left table (table1). If both
tables do not contain any matched rows or columns, it returns the NULL.
Full outer Join or Full Join: Full outer join is a type of SQL join that
combines two tables and returns all the rows from both tables, regardless of
whether they have matching values or not.
Natural Join - Natural Join joins two tables based on same attribute name
and datatypes.
Cross Join - A cross join is a type of join operation in SQL that combines every
row from one table with every row from another table.
Join Example Queries:
/* find the employee names who is working in a department */
select e.emp_name , e.dno from emp e
join dept d on d.dnumber = e.dno;
[OR]
select e.emp_name , e.dno from emp e
inner join dept d on d.dnumber = e.dno;
/* Write a query to get all the employees who are both working and not working
in the department prescribed in the department table.*/
select e.emp_name , e.dno from emp e
left join dept d on d.dnumber = e.dno;
/* Write a query to get all the employees who are both working and not working
in the department prescribed in the department table.*/
select d.dname , count(e.emp_id) as count_of_emp
from emp e
left join dept d on d.dnumber = e.dno
group by d.dname;
/* find the count of the employees from all the departments */
select d.dname , count(e.emp_id) as count_of_emp
from emp e
right join dept d on d.dnumber = e.dno
group by d.dname;
/* Query to demonstrate full outer join */
select * from dept
full join emp on emp.Dno = dept.dnumber;
[OR]
select * from dept
full join emp on emp.Dno = dept.dnumber;
/* Query to demonstrate Cross Join */
select emp_name, dname
from emp
cross join dept;
/*Query to demonstrate Union */
( SELECT DISTINCT Dname
FROM DEPARTMENT2, EMPLOYEE2
WHERE employee2.Dno = department2.Dnumber AND employee2.lname =
'Guptha' )
UNION
(SELECT DISTINCT Dno
FROM employee2, project
WHERE employee2.Dno = project.Dnumber AND employee2.lname =
'Guptha');
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
String Functions:
SELECT CHARACTER_LENGTH(dname) AS dname_count FROM dept;
SELECT CHARACTER_LENGTH('DBMS IS A GOOD SUBJECT');
SELECT dname, CHARACTER_LENGTH(dname) AS dname_count FROM
dept;
SELECT dnumber, dname, CONCAT(dnumber," ", dname) as concat_two_fields
from dept;
SELECT UPPER("SQL Tutorial is FUN!");
CONCAT – WS → The CONCAT_WS () function adds two or more strings
together with a separator.
SELECT CONCAT_WS('.', ‘www’,‘nie', ‘ac', 'in');
Date and Time Functions:
CREATE TABLE test_timestamp (
t1 timestamp
); /* creating a table with datatype timestamp */
INSERT INTO test_timestamp(t1) VALUES('2008-01-01 00:00:01'); /* inserting
values to timestamp table */
SELECT '2020-01-01' + INTERVAL 1 DAY; /* usimg intreval */
SELECT '2020-01-01' + INTERVAL -1 DAY;
SELECT DATE_ADD('2020-01-01', INTERVAL 1 MONTH); /* usimg intreval */
SELECT DATE_SUB('2020-01-01',INTERVAL 1 MONTH) AS 1_MONTH_BEFORE; /*
usimg intreval */
SELECT '2020-01-01' + INTERVAL 1 year;
SELECT '2020-01-01' + INTERVAL 14 month ;
select curdate();
select TIMESTAMPADD(month,2,'2017-10-08');
SELECT TIMESTAMP("2017-07-23");
SELECT DAYOFYEAR("2017-06-15");
SELECT DAYNAME("2017-06-15");
SELECT DAYOFMONTH("2017-06-15");
Stored Procedures
A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
use Asection;
create procedure sp_dept
as
begin
select * from department
end
create procedure sp_update_dept
as
begin
update department
set Dnumber = 1
where Dnumber = 2
end
exec sp_alter_dept;
drop procedure sp_dept;
drop procedure sp_alter_dept;
create procedure sp_alter_dept
as
begin
alter table department
add mgr_name varchar(25)
end
exec sp_alter_dept;
alter table department
drop column mgr_name;
:
A Trigger in DBMS is a procedure that is automatically executed by the
database management systems in response to a specific event such as insert,
update or delete operation.
General syntax for triggers:
1. CREATE TRIGGER Trigger_Name
2. [ BEFORE | AFTER ] [ Insert | Update | Delete]
3. ON [Table_Name]
4. [ FOR EACH ROW | FOR EACH COLUMN ]
5. AS
6. Set of SQL Statement
Joins
1)
To join item name, item unit columns from foods table and company name,
company city columns from company table, with the following condition -
1.company_id of foods and company table must be same, the following SQL
statement can be used:
SELECT foods.item_name,foods.item_unit,
company.company_name,company.company_city
FROM foods
INNER JOIN company ON foods.company_id =company.company_id;
2) Write a query to filtered out those bill number, item name and the bill
amount for each bill which bill amount exceeds the value 500 and must be
available at the food stall, the following SQL statement can be used :
SELECT a.bill_no, b.item_name, a.bill_amt
FROM counter_sale a
LEFT JOIN foods b
ON a.item_id=b.item_id
WHERE a.bill_amt>500;
3) Write a SQL query to combine each row of the salesman table with each
row of the customer table.
SELECT *
FROM salesman a
CROSS JOIN customer b
WHERE a.city IS NOT NULL AND b.grade IS NOT NULL;
4) Right Join
SELECT Orders.OrderID, Employees.LastName,
Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID =
Employees.EmployeeID
ORDER BY Orders.OrderID;
Full Join:
Write a query which retrieves all rows in the employees table, even if there is
no match in the departments table. It also retrieves all rows in the departments
table, even if there is no match in the employees table.
Select * from employee
Full outer join departments;