Mana Mohan R
Mana Mohan R
Mana Mohan R
Why Study SQL?
Why Study SQL?
Why Study SQL?
What is a Database?
A collected information which is in an organized form for easier access, management, and various
updating is known as a database.
What is a Data?
Data can be defined as a collection of facts and records on which we can apply reasoning or can-do
discussion or some calculation.
The data is always easily available and is in plenty.
It can be used for processing some useful information from it.
Also, it can be in redundant, can be irrelevant.
Data can exist in form of graphics, reports, tables, text, etc. that represents every kind of information, that
allows easy retrieval, updating, analysis, and output of data by systematically organized or structured
repository of indexed information.
What is a Database?
Containers having a huge amount of data are known as databases, for example, a public library stores books.
Databases are computer structures that save, organize, protect, and deliver data.
Any system that manages databases is called a database management system, or DBM. The typical diagram
representation for a database is a cylinder.
What is a Database?
Inside a database, the data is recorded in a table which is a collection of rows, columns, and it is indexed
so that to find relevant information becomes an easier task.
As new information is added, data gets updated, expanded and deleted.
There are several different types of database models have been developed so far, for example, flat,
hierarchical, network and relational. These models describe the operations that can be performed on
them as well as the structure of the conforming databases. Normally there is a database schema which
describes the exact model, entity types, and relationships among those entities.
What is a Database?
Flat Databases have the following characteristics −
•simple
•long and dominant
•useful for very small scale and simple applications.
DML refers to the SQL commands used to make changes within the database.
These are used to insert, edit or delete the existing data, even up to a single cell
or entry.
Some examples of DML are “Insert”, “Update”, ”Delete”.
MySQL Installation
The Client Server Model
The Relational Schema
The Relational Schema
• Consider a database called “Sales” to illustrate the concept of relational.
• The data will be stored in 4 tables – “Sales”, “Customers”, “Items”, and “Companies”.
The Relational Schema
• Table
The Relational Schema
• The Fields of a Table
The Relational Schema
• SQL Primary Key: A
column (or a set of
columns) whose
value exists and is
unique for every
record in a table is
called a primary
key.
The Relational Schema
The Relational Schema
• SQL Primary Key
• Another crucial
feature of primary
keys is they cannot
contain null values.
The Relational Schema
• How to Create a Relational Schema
• To create a relational schema, we draw a table, and we place its name on top.
• Then, we enlist the fields vertically. The field that is the primary key of the table is usually
quoted on top of the other fields. it is always underlined.
The Relational Schema
• How to Create a Relational Schema
• when you spot this table, you will immediately know: It is called “Sales”; its primary key is
purchase_number; and there are three other fields – date_of_purchase, customer_ID,
item_code.
The Relational Schema
• How to Create a Relational Schema
• This image corresponds to tabular data in the following form:
The Relational Schema
• How to Create a
Relational Schema
• When you combine
the schemas of the
tables we have in a
database, this gives
us a database
schema.
Activity: Create a relational Schema
Activity: Create a relational Schema
SQL – Data Types
SQL – Data Types
Data type Description
CHAR(size) A FIXED length string (can contain letters, numbers, and
special characters). The size parameter specifies the column
length in characters - can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and
special characters). The size parameter specifies the
maximum column length in characters - can be from 0 to
65535
BINARY(size) Equal to CHAR(), but stores binary byte strings.
The size parameter specifies the column length in bytes.
Default is 1
SQL – Data Types
ENUM(val1, val2, val3, ...) A string object that can have only one
value, chosen from a list of possible values.
You can list up to 65535 values in an ENUM
list. If a value is inserted that is not in the
list, a blank value will be inserted. The
values are sorted in the order you enter
them
• Is it correct?
• You have to consider operator precedence. AND is Always executed before OR
• Use Brackets
SQL
• Example
• Retrieve a list with all female employees whose first name is either Kellie or Aruna.
SQL – IN Operator
SQL
• Example
• Retrieve the employees list whose first name is Cathie, Mark and Nathan.
SQL
• IN operator – IN Operator allows SQL to return the data written in parenthesis
• SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
SQL
• SELECT *
FROM employees
WHERE first_name IN (‘Cathie’,’Mark’,’Nathan’);
SQL
• Use the IN operator to select all individuals from the “employees”
table, whose first name is either “Denis”, or “Elvis”.
SQL – NOT IN Operator
SQL
• NOT IN operator – NOT IN Operator allows SQL to return the data excluding what is
written in parenthesis
• SELECT column_name(s)
FROM table_name
WHERE column_name NOT IN (value1, value2, ...);
SQL
• Exercise –
• Retrieve the employees list whose first name is “NOT” Cathie, Mark and Nathan.
SQL
• Exercise –
• Extract all records from the ‘employees’ table, aside from those with employees named
John, Mark, or Jacob.
SQL – Like Operator
SQL
• LIKE - The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
• There are two wildcards often used in conjunction with the LIKE operator:
• % - The percent sign represents zero, one, or multiple characters
• _ - The underscore represents a single character
• SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
SQL
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at
least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
SQL
• Example – Retrieve the list of employees whose first name begins with ‘Mar’
• Retrieve the list of employees whose first name ends with ‘ar’
• Retrieve the list of employees where the first name contains ‘ar’ in the name
• Retrieve the list of employees where the name contains 4 letters and the first three letter
are ‘mar’
• Retrieve a list with all employees who have been hired in the year 2000
• Retrieve a list with all employees whose employee number is written with 5 characters, and
starts with “1000”.
SQL – NOT Like Operator
SQL
• NOT LIKE - The Not LIKE operator is used to get records that doesn’t match the like
pattern.
• SELECT column1, column2, ...
FROM table_name
WHERE columnN NOT LIKE pattern;
SQL
• Example: display the list of customers where the first name doesn’t start with ‘mar’
Exercise
• Extract all individuals from the ‘employees’ table whose first name contains “Jack”.
• Once you have done that, extract another list containing the names of employees that do
not contain “Jack”.
SQL – BETWEEN OPERATOR
SQL
• The BETWEEN operator selects values within a given range. The
values can be numbers, text, or dates.
• SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SQL
• Select all the information from the “salaries” table regarding contracts
from 66,000 to 70,000 dollars per year.
• Retrieve a list with all individuals whose employee number
is not between ‘10004’ and ‘10012’.
• Select the names of all departments with numbers between ‘d003’
and ‘d006’.
SQL – IS NULL/NOT NULL OPERATOR
SQL – COMPARISON OPERATOR
=, >, >=, =<, <, <>, !=
SQL
• SELECT column_name(s)
FROM table_name
WHERE column_name >,<,>=,<=,<>,!= “condition”;
SQL
• Retrieve a list with data about all female employees who were hired
in the year 2000 or after.
• Extract a list with all employees’ salaries higher than $150,000 per
annum.
• Extract a list with all employees’ whose first name is not equal to
mark and hire date is lesser than year 2000
SQL – DISTINCT OPERATOR
SQL
• The SELECT DISTINCT statement is used to return only distinct
(different) values.
• SELECT DISTINCT column1, column2, ...
FROM table_name;
SQL
• Obtain a list with all different “hire dates” from the “employees”
table.
SQL – Aggregate OPERATOR
count, sum, min, max, avg
SQL
• Count() – counts the number of non null records in a field
• Sum() – sum all the non null values in a record
• MIN() – returns the min value in the entire list
• MAX() – returns the maximum value in the entire list
• AVG() – returns the average of all non null values in a column
SQL
• Count() –
• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
• SUM () –
• SELECT SUM(column_name)
FROM table_name
WHERE condition;
SQL
• SELECT AVG(column_name)
FROM table_name
WHERE condition;
• SELECT MIN(column_name)
FROM table_name
WHERE condition;
SQL
• How many annual contracts with a value higher than or equal to
$100,000 have been registered in the salaries table?
• How many managers do we have in the “employees” database? Use
the star symbol (*) in your code to solve this exercise.
• How many departments are there in the “employees” database? Use
the ‘dept_emp’ table to answer the question.
SQL
• What is the total amount of money spent on salaries for all contracts
starting after the 1st of January 1997?
• Which is the lowest employee number in the database?
• Which is the highest employee number in the database?
• What is the average annual salary paid to employees who started
after the 1st of January 1997?
SQL – Round function
SQL
• Select ROUND(column or no, decimals)
FROM table_name
WHERE condition;
• Round the average amount of money spent on salaries for all
contracts that started after the 1st of January 1997 to a precision of
cents.
SQL – Order By
SQL
• The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
• SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SQL
• Select all data from the “employees” table, ordering it by “hire date”
in descending order.
• Select all data from the employees table. Order by first name in
ascending order and then order by last name in ascending order.
SQL – group By
SQL
• Group By is used to group the results to a specific field or fields.
• Group By must be placed immediately after the where condition if any
and just before the order by clause.
• SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
SQL
• Find out how many times the same hire date has been encountered in
the data base.
• Once found, sort it in the descending order.
• Find out how many times the first name is repeated in the database.
SQL – Aliases (AS)
SQL
• SQL aliases are used to give a table, or a column in a table, a
temporary name.
• SELECT column_name AS alias_name
FROM table_name;
SQL
• Write a query that obtains an output whose first column must contain
annual salaries higher than 80,000 dollars. The second column,
renamed to “emps_with_same_salary”, must show the number of
employee contracts signed with this salary.
SQL – JOIN
SQL
• Primary key and foreign key
SQL
• SQL Join – the sql tool that allow us to construct a relationship
between the objects
• We must find a related column from the two tables that contain the
same type of data
• We can add any no of columns from these two tables to our output.
SQL
• Understanding create, delete and insert table
SQL
• Create a table Students with the columns – Student_id, First_name,
Last_name, phone_no, mail_id, Gender. Make sure the student id is
set to not null.
• Insert your class mates details into the table
• Create another table Students_temp
• Copy all the data from the table “students” to “students_temp”
• Delete the last two records from students_temp
SQL
• Create two duplicate tables to understand join functionality and not
to mess the original tables
departments_dup dept_manager_dup
SQL
• SELECT table1.column_name(s), table2.column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SQL
• Retrieve the list with department number, department name
employee no from the recently created duplicate tables.
SQL
• Extract a list containing information about all managers’ employee
number, first and last name, department number, and hire date.
• Extract a list containing information about all managers’ employee
number, first and last name, department number, and hire date
whose last name is Markovitch.
SQL
• LEFT JOIN
departments_dup dept_manager_dup
SQL
• Join the 'employees' and the 'dept_manager' tables to return a subset
of all the employees whose last name is Markovitch. See if the output
contains a manager with that name.
• Select the first and last name, the hire date, and the job title of all
employees whose first name is “Margareta” and have the last name
“Markovitch”.
• Find the count, sum, average salaries of men and women in the
company and use alias to rename the column
SQL
• Joining two or more tables
• Retreive first name, last name, hire date, from date, and department
name of all the employees
• Select all managers’ first and last name, hire date, job title, start date,
and department name.
SQL
Obtain the output in MySQL for the below
• Retrieve the list of customer name, customers contact name, phone
number, address, order number and order date for the orders which
are cancelled
• Retrieve the list of customer name, customers contact name, phone
number, address, order number and order date for the orders which
are under dispute
• Obtain the list of unique shipping status for the company
• Obtain the list of orders which has some comments noted on them.
SQL
• Obtain the output with customer number, Customer name,
customer contact name, phone number, city, order number, product
code, product name for only motorcycles sales
• Arrange the output in ascending order
• How many products are there in product line “motorcycle”
SQL
Obtain the below details using MySQL
• Retrieve the list of employees who are working in France
• Retrieve the list of all the persons who are in the managerial
position (President, VP, Manager, Representative)
• Retrieve the list of the customer who has got the maximum credit
limit
• Obtain the product with a lowest price and the highest price
SQL
Obtain the below details of the customer using MySQL
• Customer name, Customer contact name, Phone number, Address,
Check number, amount, and payment date
• Sort the list by ascending order
• Filter the list further for those customers who has made the
payment of 1lakh
SQL
• Retrieve the list of customer name, customers contact name, phone
number, address, order number and order date for the orders which
are cancelled
• For the above output, obtain the product name and the quantity
ordered
• For the above output, obtain the reasons for cancellation
SQL
- Obtain how many products are there in each product line
- Rename the count column as “Count_of_Products”
- Order the output in ascending order
- Include the description of product line in the output
SQL
Obtain the output for the below list using MySQL
• Obtain the employee number, first name, last name, email, office
address (complete address) for all the Vice Presidents
• Obtain the minimum amount paid by the customer, maximum
amount paid by the customer
• Obtain the unique job titles of the employees
SQL
• Obtain the output with customer number, Customer name,
customer contact name, phone number, city, order number, product
code, product name
• Arrange the output in ascending order
• Obtain the output to see under which product line the product
“2001 Ferrari Enzo” falls in
SQL – Stored Routines
• Routine – A usual, fixed action, or series of actions, repeated
periodically
• Whenever a user needs to run the query in question, they can call,
reference, or invoke the routine
SQL – Stored Routines
• Example: A query to check all monthly sales generated throughout
the calender year and to return the lowest of these values
SQL – Stored Routines
• Syntax
• DELIMTER $$
• CREATE PROCEDURE Procedure_name ()
• Begin
Select * from employees
LIMIT 1000;
END $$
SQL – Stored Routines
• 1. Return the first 1000 rows from the ‘employees’ table
SQL – Stored Routines
• use employees;
• drop procedure if exists select_employees;
• DELIMITER $$
• create Procedure select_employees();
• Begin
• select * from employees
• LIMIT 1000;
• END $$
• DELIMITER ;
SQL – Stored Routines
• Invoking a stored routine
• call database_name.procedure_name();
SQL – Stored Routines
• Create a procedure that will provide the average salary of all
employees.
• set @variable_name = 0;
• call database.procedure_name(value, @variable_name);
• select @variable_name;
SQL – Stored Routines
• SQL Variables
• set @avg_sal = 0;
• call employees.emp_avg_sal(11300, @avg_sal);
• select @avg_sal;
SQL – Stored Routines
• Create a variable, called ‘v_emp_no’, where you will store the
output of the procedure you created in the last exercise.
• Call the same procedure, inserting the values ‘Aruna’ and ‘Journel’
as a first and last name respectively.