0% found this document useful (0 votes)
65 views65 pages

Sahan 2k21bmba03

1. The SHOW DATABASES command displays all databases on the server. 2. The CREATE DATABASE command creates a new database with a specified name. 3. The DROP DATABASE command deletes an existing database by name. Once deleted, it will no longer appear in SHOW DATABASES output.

Uploaded by

Sahan Peiris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views65 pages

Sahan 2k21bmba03

1. The SHOW DATABASES command displays all databases on the server. 2. The CREATE DATABASE command creates a new database with a specified name. 3. The DROP DATABASE command deletes an existing database by name. Once deleted, it will no longer appear in SHOW DATABASES output.

Uploaded by

Sahan Peiris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

DELHI TECHNOLOGICAL UNIVERSITY

University School of Management and Entrepreneurship

MASTER OF BUSINESS ADMINISTRATION (BUSINESS ANALYTICS)

MB 109: DATA QUERY AND VISUALIZATION LAB


LAB REPORT

Submitted by

T. SAHAN U. PEIRIS (2K21/BMBA/03)

Submitted to

DR. GAGANMEET KAUR AWAL


(Assistant Professor: USME – Delhi Technological University)
MB 109: DATA QUERY AND VISUALIZATION LAB
LAB REPORT
TABLE OF CONTENTS

TOPIC PAGE NO

1.0 Introduction to MySQL 01

2.0 MySQL Basics 12

3.0 MySQL Databases 15

4.0 MySQL Table – Design 16

5.0 MySQL Tables – Retrieve Data 18

6.0 MySQL - Order of Execution 22

7.0 MySQL Tables – Update and Modification 23

8.0 MySQL Tables – Constraints 25

9.0 MySQL – Functions 28

10.0 MySQL – Joins 30

11.0 MySQL – Sub – Queries 32

12.0 MySQL – Procedures 33

13.0 MySQL – Case 35

14.0 MySQL – View 35

15.0 MySQL – Trigger 36

16.0 MySQL – INDEX 36

17.0 ASSIGNMENT 1 – STUDENT Table 37

18.0 ASSIGNMENT 2 – DATABASE ALPHA: PART 1 38

19.0 ASSIGNMENT 3 – DATABASE ALPHA: PART 2 50

20.0 ASSIGNMENT 4 – DATABASE EMPLOYEE 59


1.0 Introduction to MySQL

SQL – Structured Query Language


SQL or Structured Query Language is a Database Language that communicates with
Databases. It is generally known as SQL or Sequel.

SQL is used to create, modify and update Database Design and store, manipulate and retrieve
Data stored in Relational Databases.

SQL is the standard language for Relational Database Systems. All Relational Database
Systems such as MySQL, MS Access, Oracle, Sybase, Informix, PostgreSQL and SQL
Server use SQL as their Standard Database Language.

SQL – Timeline in Brief


Development of Relational Database Concept by E. Codd

1970

E. Codd

1974 - 1979 Creation of System R with Sequel (later SQL) at IBM Research Lab
1979 Market of First Relational Database with SQL by Oracle
RDBMS available on DOS / VSE

1981 SQL/DS, INGRES


1982 IDM
1984 DG / SGL
1986 Sybase
1986 Release of ANSI SQL Standard
1989
1992
1999 Major ANSI Standard Updates
2003
2007
Current Current Relational Database Giants: MySQL, Oracle, DB2 etc.

1
MySQL Workbench

Introduction

MySQL workbench is a graphics tool for working with MySQL Servers and Databases. It is
the Official Graphical User Interface (GUI) Tool for MySQL. It allows to design, create and
browse Database Schemas, work with Database Objects and insert data as well as design and
run SQL queries to work with stored data. It is also possible to migrate schemas and data
from other database vendors to MySQL Databases. MySQL Workbench is an Open – source
Relational Database Design Tool which allows to work with Databases in a structured way.

Salient Features of MySQL Workbench

1. Modeling and Design

2. SQL Develop Tool

3. Visual performance

4. Database Migration

5. Connection Management

6. Object Management

7. User Administration

8. Server Configuration

2
Installation of MySQL Workbench in Windows
1. Visit www.mysql.com
2. Go to Products and Click on MySQL Workbench
3. Click – Download Now
4. Select Your Operating System

5. Click – Go to Download Page

3
6. Chose your installer and click – Download

7. Open the downloaded installer.


8. Click – Yes for permission.
9. Choose – Custom as Set Up Type, Click – Next.

4
10. Expand MySQL Server, select the server of choice, pop it to the Products / Features
To Be Installed window.
Do the same thing for Applications, and Install MySQL Workbench. Click – Next.

11. Click – Execute to download and install MySQL Server and MySQL Workbench.

12. Once done, Click – Next.

5
13. Go to – Type and Networking. Go with default settings, Click – Next.

14. Set password for root user.

6
15. Click – Next, keep default settings for the next steps.

16. Click – Execute. Once all the configuration steps are complete, click Finish.

7
17. To complete the installation, Click Finish.

18. Once MySQL Workbench is installed, select the Local Instance and enter the
Password.

8
Features of MySQL Workbench
Start Screen

Start Screen is where the Local instance is selected and the Password is entered.

SQL Editor

SQL Editor is the space shown above, provided to create queries and to edit them.

9
Help Panel

Once enabled, the syntax and description for a particular keyword can be viewed in the Help
Panel.

Navigation Panel

Navigation Panel allows to manage active MySQL connections and also shows the schemas on
that server for a connection.

10
History and Output Window

History and Output Window displays a summary of the executed queries in the forms of Action
Output, Text Output or History Output.

11
2.0 MySQL Basics
Typing and Executing a Command
SQL commands / queries are typed in the text field of the SQL Editor. To run any command,
it should first be selected, followed by the pressing of yellow lightning button above the text
field. Otherwise, the shortcut keys CTRL + Enter can be used after selecting the command /
query to run.

SQL Comments
Two Types of comments can be written in MySQL.

They are,
Single – Line Comments
Multi – Line Comments

Comments cannot be run to get an output.

Single – Line Comments

Single – Line Comments begin with two dashes (--) in MySQL Workbench. Any text that is
written after the dashes till the end of the line will not be considered a command.

Multi – Line Comments

Multi – Line Comments begin with a /* and end with a */. Any text that is written between the
slashes and the asterisks will not be considered a command.

12
SQL Data Types

String Type
CHAR Fixed Character Length Data
1 to 225 Characters
VARCHAR Variable Character Length Data
1 to 2000 Characters
Numerical Type
INT Integer Values Only
Integers are (whole) counting numbers / No
decimals.
Date and Time Data Type
DATE Date Formats Only
Commonly accepted formats are ‘DD-
MON-YYYY’, ‘DD-MON-YY’,
‘MM/DD/YYYY’, ‘MM/DD/YY.’ Stores
dates in the Julian date format.

13
Database Languages

Database Languages allow users to control accessing data, defining and updating data and
searching for information within the database management system (DBMS).

A DBMS interacts with users, applications and the database to record and analyse data while
also manipulating the database to offer a way to store, access and retrieve data.

DDL: Data Definition Language


CREATE, DROP, TRUNCATE, ALTER, RENAME
DML: Data Manipulation Language
DELETE, SELECT, INSERT, UPDATE
DCL: Data Control Language
GRAN, REVOKE

14
3.0 MySQL Databases
1 Display Existing Databases
Command Syntax SHOW DATABASES;
Function Shows all the databases available on the server host.
2 Create a New Database
Command Syntax CREATE DATABASE <Database Name>;
Function Creates a new database with a given name on the server host.
Once created upon query for all the available databases the
Note newly created database can be displayed in the list of
databases.
3 Delete an Existing Database
Command Syntax DROP DATABASE <Database Name>;
Function Deletes a database with a given name on the server host.
Once deleted, upon query for all the available databases the
Note deleted database would not be visible in the list of databases
any longer.
4 Select a Database
Command Syntax USE DATABASE <Database Name>;
Selects a particular database to be used since creating a
Function
database does not select it by default to be used.
Until a particular database is selected with this command, no
operation (Ex: Creating a Table) can be brought forth on that
Note database.
Once selected, the database remains default until the end of
the operations or election of another database.

15
4.0 MySQL Table – Design
1 Display Existing Tables
Command Syntax SHOW TABLES;
Function Shows all the tables available in the selected database on
the server host.
2 Create a New Table
Command Syntax CREATE TABLE <Table Name> (
<Column Name 1> <Data Type>,
<Column Name 2> <Data Type>,
<Column Name 3> <Data Type>
);
Function Creates a new table with a given identifier (name) with
attributes defined (column name, data type etc.) on a
database on the server host.
Note Once created, upon query for all the available tables in the
database, the newly created table can be displayed.
3 Delete an Existing Table
Command Syntax DROP TABLE <Table Name>;
Function Deletes a table with a given name on a database on the
server host.
Note Once deleted, upon query for all the available tables on
database the deleted table would not be visible in the list of
tables any longer.
4 Display the Table Structure
Command Syntax DESCRIBE <Table Name>; or DESC <Table Name>;
Function Shows a Table’s structural information and set data types
for different attributes in detail.
5 Insert Information to a Table
Command Syntax INSERT INTO
VALUES (< Value 1 >, < Value 2 >, …);
OR
INSERT INTO <Table Name> (< Column 1 >, < Column 2 >,
…)
VALUES (< Value 1 >, < Value 2 >, …);
Function Inserts values to all the columns of a Table (1) or to certain
columns of a table (2).

16
6 Duplicating a Table with its Values to Create a New Table
Command Syntax CREATE TABLE <Table Name> AS SELECT <Column 1>,
<Column 2>, <Column 3> FROM <Existing Table Name>;
Function Creates a table with a new name and duplicated features
and values of an existing table.
7 Creating a Table Based on Another Table with Empty Shells
Command Syntax CREATE TABLE <Table Name> AS SELECT <Column 1>,
<Column 2>, <Column 3> FROM <Existing Table Name>
WHERE 0=1;
Function Creates a table with a new name with columns and data
types of an existing table.

17
5.0 MySQL Tables – Retrieve Data

1 Retrieve All Data in a Table

Command Syntax SELECT * FROM <Table Name>;

Function Retrieves data from all rows of a desired table.

2 Retrieve a Subset of Data from a Table: Selected Columns and All Rows

Command Syntax SELECT <Column1>, <Column2>, <Column3>, …


FROM <Table Name>;

Function Retrieves data in all the rows of specific columns.

Note Hereby the order of selection determines the order of


display.

3 Retrieve a Subset of Data from a Table: Selected Rows and All Columns

Command Syntax SELECT * FROM <Table Name>


WHERE <Condition>;

Function Retrieves data in all the columns of a specific row.

Note WHERE clause allows conditions to be followed.

4 Retrieve a Subset of Data from a Table: Selected Rows and Selected Columns

Command Syntax SELECT <Column1>, <Column2> FROM <Table Name>


WHERE <Condition>;

Function Retrieves data in specific rows of specific columns.

5 Retrieve Data from a Table in a Desired Manner: SQL Aliases

Command Syntax SELECT <Column 1> <Alias Name> FROM <Table Name>;
(OR
SELECT <Column 1> <Desired Column Name> FROM <Table
Name>;)
Function Retrieves data while assigning temporary specific column
names.

Note This command does not update or alter a table. This command
is used for the purpose of visualization only. Alias does not
exist after the duration of the query.

18
6 Listing Certain Data from a Table

Command Syntax SELECT


<Column 1>, <Column 2>
FROM <Table Name> WHERE <Condition>;

Function Retrieves data according to logical constraints.

Note WHERE clause allows conditions to be followed.

7 Retrieve Distinct Data from a Table

Command Syntax SELECT DISTINCT <Column1>, <Column2>


FROM <Table Name>;

Function Retrieves only distinct (different) values.

8 Retrieve Data from a Table: Data Sorted by Logical Operator AND

Command Syntax SELECT * FROM <Table Name>


WHERE <Condition> AND <Condition>;

Function Retrieves data that agree with both the conditions on either
side of the logical operator.

9 Retrieve Data from a Table: Data Sorted by Logical Operator OR

Command Syntax SELECT * FROM <Table Name> WHERE <Condition> OR


<Condition>;

Function Retrieves data that at least agree with one of the conditions
on either side of the logical operator.

10 Retrieve Data from a Table: Data Sorted by Logical Operator NOT

Command Syntax SELECT * FROM <Table Name> WHERE NOT <Column>;


OR
SELECT * FROM <Table Name> WHERE <Column>!;

Function Retrieves data that at least agree with one of the conditions
on either side of the logical operator.

19
11 Pattern Matching
Command Syntax SELECT * FROM <Table Name> WHERE <Column> LIKE
<OPERATOR>;
Function … WHERE <Column> Finds any values that starts with
LIKE <a%>; ‘a.’
… WHERE <Column> Finds any values that ends with ‘a.’
LIKE <%a>;
… WHERE <Column> Finds any values that have ‘OR’ in
LIKE <%OR%>; any position.
… WHERE <Column> Finds any values that have ‘a’ in
LIKE <_a%>; the second position.
… WHERE <Column> Finds any values that starts with ‘a’
LIKE <a_%_%>; and are at least three characters in
length.
… WHERE <Column> Finds any values that starts with ‘a’
LIKE <a%o>; and ends with ‘o.’
Note LIKE operator is used in a WHERE clause to search for a
specific pattern in a column.
LIKE operator is used with wildcard characters; % and _.
_ represents a single character.
% represents zero or more characters.
17 Retrieve Selected Number of Rows from a Table: SELECT LIMIT Clause
Command Syntax SELECT * from <Table Name> LIMIT <from>, <till>;
Function Returns specified number of rows of records.
18 Retrieve Sorted Data from a Table: ORDER BY Clause
Command Syntax SELECT <Column 1> <Column 2> FROM <Table Name>
ORDER BY <Column1> ASC|DESC;
Function Sort data in ascending or descending order.
Note asc – sorts data in ascending order.
desc – sorts data in descending order.
Unless specified, the function sorts data in ascending order
by default.
19 Retrieve Sorted Data from Selected Number of Rows in a Table:
ORDER BY + SELECT LIMIT
Command Syntax SELECT <Column1> FROM <Table Name>
ORDER BY <Column2> ASC|DESC LIMIT <from>, <till>;
Function Sort data in ascending or descending order in specified
number of rows of records.

20
20 Check Nullability
Command Syntax SELECT <Column1> FROM <Table Name>
WHERE <Column2> IS NULL|IS NOT NULL;
Function Tests for empty and non – empty values.
Note IS NULL tests for empty values.
IS NOT NULL tests for non – empty values.
21 Retrieve Data from a Table with Multiple Values in Where Clause: IN / NOT IN
Operators
Command Syntax SELECT * FROM <Table Name> WHERE <Column Name>
IN|NOT IN ('Value1', 'Value2');
Function Allows to specify multiple values in WHERE clause.
Note IN operator is shortened for multiple OR conditions.
22 Retrieve Sorted Data from a Table: GROUP BY Clause
Command Syntax SELECT <Column 1> <Column 2>
AGGREGATE FUNCTION () FROM <Table Name>
WHERE <Condition> GROUP BY <Column1>,<Column2>.. ;
Function Groups rows that have the same values into summary rows.
Note Often used with aggregate functions to group results set by
one or more columns.
23 Retrieve Sorted Data from a Table: GROUP BY + HAVING Clause
Command Syntax SELECT <Column 1> <Column 2>
AGGREGATE FUNCTION () FROM <Table Name>
WHERE <Condition> GROUP BY <Column1>,<Column2>
HAVING <Condition>;
Note The having clause was added to SQL because where
keyword cannot be used with aggregate functions.
24 Retrieve Sorted Data from a Table: GROUP BY + HAVING + ORDER BY Clause
Command Syntax SELECT <Column 1> <Column 2>
AGGREGATE FUNCTION () FROM <Table Name>
WHERE <Condition> GROUP BY <Column1>,<Column2>
HAVING <Condition>
ORDER BY <Column1>,<Column2>,..;

21
6.0 MySQL - Order of Execution
Below mentioned is the order of execution of MySQL commands.

FROM Choose and join tables to get base data.

WHERE Filters the base data.

GROUP BY Aggregate the base data.

HAVING Filters the aggregated data.

SELECT Returns the final data.

ORDER BY Sorts the final data.

LIMIT
Limits the returned data to a row count.

22
7.0 MySQL Tables – Update and Modification

1 UPDATE Command
Command Syntax UPDATE <Column> = <Value>
WHERE <Column> = <Value>;
Function Updates existing records with new values.
2 UPDATE with Function Commands
1 String Functions
CONCAT ()
Command Syntax UPDATE <Table Name>
SET <Column 1> = CONCAT ('Expression', Column 1);
Function Adds two or more string together.
UPPER ()
Command Syntax UPDATE <Table Name> SET <Column 1> = UPPER(‘text’)
WHERE <Column1> = <Record>;
Function Converts a string to upper case.
LOWER ()
Command Syntax UPDATE <Table Name> SET <Column 1> = LOWER(‘TEXT’)
WHERE <Column1> = <Record>;
Function Converts a string to lower case.
2 Date Function
CURTIME ()
Command Syntax SELECT CURTIME ();
Function Shows current time.
NOW ()
Command Syntax SELECT NOW ();
Function Shows date and current time.

23
2 DELETE Command
1 Command Syntax DELETE FROM <Table Name>;
Function Delete all inserted data in a table.
2 Command Syntax DELETE FROM <Table Name> WHERE <Column Name> =
<Value> <LOGICAL OPERATOR> <Condition>;
Function Delete data from specific row/s.
3 ALTER Command
1 Command Syntax ALTER TABLE <Table Name> ADD COLUMN <Column
Name> <Data Type>;
Function Adds a new column.
2 Command Syntax ALTER TABLE <Table Name> DROP COLUMN <Column
Name>;
Function Drops an existing column.
3 Command Syntax ALTER TABLE <Table Name> MODIFY <Column Name>
<Data Type>;
Function Modifies an existing column.
4 Command Syntax ALTER TABLE <Table Name> RENAME TO <New Table
Name>;
OR
(RENAME TABLE <Table Name> TO <New Table Name>;)
Function Renames an existing table.
5 Command Syntax ALTER TABLE <Table Name> RENAME <Column Name>
TO <New Column Name>;
Function Renames an existing column.

24
8.0 MySQL Tables – Constraints

1 NOT NULL Constraint


Command Syntax CREATE TABLE <Table Name> (
<Column Name 1> <Data Type>,
<Column Name 2> <Data Type> NOT NULL,
<Column Name 3> <Data Type>
);
Function Ensure that a column cannot have a null value. It does not
allow to have null values. But it allows duplicate values.
2 UNIQUE Constraint
Command Syntax CREATE TABLE <Table Name> (
<Column Name 1> <Data Type>,
<Column Name 2> <Data Type> UNIQUE,
<Column Name 3> <Data Type>
);
Function It allows only one null value. But it does not allow duplicate
values.
3 PRIMARY KEY Constraint
Command Syntax 1 Defined at Column Level
CREATE TABLE <Table Name> (
<Column Name 1> <Data Type> PRIMARY KEY,
<Column Name 2> <Data Type>,
<Column Name 3> <Data Type>
);
2 Defined at Table Level
CREATE TABLE <Table Name> (
<Column Name 1> <Data Type>,
<Column Name 2> <Data Type>,
<Column Name 3> <Data Type>,
PRIMARY KEY (<Column Name 1>)
);
Function Primary Key is a combination of a Not Null and Unique
constraints. It uniquely identifies each row in a table.

25
4 FOREIGN KEY Constraint
Command Syntax 1 Defined at Column Level
CREATE TABLE <Table Name> (
<Column Name 1> <Data Type> FOREIGN KEY,
<Column Name 2> <Data Type>,
<Column Name 3> <Data Type>
);
2 Defined at Table Level
CREATE TABLE <Table Name> (
<Column Name 1> <Data Type>,
<Column Name 2> <Data Type>,
<Column Name 3> <Data Type>,
FOREIGN KEY (<Column Name 1>)
);
Function Prevents actions that would destroy links between tables.

5 ALTER -- PRIMARY KEY


Command Syntax 1 ADD PIMARY KEY
ALTER TABLE <Table Name>
ADD PRIMARY KEY <Column Name 1>);
or
ALTER TABLE <Table Name>
ADD CONSTRAINT pk_<Table Name>
PRIMARY KEY <Column Name 1>);
2 DROP PRIMARY KEY
ALTER TABLE <Table Name>
DROP PRIMARY KEY;
or
ALTER TABLE <Table Name>
DROP CONSTRAINT pk_<Table Name> ;
Function Adds or removes Primary Key from existing tables.

26
5 ALTER -- FOREIGN KEY
Command Syntax 1 ADD FOREIGN KEY
ALTER TABLE <Table Name>
ADD FOREIGN KEY <Column Name 1>)
REFERENCES <Table Name> (<Column Name>);
or
ALTER TABLE <Table Name>
ADD CONSTRAINT fk_<Table Name>
FOREIGN KEY <Column Name 1>)
REFERENCES <Table Name> (<Column Name>);
2 DROP FOREIGN KEY
ALTER TABLE <Table Name>
DROP FOREIGN KEY;
or
ALTER TABLE <Table Name>
DROP CONSTRAINT fk_<Table Name> ;
Function Adds or removes Foreign Key from existing tables.

27
9.0 MySQL – Functions

Aggregate Functions
Aggregation is the task of collecting a set of values to return a single value. It is done with the
help of aggregate functions, such as SUM, COUNT, MAX, MIN and AVG.

1 MIN Function
Command Syntax SELECT MIN (<Column Name>)
FROM <Table Name>
WHERE condition;
Function Returns the smallest value of the selected column.
2 MAX Function
Command Syntax SELECT MAX (<Column Name>)
FROM <Table Name>
WHERE condition;
Function Returns the largest value of the selected column.
3 COUNT Function
Command Syntax SELECT COUNT (<Column Name>)
FROM <Table Name>
WHERE condition;
Function Returns the number of rows that matches a specified
criterion.
4 SUM Function
Command Syntax SELECT SUM (<Column Name>)
FROM <Table Name>
WHERE condition;
Function Returns the total sum of a numeric column.
5 AVG Function
Command Syntax SELECT AVG (<Column Name>)
FROM <Table Name>
WHERE condition;
Function Returns the average value of a numeric column.

28
String Functions
String Functions work on string values. Examples for String Functions are LOWER, UPPER,
CONCAT etc.
1 UPPER Function
Command Syntax SELECT UPPER (‘String’);
Function Converts all the characters in a string to uppercase
characters.
2 LOWER Function
Command Syntax SELECT LOWER (‘String’);
Function Converts all the characters in a string to lowercase
characters.
3 CONCAT Function
Command Syntax UPDATE <Table Name> SET <Column Name> = CONCAT
(‘String Value 1’,‘String Value 2’);
Function Joins two or more strings.

Date Functions

1 NOW () Syntax
Command Syntax SELECT NOW();
Function Shows date and current time.
2 CURDATE () Syntax
Command Syntax SELECT CURDATE();
Function Selects current date.
3 CURTIME () Syntax
Command Syntax SELECT CURTIME();
Function Shows current time.

29
10.0 MySQL – Joins

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

1 INNER JOIN
Command Syntax SELECT (<Column/s>)
FROM <Table Name 1>
INNER JOIN <Table Name2>
ON Table Name 1.Column = Table Name 2.Column;
Function Returns records that have matching value in two tables.

2 LEFT OUTER JOIN


Command Syntax SELECT (<Column/s>)
FROM <Table Name 1>
LEFT OUTER JOIN <Table Name2>
ON Table Name 1.Column = Table Name 2.Column;
Function Returns all records from the left table (Table 1), and the
matching records from the right table (Table 2). The result
is 0 records from the right side, if there is no match.

3 RIGHT OUTER JOIN


Command Syntax SELECT (<Column/s>)
FROM <Table Name 1>
RIGHT OUTER JOIN <Table Name2>
ON Table Name 1.Column = Table Name 2.Column;
Function Returns all records from the right table (Table 2), and the
matching records from the left table (Table 1). The result is
0 records from the left side, if there is no match.

30
4 FULL OUTER JOIN
Command Syntax SELECT (<Column/s>)
FROM <Table Name 1>
FULL OUTER JOIN <Table Name2>
ON Table Name 1.Column = Table Name 2.Column;
or
SELECT (<Column/s>)
FROM <Table Name 1>
CROSS JOIN <Table Name2>
ON Table Name 1.Column = Table Name 2.Column;
Function Returns all records when there is a match in left (Table 1) or
right (Table 2) table records.

Note LEFT OUTER JOIN = LEFT JOIN


RIGHT OUTER JOIN = RIGHT JOIN
LEFT OUTER JOIN = LEFT JOIN = CROSS JOIN

31
11.0 MySQL – Sub – Queries

A subquery in SQL is a query, which is nested into another SQL query and embedded with
SELECT, INSERT, UPDATE or DELETE statement along with the various operators like =, <, >,
>=, <=, IN, BETWEEN, etc. We can also nest the subquery with another subquery.

Types of Sub – Queries

Types of Purpose Operators


Sub – Queries
Single Row Only 1 row retrieved by subquery. It uses Single Row
Subquery comparison. Comparison
NOT EQUAL TO. Operators:
<,>, =, <=,>=, <>
Multiple Row More than 1 rows are retrieved by subquery. It Multi Row
Subquery uses multi-row comparison operators. Comparison
Operators:
IN IN, ANY, ALL
Equal to any member in the list.
ANY
Compares value to each value returned by the
subquery.

• <ANY means less than the maximum.


• >ANY means more than the minimum.
• =ANY means is equivalent to IN.
ALL
Compares value to every value returned by the
subquery.

• <ALL means less than the minimum.


• >ALL means more than the maximum.

Command Syntax
SELECT <Select List>
FROM <Table Name>
WHERE <Expression Operator>
SELECT <Select List>
FROM <Table Name>;

32
12.0 MySQL – Procedures

A procedure is a prepared SQL code that you can save, so the code can be reused over and
over again.

1 No Parameter
Command Syntax DELIMITER //
CREATE PROCEDURE Procedure Name ()
BEGIN
COMMAND
END//
DELIMITER;
CALL Procedure Name ();
SELECT @Column Name;
2 IN Parameter
Command Syntax DELIMITER //
CREATE PROCEDURE Procedure Name
(IN <Column Name> Data Type, …)
BEGIN
COMMAND
END//
DELIMITER;
CALL Procedure Name ();
SELECT @Column Name;
3 OUT Parameter
Command Syntax DELIMITER //
CREATE PROCEDURE Procedure Name
(OUT <Column Name> Data Type, …)
BEGIN
COMMAND
END//
DELIMITER;
CALL Procedure Name ();
SELECT @Column Name;
4 IN OUT Parameter
Command Syntax DELIMITER //
CREATE PROCEDURE Procedure Name
(IN <Column Name> Data Type, OUT <Column Name>
Data Type )

33
BEGIN
COMMAND
END//
DELIMITER;
CALL Procedure Name ();
SELECT @Column Name;
5 IF ELSE Procedure
Command Syntax DELIMITER $$
CREATE PROCEDURE Procedure Name (Parameter)
BEGIN
COMMAND
IF (Condition) THEN
SET <Column Name> = ‘TRUE’;
ELSE
SET <Column Name> = ‘FALSE’;
END IF;
END$$
DELIMITER;
CALL Procedure Name ();
SELECT @Column Name;
5 IF ELSEIF ELSE Procedure
Command Syntax DELIMITER $$
CREATE PROCEDURE Procedure Name (Parameter)
BEGIN
COMMAND
IF (Condition) THEN
SET <Column Name> = ‘TRUE 1’;
ELSEIF
SET <Column Name> = ‘TRUE 2’;
ELSE
SET <Column Name> = ‘FALSE’;
END IF;
END$$
DELIMITER;
CALL Procedure Name ();
SELECT @Column Name;

34
13.0 MySQL – Case

CASE
Command Syntax SELECT <Column1>, <Column2>, <Column3>, …,
(CASE
WHEN <Condition 1>
THEN <‘Statement 1’>
WHEN <Condition N>
THEN <‘Statement N’>
END)
ELSE <‘Result’>
AS <Column Name>
FROM <Table Name>;

14.0 MySQL – View

In SQL, a view is a virtual table based on the result set of an SQL statement. A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.

VIEW
Command Syntax CREATE VIEW View Name AS
SELECT <Column1>, <Column2>, <Column3>, …,
FROM <Table Name>
WHERE <‘Condition>

DROP VIEW View Name;

35
15.0 MySQL – Trigger

A Trigger is a stored procedure in database which automatically invokes whenever a special


event in the database occurs.

TRIGGER
Command Syntax CREATE TRIGGER Trigger Name
<BEFORE|AFTER>
<INSERT|UPDATE|DELETE>
ON <Table Name>
FOR EACH ROW
<Trigger Body>;

16.0 MySQL – INDEX

The CREATE INDEX statement is used to create indexes in table. Indexes are used to retrieve
data from the database quicker than normal searches and queries.

INDEX
Command Syntax CREATE INDEX Index Name
ON <Table Name>
(Column Name1, Column Name 2, …);

36
ASSIGNMENT 1: STUDENT Table

Create STUDENT Table and insert data of about 10 students.

37
ASSIGNMENT 2
DATABASE ALPHA: PART 1
A company called Alpha Ltd. wants to keep records of their employees working in
different departments across different locations. Create a database names Alpha for the
company that contains the following tables:

1. Table emp that records:


emp_id, emp_name, emp_address, emp_phone, emp_dept_id, emp_designation,
emp_monthlysalary.

2. Table emp that records:


dept_id, dept_name, dept_location

38
Insert at least 10 records in both the tables.

39
40
Answer all the Queries.

1. List the names of all the employees that work in Alpha company.

41
2. List the names of all the departments within Alpha company.

42
3. List the employee id, name and annual salary as required by the accounts department.

43
4. List the distinct designations in the company.

5. List names of all the employees who are clerks.

6. List all the departments in London.

44
7. List the employees along with their designations.

45
8. List the names and address of all employees who are managers.

9. List all the employees whose salary is greater than 30000.

46
10. List the address of the employee named ‘Ana.’

11. List all the salesperson with salary greater than 20,000.

12. List the employee ids of all managers whose location is New York.

47
13. List all employees who belong to the department no 1.

14. List all managers and their salaries who belong to the department 2.

48
15. List all employees except ‘Ana’.

49
ASSIGNMENT 3
DATABASE ALPHA: PART 2
1. List all employees as per their salary starting from the employee with highest salary.

50
2. List all employees alphabetically as per their designation.

51
3. List the employee id, name and quarterly salary of all employees. The names of the field should
be displayed as: Employee Code, Name of the Employee, Quarterly Salary of employee.

52
4. The salary of all clerks is increased by 5000. Reflect the changes in the table.

5. List all employees whose salary is greater than 45000 but less than 99999.

53
6. The company got acquired by a new Company Beta Ltd. Affix the letter ‘A’ in all the
departments id.

7. The department of all the salesperson to be updated to ‘B_DS’.

54
8. The analytics department has now moved to Chicago. Reflect the changes in the database.

9. The salary of the director of Alpha company working in London is now upgraded to $400000.

55
10. All the clerks of the Alpha company are fired and their corresponding records from the
employee needs to be removed.

56
11. All the departments in the location “Paris” are shut. Reflect the changes in the database.

12. List the employee id and address of all the analysts working at New York office earning salary
greater than 70000 except for the analyst Bob.

57
13. List all the managers who either work in ‘D2’ departments or are residing at ‘Delhi’.

58
ASSIGNMENT 4 – DATABASE EMPLOYEE

1. Create a table emp with the columns EMP_ID, EMP_NAME, DESIGNATION and
SALARY. Declare EMP_ID as the PRIMARY KEY.

2. Try to enter same values for EMP_ID.

59
3. Try to give a null value to EMP_ID.

4. Give values only for EMP_NAME and SALARY skipping for EMP_ID and
DESIGNATION.

5. Create table dept with columns DEPT_ID, DEPT_NAME, DEPT_LOC with DEPT_ID as
the PRIMARY KEY. Insert at least 4-5 records in the table.

60
6. Create table emp with columns EMP_ID, EMP_NAME, DESIGNATION, SALARY,
D_ID and make EMP_ID as the PRIMARY KEY and D_ID as the FOREIGN KEY.

7. Insert at least 4-5 records in the table.

8. Try inserting a null value in the foreign key column D_ID.

61
9. Try inserting a value in foreign column of EMP table which doesn’t exist in the parent table
key column DEPT_ID.

10. Try inserting the value which already exist in D_ID column.

62

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy