Unit 03 - SQL Queries (1)
Unit 03 - SQL Queries (1)
SQL QUERIES
1. Introduction to SQL
2. Characteristics of SQL, advantages of SQL.
3. SQL data type and literals,
4. Types of SQL commands,
5. SQL operators and their procedure,
6. Tables, views and indexes,
7. Queries and subqueries,
8. Aggregate functions. [ Refer to Lab Experiment 03 ].
9. Insert, update and delete operations, [ Refer to Lab Experiment 02 ] .
10. Joins, Unions, Intersection, Set Difference, Triggers and Procedures in SQL.
[Introduction to SQL ] What is SQL ?
Structured query language (SQL) is a Declarative query language for storing and
processing information in a relational database.
A relational database stores information in tabular form, with rows and columns
representing different data attributes and the various relationships between the data
values.
You can use SQL statements to store, update, remove, search, and retrieve
information from the database. You can also use SQL to maintain and optimize
database performance.
Source - https://aws.amazon.com/what-is/sql/
History of SQL
SQL was invented in the 1970s based on the relational data model. It was
initially known as the structured English query language (SEQUEL). The term
was later shortened to SQL.
Source - https://aws.amazon.com/what-is/sql/
What are the components of a SQL system?
Examples
Source - https://aws.amazon.com/what-is/sql/
Characteristics of SQL
1. Declarative Language – SQL focuses on what data is needed rather than how to
retrieve it.
2. Standardized Language – It follows ANSI and ISO standards for database
management.
3. Portable – Can be used across different database systems like MySQL, PostgreSQL,
SQL Server, and Oracle.
4. User-Friendly – SQL is easier to learn compared to procedural languages.
5. Efficient Data Retrieval – Provides quick and optimized data retrieval using indexing
and optimization techniques.
6. Scalability – Suitable for both small and large-scale databases.
7. Security and Access Control – Supports role-based permissions, encryption, and
authentication.
Features of SQL
SQL provides various functionalities to manage data effectively:
✔ INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN – Combines data from multiple
tables.
✔ SELF JOIN – Joins a table with itself.
E. Advanced Functions
Source - https://dev.mysql.com/doc/refman/8.4/en/data-types.html
Numeric Data Types
Used for storing numbers, including integers and decimals.
Source - https://dev.mysql.com/doc/refman/8.4/en/numeric-types.html
Date and Time Data Types
Used for handling dates, times, and timestamps.
Source - https://dev.mysql.com/doc/refman/8.4/en/numeric-types.html
String Data Types
Used for storing text and character-based data.
Source - https://dev.mysql.com/doc/refman/8.4/en/numeric-types.html
Spatial Data Types
Used for geographical and spatial data representation.
The JSON Data Type
Used for storing JSON (JavaScript Object Notation) data in structured
form.
Types of SQL Commands
TRUNCATE – Removes all records from a table but keeps its structure.
Arithmetic Operators
Used for mathematical operations on numerical data.
Source : https://www.deepseek.com/
SQL Operators and their Usages ( Cont..)
Comparison Operators
Used for comparing values in conditions (used in WHERE, HAVING, etc.).
Source : https://www.deepseek.com/
SQL Operators and their Usages ( Cont..)
Logical Operators
Used for combining multiple conditions.
Source : https://www.deepseek.com/
SQL Operators and their Usages ( Cont..)
Bitwise Operators
Used to perform bit-level operations.
Source : https://www.deepseek.com/
SQL Operators and their Usages ( Cont..)
Special Operators
Used for pattern matching and checking NULL values.
Source : https://www.deepseek.com/
What is Table ?
Features of Views:
Employee01 View:
Note: This creates an index on the "Name" column, making searches faster.
Queries and Subqueries
A query is an operation that retrieves data from one or more tables or views.
In this reference, a top-level SELECT statement is called a query, and a query nested
within another SQL statement is called a subquery.
Example:
DBMS Team
The Big Picture
Extract
Transform
Load
33
Joining Multiple Tables
❑ A Join
– Combines data from multiple tables using foreign key references
❑ Syntax
SELECT column1, column2, …
FROM table1, table2
WHERE table1.joincolumn = table2.joincolumn
AND search_condition(s);
35
Inner Joins
❑ Simplest type of join
❑ Also called: Theta join, Equi-join, Natural join
❑ VALUES in one table equal to values in other table
❑ Query design diagram helps get the query right
37
Display column, search column, join column
❑ Display columns: appear in SELECT clause
❑ Search columns: appear in search condition
❑ Join columns: primary key and foreign key column on which you join the
tables.
❑ Linkage table: contains join column to link other tables through foreign
key values.
SELECT f_last
FROM faculty, course_section, term
WHERE faculty.f_id = course_section.f_id
AND course_section.term_id = term.term_id
AND term_desc = 'Summer 2007';
38
Deriving a SQL Query From a Query Design Diagram
39
Joins and Inference
● Chaining relations together is the basic inference
method in relational DBs. It produces new relations
(effectively new facts) from the data:
SELECT S.name, M.mortality
FROM Students S, Mortality M
WHERE S.Race=M.Race
SName Race
M
Race Mortality
Socrates Man Man Mortal
Thor God God Immortal
Barney Dinosaur Dinosaur Mortal
Blarney stone Stone Stone Non-living
Joins and Inference
● Chaining relations together is the basic inference
method in relational DBs. It produces new relations
(effectively new facts) from the data:
SELECT S.name, M.mortality
FROM Students S, Mortality M
WHERE S.Race=M.Race
Name Mortality
Socrates Mortal
Thor Immortal
Barney Mortal
Blarney stone Non-living
TYPES OF SQL JOIN OPERATIONS
INNER JOIN
OUTER JOIN
● LEFT OUTER JOIN
● RIGHT OUTER JOIN
● FULL OUTER JOIN
CROSS JOIN
THETA JOIN , EQUI JOIN AND NATURAL JOIN
JOIN TABLE OVERVIEW
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table
SQL Inner Joins
SELECT S.name, E.classid
FROM Students S (INNER) JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
Note the previous version of this query (with no join keyword) is an “Implicit join”
ANOTHER EXAMPLE:
SQL Inner Joins
SELECT S.name, E.classid
FROM Students S (INNER) JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194 Unmatched keys
Smith French150
What kind of Join is this?
SELECT S.name, E.classid
FROM Students S ?? Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
Brown NULL
SQL Joins
SELECT S.name, E.classid
FROM Students S LEFT OUTER JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
Brown NULL
ANOTHER EXAMPLE:
What kind of Join is this?
SELECT S.name, E.classid
FROM Students S ?? Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
NULL English10
SQL Joins
SELECT S.name, E.classid
FROM Students S RIGHT OUTER JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
NULL English10
SQL Joins
SELECT S.name, E.classid
FROM Students S ? JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
NULL English10
Brown NULL
SQL Joins
SELECT S.name, E.classid
FROM Students S FULL OUTER JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience194
Smith French150
NULL English10
Brown NULL
What kind of Join is this?
SELECT S.name, E.classid
FROM Students S ?? Enrolled E
ON S.sid=E.sid
E.sid E.classid
S E
S.name S.sid
Jones 11111 11111 History105
Smith 22222 11111 DataScience194
Brown 33333 22222 French150
44444 English10
S.name E.classid
Jones History105
Smith French150
SUMMARY
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left or
right table
What kind of Join is this?
SELECT *
FROM Students S ?? Enrolled E
S S.name
Jones
S.sid
11111
E E.sid
11111
E.classid
History105
Smith 22222 11111 DataScience194
22222 French150
Query:
Select person_fname, person_lname, studio_name
From Movies, People
Where studio_city = person_city
AND studio_state = person_state
SQL – More than two tables
Example: Get title, director, studio, city for all movies in the database
Schema:
Studios(studio_id, studio_state, studio_name, studio_city)
People(person_fname, person_lname, person_id, person_state, person_city)
Movies(movie_title, director_id, studio_id)
Query:
Select M.movie_title, M.studio_id, P.person_fname, P.person_lname, S.studio_city
From Movies M, People P, Studio S
Where M.director_id = P.person_id
AND M.studio_id = P.person_id
Aggregate Queries
Including reference counts in the lookup tables allows you to perform
aggregate queries on those tables alone:
Average age of users, most popular location,…
Tweet id User id Location id Body
11 111 1111 I need a Jamba Juice
22 111 1111 Cal Soccer rules
33 111 2222 Why do we procrastinate?
44 222 3333 Close your eyes and push “go”
b) A function used to combine data from two or more tables based on a related column
More Practices ..
SQL – Select
Select <List of Columns and expressions (usually involving columns)>
From <List of Tables & Join Operators>
Where <List of Row conditions joined together by And, Or, Not>
Group By <list of grouping columns>
Having <list of group conditions connected by And, Or, Not >
Order By <list of sorting specifications>
Conceptual Evaluation
From Tables: Cross
product and join 1
operations
Restriction on
where
conditions
2
Compute
By? Sort on aggregates Restriction
Group Group BY and reduce on HAVING
Yes columns each group conditions
No 3 to 1 row
5
Order 4
By? Sort
No
Yes columns in 6
ORDER BY
Project columns 7
in SELECT
finish
SQL – DISTINCT
• Eliminates all the duplicate entries in the table resulting from the query.
Syntax:
Select [DISTINCT] select_list
From table[, table, …]
[Where expression]
[Order By expression]
Example:
Select DISTINCT studio_id, director_id
From Movies
studio_id director_id
1 1
2 2
2 10
3 1
3 9
SQL – Order By
• Used to sort the results based on contents of a column
• Multiple levels of sort can be done by specifying multiple columns
• An expression can be used in Order By clause
Syntax:
Select function(column)
From table1 [, table2 …]
[Where condition]
[Order By {Column | alias | position} [ASC | DESC]]
SQL – Order By
Example: Sort Movies by profits in Ascending order
Select MovieTitle, Gross, Budget, (Gross – Budget) as profits
From movies
Order BY profits
Syntax:
Select column1, [column2, …]
From table [, table …]
[Where condition]
Group By column1, [column2, ….]
Having [Condition]
Aggregate Queries – Group By
Example: Get # of movies by each director for each studio
Select studio_id, director_id, count(*)
From Movies
Group By director_id, studio_id
Syntax:
Select function(column)
From <list of tables>
Where <condition>
Group By <list of columns>
Having <condition>
Aggregate Queries
• Functions:
– Sum() Returns a sum of the column
– Count() Returns a total number of rows returned by a query
– Avg() Returns the average of a column
– Min() Returns minimum value of the column returned by query
– Max() Returns maximum value of the column returned by query
Notes 1: Count function does not include columns containing null values in total
Notes 2: Count can be used with distinct to count the number of distinct rows
Example:
Query: Select sum(budget)
From movies
Where studio_id = 3
Output: Sum(budget)
---------------
65.1
Stored Procedure
Link:
https://docs.google.com/document/d/1XT13HWN9FfBvFEpM8jn7wmEkk4z33iDPoeai6zZXbjs/edit?
usp=sharing
A stored procedure is a precompiled SQL code block that can be executed manually with parameters.
Link:
https://docs.google.com/document/d/1XT13HWN9FfBvFEpM8jn7wmEkk4z33iDPoeai6zZXbjs/edit?usp=sha
ring
Difference between Trigger and Stored Procedure
End of Unit 03 : Feel free to ask questions !!