Sahan 2k21bmba03
Sahan 2k21bmba03
Submitted by
Submitted to
TOPIC PAGE NO
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.
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
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.
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
3
6. Chose your installer and click – Download
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.
5
13. Go to – Type and Networking. Go with default settings, Click – Next.
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
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 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.
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
2 Retrieve a Subset of Data from a Table: Selected Columns and All Rows
3 Retrieve a Subset of Data from a Table: Selected Rows and All Columns
4 Retrieve a Subset of Data from a Table: Selected Rows and Selected Columns
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
Function Retrieves data that agree with both the conditions on either
side of the logical operator.
Function Retrieves data that at least agree with one of the conditions
on either side of the logical operator.
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.
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
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.
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.
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.
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.
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>;
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>
35
15.0 MySQL – Trigger
TRIGGER
Command Syntax CREATE TRIGGER Trigger Name
<BEFORE|AFTER>
<INSERT|UPDATE|DELETE>
ON <Table Name>
FOR EACH ROW
<Trigger Body>;
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
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:
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.
44
7. List the employees along with their designations.
45
8. List the names and address of all employees who are managers.
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.
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.
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.
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