0% found this document useful (0 votes)
34 views

SQL102

The document discusses various SQL concepts like creating and dropping databases, importing and exporting files, filtering data using where clauses, arithmetic and comparison operators, and logical operators. It provides examples of SQL queries to retrieve filtered data based on conditions. It also includes assignments asking the reader to write SQL queries to retrieve records from the "Salesman" table based on various criteria.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

SQL102

The document discusses various SQL concepts like creating and dropping databases, importing and exporting files, filtering data using where clauses, arithmetic and comparison operators, and logical operators. It provides examples of SQL queries to retrieve filtered data based on conditions. It also includes assignments asking the reader to write SQL queries to retrieve records from the "Salesman" table based on various criteria.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

SQL : Lecture 2

What to expect
Till now, you have downloaded and installed MySQL and have a good idea about
creating tables, inserting data into it, retrieving data from it. You also have studied about
relationships between different tables in a dataset along with the data types and
constraints. You have learnt about primary and foreign keys which helps you define
relationships between different tables.

Now its time to move on and understand


• How to create and drop a database
• How to import and export files in MySQL
• How to read and understand data and data types
• How to filter data basis given conditions
• How to apply operators along with filters
• Introduction to functions, group by, order by & having
Creating and dropping a database

The CREATE DATABASE statement is used The DROP DATABASE statement is used to
to create a new SQL database drop an existing SQL database

After successfully running the above query After successfully running the above query
new database naming studentInformation existing database naming
will be created studentInformation will be dropped i.e.
A database may contain one or more deleted
tables
Importing a file
Go to Navigator window at left -> Schemas -> select the database under which you want
to import file -> Right click on Tables and then follow the following steps to import a file
from your system.

Click on Next after mentioning the


path in Browser window
Importing a file

Click on Next after Select next, after checking Click Next, followed by
applying displayed the import settings Finish to complete the
settings importing process.
Refresh the Navigator
window in Workbench to
see the imported file
Importing & Exporting Files
Import Data
– Records from a CSV file can be imported into the result set of the workbench
Export a Result Set
– A result set in the workbench can be exported to common file formats including
CSV, JSON, HTML, and XML
Understanding data using two datasets
a) salesman

Notice that there are 2 columns


which are common between
these 2 tables.
1. salesman_id
2. City

b) customer
Discuss the data types of the
given data fields before moving
to next slide
Importing and understanding the data
Create database ‘db’ and import “salesman.csv” and “customer.csv”
Data Description: (SHOW COLUMNS FROM)
• Salesman dataset has four columns ( Fields) as shown
1. salesman_id , 2. name, 3. city and 4. commission

The data types of respective columns are shown in its adjacent column
• salesman_id and commission are continuous valued columns comprising numeric quantity
• name and city are categorical columns comprising text ( character/ string) data
Importing and understanding the data
• Customer dataset has five columns (Fields) as shown
1. customer_id, 2. cust_name, 3. city, 4. grade and 5. salesman_id

The data types of respective columns are shown in its adjacent column
• customer_id, grade and salesman_id are continuous columns comprising numeric data
• cust_name and city are categorical columns comprising text ( character/ string) data
Retrieving filtered data using where clause
The WHERE clause is used to filter record

Step 1: Check if all the records are Step 2: Fetching the records of sales person
imported successfully from “salesman” table who lives in Rome.
Filtering null values
‘where’ clause is used along with ‘is null’
constraint and ‘or’ operator to check for
missing values in salesman table

‘where’ clause is used along with ‘is null’


constraint and ‘or’ operator to check for
missing values in customer table
Filtering basis a condition

Question: Fetch the names of salesmen who reside in New York city.
Operators
An operator is a reserved word or a character used in an SQL statement's WHERE clause
to perform operations, such as comparisons and arithmetic operations

Below are the list of some operators:


Arithmetic operators (+, -, *, /, %)
Comparison operators (=, !=, <> , > , <)
Logical operators (AND, OR, IN, LIKE, NOT)
Arithmetic Operators
Operator Description Example
+ Addition - Adds values on either side of the operator a+b
- Subtraction - Subtracts right hand operand from left a-b
hand operand
* Multiplication - Multiplies values on either side of a*b
the operator
/ Division - Divides left hand operand by right hand b/a
operand
% Modulus - Divides left hand operand by right hand b%a
operand and returns remainder
Arithmetic Operators

Addition Subtraction Multiplication Division Modulo


Comparision Operators
Operator Description Example

= Checks if the values of two operands are equal or not, if yes then condition becomes true. (a = b)

Checks if the values of two operands are equal or not, if values are not equal then condition becomes
!= true. (a != b)

Checks if the values of two operands are equal or not, if values are not equal then condition becomes
<> true. (a <> b)

Checks if the value of left operand is greater than the value of right operand, if yes then condition
> becomes true. (a > b)

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes
< true. (a < b)
Assignment:
Q1. Using the table “Salesman”. Write down a SQL query to display the records of
salesperson with salesman_id = 5002
Q2. Using the table “Salesman”. Write down a SQL query to display the records of
salesperson with salesman_id not equals to 5001
Q3. Using the table “Salesman”. Write down a SQL query to display the records of
salesperson with salesman_id less than 5003
Q4. Using the table “Salesman”. Write down a SQL query to display the records of
salesperson with salesman_id greater than 5002
Q5. Using the table “Salesman”. Write down a SQL query to display the records of
salesperson with salesman_id less than or equals to 5003
Q6. Using the table “Salesman”. Write down a SQL query to display the records of
salesperson with salesman_id greater than or equals to 5003

Once you have written your query – then only you should move to the next slides to
check for the answers
Comparision Operators

Equals Operator Not Equals Operator


Comparision Operators

Less than Operator Greater than Operator


Comparision Operators

Less than or equals Operator Greater than or equals Operator


Logical Operators

Operator Description

ALL TRUE if all of the sub-query values meet the condition

AND TRUE if all the conditions separated by AND is TRUE

ANY TRUE if any of the sub-query values meet the condition

BETWEEN TRUE if the operand is within the range of comparisons

IN TRUE if the operand is equal to one of a list of expressions

LIKE TRUE if the operand matches a pattern

NOT Displays a record if the condition(s) is NOT TRUE

OR TRUE if any of the conditions separated by OR is TRUE


Assignment:
Q1. Using the table “Salesman”. Write down a SQL query to fetch the records of
Salesman having id = 5001 with grade as 200
Q2. Using the table “Salesman”. Write down a SQL query to fetch the records of
Salesman having id = 5001 or work on grade as 200
Q3. Using the table “Salesman”. Write down a SQL query to fetch the records of
Salesman live in cities other than Rome
Q4. Using the table “Salesman”. Write down a SQL query to fetch the records of
Salesman having salesman id’s in between 5001 to 5005
Q5. Using the table “Salesman”. Write down a SQL query to fetch the records of
Salesmen who live in either New York, Rome, London
Q6. Using the table “Salesman”. Write down a SQL query to fetch the records of
Salesmen who do not live in New York, Rome, London

Once you have written your query – then only you should move to the next slides to
check for the answers
Logical Operators

Fetch the Records of Salesman having Fetch the Records of Salesman having
id = 5001 with grade as 200 id = 5001 or work on grade as 200

AND Operator OR Operator


Logical Operators
Fetch the Records of Salesman live in Fetch the Records of Salesman having
cities other than Rome salesman id’s in between 5001 to 5005.

NOT Operator BETWEEN Operator


Logical Operators
Fetch the Records of Salesmen who Fetch the Records of Salesmen who do
live in either New York, Rome, London not live in New York, Rome, London

IN Operator NOT IN Operator


Like Operator
• It used in the where clause to search for
the specified pattern in the column.
• Two Wildcards are used in conjunction
with LIKE operator.
o The percent sign (%) represents zero,
one, or multiple characters.
o The underscore sign (_) represents
one, single character.

Example 1: Fetch the records of sales men


names whose names starts with P.
Like Operator
Example 2: Fetch the records of salesmen having second letter of name as “A.”
ALL and ANY Operator

To fetch data where all of the given sub- To fetch data where any of the given sub-
query conditions are true. query condition is true.
BASIC FUNCTIONS IN SQL
The COUNT() function gives the number of rows that matches specified conditions
The AVG() function in SQL returns the average value of a numeric column
The SUM() function in SQL returns the total sum of a numeric column
The MIN() function in SQL returns the smallest value of the selected column from the table
The MAX() function in SQL returns the largest value of the selected column from the table

COUNT() Syntax MIN() Syntax


SELECT COUNT(abc) SELECT MIN(abc)
FROM table_name; FROM table_name;
AVG() Syntax MAX() Syntax
SELECT AVG(abc) SELECT MAX(abc)
FROM table_name; FROM table_name;
SUM() Syntax
SELECT SUM(abc)
FROM table_name;
SORTING (ORDER BY)
SELECT * One may also specify multiple sorting columns.
FROM Employees
ORDER BY LName DESC For example:
SELECT *
--This statement will sort the FROM Employees
table in descending order of ORDER BY LName ASC, FName ASC
column ‘Employees’--
--This example will sort the results first by LName and then, for
SELECT * records that have the same LName, sort by Fname--
FROM Employees
ORDER BY LName ASC This will give you a result similar to what you would find in a
telephone book.
--This statement will sort the
table in descending order of In order to save retyping the column name in the ORDER BY clause,
column ‘Employees’-- it is possible to use instead the column's number.
GROUP BY, ORDER BY STATEMENT
The GROUP BY used to group rows from the table. And it has the same values as summary
rows. For example, find the number of customers in each country, The GROUP BY is often
used with aggregate functions like (COUNT, MAX, MIN, SUM, AVG) to group the result-set
by one or more columns.

GROUP BY & ORDER BY Syntax


SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s); ORDER BY is used to sort the results
HAVING CLAUSE
The HAVING clause is added to SQL because the WHERE keyword can not be used with
aggregate functions.

HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition GROUP BY is used to group rows by one or
GROUP BY column_name(s) more columns
HAVING condition
ORDER BY column_name(s); ORDER BY is used to sort the results
Review most used query
There WHERE clause can also be used with GROUP BY, but WHERE filters out records
before any grouping is done. This is just an example :

SELECT department, --select--


AVG(income) --function--
FROM employees –getting data-
WHERE department <> 'ACCOUNTING' --filter--
GROUP BY department; --group rows--

If you need to filter the results after the grouping has been done,
e.g., to see only departments whose average income is larger than 1000, you need to use
the HAVING clause:

Above query +
HAVING AVG(income) > 1000; --further filer--
6 steps of SQL select statement process
Step 1: Getting Data (From, Join)
Result of these operations is a Cartesian product of our 2 tables
Step 2: Row Filter (Where)
After getting qualified rows, it is passed on to the Where clause.
This evaluates every row using conditional expressions
Step 3: Grouping (Group by)
It will group rows that have the same values into summary rows
Step 4: Group Filter (Having)
The Having clause consists of a logical predicate, it is processed
after the Group by (it no longer refer to individual rows, only to
groups of rows)
Step 5: Return Expressions (Select)
During this step, the processor evaluates what will be printed as
a result of the query, and if there are some functions to run on
data like Distinct, Max, Sqrt, Date, Lower, etc.
Step 6: Order (Order by) and Paging (Limit / Offset)
The final processing steps of the query deal with presentation
ordering and the ability to limit the size of the result set
Become smart using SQL
Knowing how to Google >>>> knowing all the SQL functions by heart.
Say, you need to isolate the 5th letter in a string, so you can simply Google:
"Nth character from a string SQL''

And the substring() function will pop


You may or may not know substring(). You may have used substring(). But it had been a
while, so you simply had to look it up!

The fact that you don't need to know all the SQL functions at any given point in time is
incredibly liberating.
So don't worry about memorizing all the functions you have learned...
because they're ALWAYS just a simple Google search away

You will be working on case study in the next session – where it is completely fine if you
google and code – become smart using SQL!
Thank you

You might also like