You are on page 1of 147

SQL

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.

A Relational Database has the following characteristics −


•organizes data such that it appears to the user to be stored in a series of interrelated tables
•used for high-performance applications
•efficient
•ease of use
•ability to perform a variety of useful tasks
DBMS and RDBMS
DBMS represents a Database Management System. It is used to create/update/delete and maintain a
database and it provides controlled access to data. 
RDBMS, Relational Database Management System, is an enhanced version of DBMS.
DBMS and RDBMS

Following are the important differences between


DBMS and RDBMS.
Why Study SQL?
Why Study SQL?
According to Stackoverflow, Most Popular Technology —
Why Study SQL?
Why Study SQL?
Advantages of Using SQL
• Higher Processing Speed: SQL generally operates at a high speed when users explore the database.
It helps in retrieving large amounts of data quickly and efficiently.
• Minimal Coding Requirement: SQL is highly user friendly, i.e. it is easy to use. Someone with no
coding experience can easily learn basic SQL coding within a few days. The code structure is also
simple, borrowing heavily from English sentences with minimal use of special characters.
• Easier to Manipulate Data: With SQL, it is very easy to view and manipulate the existing data on the
database. With a few queries, users can update or change the uploaded information on the database,
thus making it helpful for storing dynamic information.
• Easier Data Mining: Among other uses of SQL, it is used for sorting and filtering data by using several
queries, making the data more relevant and useful, while reducing redundancy.
• Restricted Access: SQL is widely considered a safe and protected database. The system is password
protected on every device, thus making it difficult for malicious users to use the data without consent.
Advantages of Using SQL
• Reliable for Complex Queries: SQL is highly-reliable to deliver correct results
on complex queries by users, as compared to other Database Management
systems.
Uses of SQL
• Data Definition Language (DDL)

• Data Control Language (DCL)

• Data Manipulation Language (DML)


Uses of SQL
• Data Definition Language (DDL)

• Amongst the prominent uses of SQL, it is applied as Data Definition Language


(DDL) in order to define and modify the structure of data.
• The commands under DDL are used to add, remove or modify the tables
within a database.
• Create, Drop, Alter, are some of the commonly used DDLs.
Uses of SQL
• Data Control Language (DCL)

When SQL is applied as a Data Control Language, it is mainly to control the


permissions and rights to perform certain actions on the database.
When it comes to the uses of this SQL sub-language, it is mainly utilised by the
Database Administrator to give or take back permission from the users.
“Grant” and “Revoke” are examples of DCL
Uses of SQL
• Data Manipulation Language (DML)

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

DATE A date. Format: YYYY-MM-DD. The


supported range is from '1000-01-01' to
'9999-12-31'

TIME(fsp) A time. Format: hh:mm:ss. The supported


range is from '-838:59:59' to '838:59:59'
SQL – Data Types
INT(size) A medium integer. Signed range is from -
2147483648 to 2147483647. Unsigned
range is from 0 to 4294967295.
The size parameter specifies the maximum
display width (which is 255)
SQL – SELECT
SQL
• SELECT statement – used to load a particular data from the database
• Format
SELECT coloumn1,column2,…column
FROM table_name;
SQL
• Excercise:
o Load first name and last name from the employees table
o Load All the data from the employees table

• Load department number from departments table


• Load all data from departments table
SQL – WHERE Operator
SQL
• WHERE - used to narrow down the search criteria
• Format
SELECT coloumn1,column2,…column
FROM table_name
WHERE condition;
SQL
• Excercise:
o Load the employees from the employees table whose first name is “Saniya”
o Load the employees from the employees table whose first name is “Mahendra”
o Load the employees from the employees table whose first name is “Subbu”
SQL – AND Operator
SQL
• AND = Allows you to logically combine two statements in the condition code
• Format
SELECT coloumn1,column2,…columnN
FROM table_name;
Where condition_1 and condition_2
SQL
• AND = Allows you to logically combine two statements in the condition code
• Excercise:
o Load the employees from the employees table whose first name is “Saniya” and last
name is “Khalil”
o Load the employees from the employees table whose first name is “Mahendra” and last
name is “dasSarma”
o Retrieve a list with all female employees whose first name is Kellie. 
SQL – OR Operator
SQL
• OR = Allows you to logically execute either of the two statements in the
condition code
• Format
SELECT coloumn1,column2,…columnN
FROM table_name;
Where condition_1 or condition_2
SQL
• Excercise:
• Retrieve a list with all employees whose first name is either Kellie or Aruna.
SQL
• Example
• Select all the employees whose last name is “denis” and gender is either male or
female
SQL
• Example
• Select all the employees whose last name is “denis” and gender is either male or
female

• 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

• Create two tables departments_dup and dept_manager_dup


• Copy the data from departments to departments_dup
• Insert the department public relations
• Delete the department d002
• Insert two departments – d010 and d011
SQL
• Create two duplicate tables to understand join functionality and not
to mess the original tables

• Create two tables departments_dup and dept_manager_dup


• Copy the data from dept_manager to dept_manager_dup
• Insert the values 999904 to 999907 and date as 2017-01-01
• Delete the department d001
SQL

• DROP TABLE IF EXISTS departments_dup; • DELETE FROM departments_dup


• CREATE TABLE departments_dup • WHERE
• ( •     dept_no = 'd002';    
•     dept_no CHAR(4) NULL, • INSERT INTO departments_dup(dept_no) VALUES
('d010'), ('d011');
•     dept_name VARCHAR(40) NULL
• );
•  
• INSERT INTO departments_dup
• (dept_no, dept_name)
• SELECT * FROM departments;

• INSERT INTO departments_dup (dept_name)


• VALUES ('Public Relations');
•  
SQL

• DROP TABLE IF EXISTS dept_manager_dup; •                                 (999905, '2017-01-01'),


• CREATE TABLE dept_manager_dup ( •                                (999906, '2017-01-01'),
•   emp_no int(11) NOT NULL, •                                (999907, '2017-01-01');
•   dept_no char(4) NULL, •  
•   from_date date NOT NULL, • DELETE FROM dept_manager_dup
•   to_date date NULL • WHERE
•   ); •     dept_no = 'd001';

• INSERT INTO dept_manager_dup


• select * from dept_manager;
• INSERT INTO dept_manager_dup (emp_no, from_date)
• VALUES                (999904, '2017-01-01'),
SQL
• INNER JOIN

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.

• Hint: Create an output containing information corresponding to the


following fields: ‘emp_no’, ‘first_name’, ‘last_name’, ‘dept_no’,
‘from_date’.
SQL
• SELECT
•     e.emp_no,
•     e.first_name,
•     e.last_name,
•     dm.dept_no,
•     dm.from_date
• FROM
•     employees e
•         LEFT JOIN
•     dept_manager dm ON e.emp_no = dm.emp_no
• WHERE
•     e.last_name = 'Markovitch'
• ORDER BY dm.dept_no DESC, e.emp_no;
SQL
SQL
• Join and Where used together

• Join: Used for connecting two tables

• Where: Used to define the condition on which the join is to be


performed
SQL
• Obtain the employee no, First_name, Last_name and salary of the
employees where the salary is greater than 145000 $

• 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

• Stored Routine – An SQL statement, or a set of SQL statements, that


can be stored on the database server

• 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.

• Then, call the procedure.


SQL – Stored Routines
• Alternative way of creating a stored routine
SQL – Stored Routines
• Drop a routine

• Drop procedure procedure_name;


SQL – Stored Routines
• Parametric Procedures
SQL – Stored Routines
• Parametric Procedures
• DELIMITER $$
• create Procedure Procedure_name ( in parameter);
• Begin
• select * from employees
• LIMIT 1000;
• END $$
• DELIMITER ;
SQL – Stored Routines
• Create a stored parameter procedure to obtain the first_name,
last_name, salary, from date, to date for the employee 11300

• Obtain first_name, last_name, average salary for the employee 11300


SQL – Stored Routines
• use employees;
• drop procedure if exists sal_details;
• delimiter $$
• create procedure sal_details( in p_emp_no integer)
• begin
• select e.first_name, e.last_name, s.salary, s.from_date, s.to_date
• from employees e
• join salaries s
• on e.emp_no = s.emp_no
• where e.emp_no = p_emp_no;
• END $$
• delimiter ;
SQL – Stored Routines
• OUT Paramater – Used to store the value to a variable so that it can
be referred later
SQL – Stored Routines
• DELIMITER $$
• create Procedure Procedure_name ( in parameter , OUT parameter);
• Begin
• select
• Into parameter
• col_name from employees
• LIMIT 1000;
• END $$
• DELIMITER ;
SQL – Stored Routines
• Create a procedure called ‘emp_info’ that uses as parameters the first
and the last name of an individual, and returns their employee
number.
SQL – Stored Routines
• DELIMITER $$
• CREATE PROCEDURE emp_info(in p_first_name varchar(255), in p_last_name
varchar(255), out p_emp_no integer)
• BEGIN
• SELECT e.emp_no
• INTO p_emp_no
• FROM employees e
• WHERE e.first_name = p_first_name AND e.last_name = p_last_name;
• END$$
• DELIMITER ;
SQL – Stored Routines
• SQL Variables

• 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.

• Finally, select the obtained output.


SQL – Stored Routines
• set @v_emp_no = 0;
• call employees.emp_info('aruna', 'journel', @v_emp_no);
• select @v_emp_no;

You might also like