Final Fundamentals of SQL
Final Fundamentals of SQL
1
SQL
SQL, which stands for Structured Query Language, is
the standard language for relational database
management systems.
SQL is a non-procedural language: you specify what
information you require, rather than how to get it.
The software used to store, manage, query, and retrieve
data stored in a relational database is called a relational
database management system (RDBMS).
A relational database is a type of database that stores
and provides access to data points that are related to
one another.
2
Importance of SQL
Allows users to access data in the relational database
management systems.
Allows users to describe the data.
Allows users to define the data in a database and
manipulate that data.
Allows users to create and drop databases and tables.
3
Starting with SQL
1.Type ssms on the start menu and open sql server
management system (ssms is a relational database
management system that uses SQL to create and manipulate
databases)
2.when the connect to server dialogue box shows up, if all
the textboxes are already filled just say connect
3.Once you have opened the ssms, you’ll see on the left the
object explorer. And on the left you will find an open area
1.From the top menu, click on “new query”. This opens the
query window
2.The Query Window is the editing environment that we use to
edit and execute queries
3.That’s where we will be writing the SQL commands
4
Operations in SQL
SQL is in general divided into two groups of operations
known as Data Definition Language (DDL) and Data
Manipulation Language (DML).
As a language, SQL has two major components:
1. Data Definition Language (DDL) for defining
the database structure;
DDL statements are written using these three keywords:
CREATE, ALTER, and DROP
We will be starting with DDL commands
6
Data Types
Numeric (int, decimal, numeric, money, float, real…)
Date and Time (date (SQL stores date in 'YYYY-MM-
DD' format), datetime (SQL stores date and time
information in the format 'YYYY-MM-DD
HH:MM:SS'), time…)
Character and String (char, varchar, binary, text…)
7
Database Schema Design
Working with a Database
Creating a database
create database database_name
Deleting a database
drop database database_name
8
Creating a Table
CREATE TABLE book
(
isbn char(12),
title char(20),
author char(20),
publisher char(6)
)
9
Exercise 1
Create tables inside the School database for the
following entities and their associated attributes:
Student entity : has stud_id, fname, lname,
gender, age, contact_add, stud_email, stud_pass
Schedules entity : has sched_id, course_id,
ins_id, sub_id, stud_id, day, time_start, time_end
Courses entity : has course_id, course_name,
course_desc, school_yr
Subjects entity : has sub_id, name, course_id
10
End of week 0
11
How to backup and restore databases
[demo]
12
Database Schema Design…
Working with a Table
A table, in relational database, is a structure that represents
data in form of rows and columns. A database is basically
formed out of logically related sets of tables.
Creating a table
Use db_name
Create table table_name (
Column1 data_type,
Column2 data_type,
…
Primary key(column1,column2,…)
Foreign key(column) references ref_table(ref_column)
13
…
14
Database Schema Design…
Primary key and foreign key
Any table in SQL should have a primary key which is
used to uniquely identify a record in a table.
There is a logical relationship between and among
data in a database. Foreign key is a mechanism by
which tables are interconnected each other in a
relational database like SQL.
15
Author (AuthorId, FullName, TelNo, Email)
Primary key AuthorId
BookCategory (CategoryId, CategoryName) DB Name:
LMIS_3B
Primary key CategoryId
Book (ISBN, BTitle, NumPages, DatePublished, Publisher, CategoryId)
Primary Key ISBN
Foreign Key CategoryId references BookCategory (CategoryId)
BookAuthor (AuthorId, ISBN)
Primary key AuthorId, ISBN
Foreign key AuthorId references Author (AuthorId)
Foreign key ISBN references Book (ISBN)
Member (MemberId, FullName, TelNo, Email, DOB)
Primary key MemberId
Librarian (LID, FullName, DOB, DOE, StartingSalary, CurrentSalary, Position)
Primary key LID
BookLoan (MemberId, ISBN, LID, LoanDate, DueDate, Penality)
Primary key MemberId, ISBN, LID
Foreign key MemberId references Member (MemberId)
16 Foreign key ISBN references Book (ISBN)
Database Schema Diagram
17
End of week 1
18
Database Schema Design…
Defining constraints
A constraint is usually associated with a table and defines certain
properties that data in a database must comply with. Primary key,
foreign key, default, check, nullity and unique constraints.
Use db_name
Create table table_name (
Column1 data_type unique,
Column2 data_type not null,
Column3 data_type check (condition),
Column4 data_type default ‘default_value’
…
Primary key(column1,column2,…)
Foreign key(column) references ref_table(ref_column)
19
Defining Constraints
Check constraint is used in the example below for StartingSalary
field. Check constraint in general ensures the value entered for a
field is in agreement with the rule defined in the check
constraint.
Default Constraint is used in the example below for the position
field. Default constraint ensures that a field takes the value given
as default in case a value is not explicitly entered by the user.
Unique Constraint is used in the example below for the LID
field. Unique constraint as the name indicates, is a constraint that
ensures the value for each record of the table with regard to the
unique field is unique. A primary key constraint automatically
has a unique constraint.
Nullity constraint is used in the example below for the DOE
field. The not null specification enforces not to accept null
20
values for a column
Defining Constraints…
21
Database Schema Design…
Modifying table structure
you can add or remove columns, change the type of existing
columns, or rename columns or the table itself, add
constraint.
Alter table table_name
Alter column column_name
24
Manipulating Data in a Database
Inserting data into a table
Insert into table_name (column_list) values
(data value)
Or
Insert into table_name(column_list) values
(data value1),
(data value2),…
25
Librarian Table
26
Exercise 3
1. Write an SQL statement to insert a single record into the
Author table.
2. Write an SQL statement that inserts five records into the
Author table.
3. Write separate SQL statements to insert three records at
a time into the following tables:
a. Book
b. Book Category
c. Member
4. Write an SQL statement that inserts five records into all
the remaining tables
Note: Set the order of the insertion process in such a way that
the primary key tables come before the foreign key tables
27
End of week 3
28
Manipulating Data in a Database…
Retrieving information from a table
Selecting all data
Select * from table_name
Selecting Particular Rows
to display only those rows that satisfy certain conditions.
you have to modify the SELECT statement by adding
a where clause. A variety of operators can be in a
where clause.
Select * from table_name
Where condition
29
Manipulating Data in a Database…
Comparison operators
compare values of two operands. Equality (=), Greater
than (>), Less than (<), Greater than or equal to (>=),
Less than or equal to (<=), Not equal to (<>).
30
Manipulating Data in a Database…
Range operator (Between and Not Between)
Range operator checks if a value is within or outside a
range.
Select * from table_name
Where column_name between value1 and value2
31
Manipulating Data in a Database…
List membership operator (In and Not In)
The list membership operator checks if a value is in a list
or not in a list.
Select *from table_name
Where column_name in (‘value1’, ‘value2’,..)
32
Manipulating Data in a Database…
Pattern matching (Like and Not Like)
The LIKE keyword searches for character string, date, or
time values that match a specified pattern.
Select *from table_name
Where column_name like ‘character%’
33
Manipulating Data in a Database…
Nullity operator (Is NULL and IS NOT NULL)
IS NULL and ISNOTNULL operators check if the value
of a field is null or different from null respectively.
Select *from table_name
Where column_name is not null
34
Manipulating Data in a Database…
Logical operator (AND, OR , NOT)
The two operators AND and OR are used to connect two
or more expressions and form a bigger logical
expression in a where clause.
Select *from table_name
Where column condition and column condition
35
Exercise 4 (a)
1. Write a SELECT SQL statement that displays all
records from the Librarian table.
2. Write a SELECT SQL statement that displays all
Librarians whose current salary is greater than 5000
3. Write a SELECT SQL statement that displays all
Librarians whose current salary is between 6000 and
10000
4. Write a SELECT SQL statement that displays all
Librarians whose positions are Manager, clerks, staff
and IT
36
Exercise 4(b)
1. Write a SELECT SQL statement that displays all Books
whose title starts with the letter M
2. Write a SELECT SQL statement that displays all Book
category names that has the letter ‘F’
3. Write a SELECT SQL statement that displays all Librarian
whose DOB is empty
4. Write a SELECT SQL statement that displays all
Librarians whose currentSalary is over 1000 and whose
position is IT
5. Write a SELECT SQL statement that displays all
Librarians whose currentSalary is either over 1000 or
whose position is IT
37
End of week 4
38
Manipulating Data in a Database…
Selecting particular columns
When you want to see records of a table in terms of
some but not all columns.
39
Manipulating Data in a Database…
Sorting rows
You can sort your results using the ORDER BY clause
in your SQL statement. You can also choose the sort
direction: ascending or descending, by following
ORDER BY with either ASC (default) or DESC
depending on your choice.
40
Exercise 5(a)
1. Write a SELECT SQL statement that displays all
book titles and days the books were published from
the “Book” table
2. Write a SELECT SQL statement that displays the
Fullname and position of all librarians whose
currentSalary is over 4000
3. Write a SELECT SQL statement that displays all
librarians' ID, name, current salary, and position,
sorted by their salary from highest to lowest
41
Manipulating Data in a Database…
Selecting from multiple tables
When you want to get information that is collected from
two or more tables based on their relationship.
42
Exercise 5(b)
1. Write a SELECT SQL statement that displays ISBN,
BTitle, date published, and the category name of all
the books in the library
2. Write a SELECT SQL statement that displays the
ISBN and author names of all the books in the
library
3. Write a SELECT SQL statement that displays the list
of ‘database books’ along with the full name of
members aged between 20-35 who read the books.
43
Manipulating Data in a Database…
Aggregate functions
Aggregate functions are built-in system functions that
generate summary values for an expression.
SUM: generates sum value
AVG: generates average value
MAX: generates the maximum value
MIN: generates the minimum value
COUNT: generates a value that represents the number
of rows
Select agg_fun (column_name) as ‘Summary Name’ from
table_name
44
Exercise 5(c)
1. Find the minimum, maximum, and average of
Librarians’ salaries
2. How many librarians have salaries higher than 4500
per month?
3. Find the total number of assistant librarians and the
sum of their salaries
45
…
The GROUP BY statement groups rows that have
the same values into summary rows,
Eg., the number of customers in each country
The GROUP BY statement is used with aggregate
functions to group the result-set by one or more
columns. Eg.,
average salary from each department or
maximum salary from each department
Example,
SELECT MAX(salary) FROM Employee
GROUP BY EDID
46
Exercise 5 (d)
1. Write a SQL SELECT statement to retrieve the
minimum current salary for each specific position
from the librarian table
2. Write a SQL SELECT statement to retrieve the
'position' column and the number of assistant
librarians with the column name 'No. of Staff'.“
47
Takeaway questions
Write a SELECT SQL statement that displays name
and e-mail of people in the database with a gmail
account.
Write a SELECT SQL statement that displays the
oldest library staff.
Write a SELECT SQL statement that displays the
Number of Members who have taken more than one
book.
48
End of week 5
49
Manipulating Data in a Database…
Updating information in a table
used for changing values of records in a database.
Update table_name
Set column_name = value where condition
50
Exercise 6(a)
1. Adane changed his email address to
[email protected] . Update his information
accordingly
2. Increase the salary of all librarians by 5%
3. Write an UPDATE SQL statement that decreases the
current salary of a director of the library by 3%.
4. Write an UPDATE SQL statement that Increases
penalty of ICT books by 10%.
51
Manipulating Data in a Database…
Deleting information from a table
used for deleting records from a table.
52
Exercise 6(b)
1. Remove Fana Bekele from the librarian table
2. Delete the member “Adane Tefera” from the
members table
3. Delete book loan record of members whose penalty
is less than the average penalty of all members
4. Write a DELETE SQL statement that deletes record
of a librarian named Bekele Kebede.
5. Write a DELETE SQL statement that deletes a Book
authored by a single individual.
53
End of week 6
54
Joining tables
A JOIN clause is used to combine rows from two or
more tables, based on a related column between them
we use equality between primary key attributes and
foreign key attributes.
The General Syntax:
SELECT <attribute List>
FROM <table1> [ JOIN TYPE ] <table2>
ON <Join condition>
WHERE <additional Condition>
55
Different Types of SQL JOINs
(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
56
Different Types of SQL JOINs
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
57
Create a new database called SiS_DB
Employee table
Department table
58
What SQL query can be used to generate the
following resulting table?
59
What SQL query can be used to generate the
following resulting table?
60
What SQL query can be used to generate the
following resulting table?
61
What SQL query can be used to generate the
following resulting table?
62
Creating a view or virtual table
In SQL, a VIEW is a virtual table based on the result-
set of a SELECT 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.
General Syntax
CREATE VIEW <View_Name> AS
SELECT <attribute List>
FROM <Table_Name>
WHERE <Condition>
63
1. Create a view that displays all book titles and days
the books were published from the “Book” table
2. Create a view that displays the Fullname and
position of all librarians whose currentSalary is over
4000
3. Create a view that displays all librarians' ID, name,
current salary, and position, sorted by their salary
from highest to lowest
64
Thank You
65