Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

SQL Introduction

Uploaded by

kqdkh9hbpr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

SQL Introduction

Uploaded by

kqdkh9hbpr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

SQL Introduction

 Structured Query Language


Table of Contents
1. SQL and T-SQL Languages
2. The “SoftUni” Database Schema
3. Introducing the SELECT SQL Statement
SQL Operators
Using UNION, INTERSECT, EXCEPT
The WHERE Clause
Sorting with ORDER BY
Working with NULL values

2
Table of Contents
4. Selecting Data From Multiple Tables
Cartesian Product
Inner Joins with ON Clause
Left, Right and Full Outer Joins
Cross Joins
5. Inserting Data – INSERT
6. Modifying Data – UPDATE
7. Deleting Data – DELETE

3
Relational Databases
and SQL
The SQL Execution Model
Relational Databases and SQL

A relational database (RDBMS) can be


accessed and modified by executing SQL
statements
 DML commands: searching / modifying table data rows
 DDL commands: defining / modifying the database schema
 SQL commands may return
 A record set (table), e.g. SELECT * FROM TABLE
 A single value, e.g. SELECT COUNT(*) FROM TABLE
 Nothing, e.g. CREATE TABLE …
5
Communicating with the DB
SQL command is
sent to the DB se
SELECT Name rver
FROM Departments Database

Name
Engineering
t i s re tu rned
Sales The resul o rd set)
a re c
Marketing (usually as

6
SQL Execution

 SQL commands are executed through a database connection


 DB connection is a channel between the client and the SQL server
 DB connections take resources and should be closed when no longer used
 RDBMS systems are multi-user
 Multiple clients can be connected to the SQL server concurrently
 SQL commands can be executed in parallel
 Transactions and isolation deal with concurrency

7
SQL and T-SQL
Introduction
What is SQL?

Structured Query Language (SQL) –


en.wikipedia.org/wiki/SQL
 Declarative language for query and manipulation of relational data
 SQL consists of:
 Data Manipulation Language (DML)

 SELECT, INSERT, UPDATE, DELETE


 Data Definition Language (DDL)

 CREATE, DROP, ALTER


 Data Control Language (DCL)

 GRANT, REVOKE
9
SQL – Few Examples
SELECT FirstName, LastName, JobTitle FROM Employees

SELECT * FROM Projects WHERE StartDate = '1/1/2006'

INSERT INTO Projects(Name, StartDate)


VALUES('Introduction to SQL Course', '1/1/2006')

UPDATE Projects
SET EndDate = '8/31/2006'
WHERE StartDate = '1/1/2006'

DELETE FROM Projects


WHERE StartDate = '1/1/2006' 10
What is T-SQL?

 Transact SQL (T-SQL) is an


 Extension to the standard SQL language
 Used as standard in MS SQL Server
 Supports if statements, loops, exceptions
 T-SQL is designed for writing logic inside the database:
 Database stored procedures
 Database functions
 Database triggers

11
T-SQL – Example
CREATE PROCEDURE EmpDump AS
DECLARE @EmpId INT, @EmpFName NVARCHAR(100), @EmpLName NVARCHAR(100)
DECLARE emps CURSOR FOR
SELECT EmployeeID, FirstName, LastName FROM Employees
OPEN emps
FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLName
WHILE (@@FETCH_STATUS = 0) BEGIN
PRINT CAST(@EmpId AS VARCHAR(10)) + ' '
+ @EmpFName + ' ' + @EmpLName
FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLName
END
CLOSE emps
DEALLOCATE emps
GO 12
SQL Language
Introducing the SELECT Statement
Capabilities of SQL SELECT
Projection Selection
Take a subset of the columns Take a subset of the rows

Join
Combine tables
by
some column Table 1 Table14 2
The SoftUni Database Schema in SQL
Server

15
Basic SELECT Statement

 SELECT identifies what columns


 FROM identifies which table

SELECT * | {[DISTINCT] column|expression [alias], …}


FROM table

16

SELECT – Example
Selecting all columns from the "Departments" table

SELECT * FROM Departments


DepartmentID Name ManagerID
1 Engineering 12
2 Tool design 4
3 Sales 273
… … …

 Selecting specific columns DepartmentI Name


D
SELECT 1 Engineering
DepartmentId, Name 2 Tool design
FROM Departments 3 Sales 17

… …
Arithmetic Operations

 Arithmetic operators are available: +, -, *, /


 Examples: SELECT (2 + 3) * 4 --> returns 20

SELECT LastName, Salary, Salary + 300


FROM Employees

LastName Salary (No column name)


Gilbert 12500.00 12800.00
Brown 13500.00 13800.00
Tamburello 43300.00 43600.00
… … … 18
The NULL Value
A NULL is a special value that means unavailable / unassigned
/ unknown / inapplicable / missing value
Not the same as 0 or a blank space
 Arithmetic expressions containing a NULL value are evaluated to
NULL
SELECT LastName, ManagerID FROM Employees

LastName ManagerID
NULL
NULL is displayed as
Sánchez
empty string or as
Duffy 300
"NULL"
Wang 1
… … 19
Column Aliases
 Aliases rename a column heading
 Immediately follows the column name (an
optional AS keyword)
 Use "Some Name" or [Some Name] when the alias
contains spaces
SELECT FirstName, LastName, Salary, Salary*0.2 AS Bonus,
Salary * 0.2 / 12 AS "Monthly Bonus" FROM Employees

FirstName LastName Salary Bonus Monthly Bonus


Guy Gilbert 12500.00 2500.00000 208.33333333
Kevin Brown 13500.00 2700.00000 225.00000000
… … … … …
20
Concatenation Operator
 Concatenates columns or character strings to other columns
Represented by the plus sign “+” (or "||" in some databases)
 Creates a resultant column that is a character expression
SELECT FirstName + ' ' + LastName AS [Full Name],
EmployeeID as [No.] FROM Employees

Full Name No.


Guy Gilbert 1
Kevin Brown 2
Roberto Tamburello 3
… … 21
Literal Character Strings
 A literal is a character / number / date included in the SELECT
 Date and character literal values must be enclosed within single quotation
marks, e.g. 'some string', '25-Jan-2015'

SELECT FirstName + '''s last name is ' +


LastName AS [Our Employees] FROM Employees

Our Employees
Guy's last name is Gilbert
Kevin's last name is Brown
Roberto's last name is Tamburello

22
Removing Duplicate Rows
 By default SELECT returns all rows, including duplicate rows

DepartmentID
7
SELECT DepartmentID 7
FROM Employees
2
 Use DISTINCT keyword to eliminate duplicated rows: ...

DepartmentID
SELECT 7
DISTINCT DepartmentID
2
FROM Employees
... 23
Set Operations: UNION, INTERSECT and
EXCEPT
 UNION combines the results from several SELECT statements
 The columns count and types should match
Name
SELECT FirstName AS Name FROM Employees A. Scott
UNION Abbas
SELECT LastName AS Name FROM Employees Abercrombie

...
INTERSECT / EXCEPT perform logical intersection / difference between two
sets of records

24
Filtering the Selected Rows

LastName DepartmentI
Restrict the rows returned by using the WHERE clause:
D
Tamburell 1
SELECT LastName, DepartmentID o
FROM Employees Erickson 1
WHERE DepartmentID = 1
Goldberg 1
 More examples:
... ...

SELECT FirstName, LastName, DepartmentID FROM


Employees WHERE LastName = 'Sullivan'

SELECT LastName, Salary FROM Employees


WHERE Salary <= 20000 25
Other Comparison Conditions
 Using BETWEEN operator to specify a range:

SELECT LastName, Salary FROM Employees


WHERE Salary BETWEEN 20000 AND 22000
 Using IN / NOT IN to specify a set of values:

SELECT FirstName, LastName, ManagerID FROM Employees


WHERE ManagerID IN (109, 3, 16)
 Using LIKE operator to specify a pattern:

 % means 0 or more chars; _ means one char


SELECT FirstName FROM Employees
WHERE FirstName LIKE 'S%'
26
Comparing with NULL
 Checking for NULL values:

SELECT LastName, ManagerId FROM Employees


WHERE ManagerId IS NULL

SELECT LastName, ManagerId FROM Employees


WHERE ManagerId IS NOT NULL

 Attention: COLUMN = NULL is always false!

SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES


WHERE MANAGER_ID = NULL This is always false !
SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES
WHERE NULL = NULL This is always false !
27
Logical Operators and Brackets
 Using NOT, OR and AND operators and brackets:

SELECT FirstName, LastName FROM Employees


WHERE Salary >= 20000 AND LastName LIKE 'C%'

SELECT LastName FROM Employees


WHERE ManagerID IS NOT NULL OR LastName LIKE '%so_'

SELECT LastName FROM Employees


WHERE NOT (ManagerID = 3 OR ManagerID = 4)

SELECT FirstName, LastName FROM Employees


WHERE
(ManagerID = 3 OR ManagerID = 4) AND
(Salary >= 20000 OR ManagerID IS NULL) 28
Sorting with ORDER BY
 Sort rows with the ORDER BY clause
 ASC: ascending order, default
 DESC: descending order LastName HireDate
Gilbert 1998-07-31
Brown 1999-02-26
SELECT LastName, HireDate FROM Tamburello 1999-12-12
Employees ORDER BY HireDate … …

LastName HireDate
Valdez 2005-07-01
SELECT LastName, HireDate FROM Tsoflias 2005-07-01
Employees ORDER BY HireDate DESC Abbas 2005-04-15
… 29

Select with Paging in SQL Server
TownID Name
1 Redmond
 Select the first 5 rows only: 2 Calgary
3 Edmonds
SELECT TOP 5 * FROM Towns
4 Seattle
 Select rows from 20 to 24: 5 Bellevue

TownID Name
SELECT * FROM Towns 1 Monroe
ORDER BY Name 2 Nevada
OFFSET 20 ROWS 3 Newport Hills
FETCH NEXT 5 ROWS ONLY 4 Ottawa
5 30Portland
SQL Language
Joins: Selecting Data From Multiple Tables
Data from Multiple Tables
DepartmentI Name
 Sometimes you need data from several tables:
D
1 Engineerin
LastNam DepartmentI g
e D 2 Tool design
Duffy 1 3 Sales
Abbas 3
Galvin 2
LastName DepartmentNam
e
Duffy Engineering
Galvin Tool design
Abbas Sales 32
Cartesian Product
 This will produce Cartesian product:

SELECT LastName, Name AS DepartmentName


FROM Employees, Departments

 The result:
LastName DepartmentName
Duffy Document Control
Wang Document Control
Sullivan Document Control
Duffy Engineering
Wang Engineering
… … 33
Cartesian Product (2)

 A Cartesian product is formed when:


 A join condition is omitted
 A join condition is invalid
 All rows in the first table are joined to all rows in the second table
 To avoid a Cartesian product, always include a valid join condition

34
Types of Joins
Inner joins
Left, right and full outer joins
Cross joins

35
Inner Join with ON Clause
 To specify a join conditions, use the INNER JOIN … ON clause

SELECT e.EmployeeID, e.LastName, e.DepartmentID,


d.DepartmentID, d.Name AS DepartmentName
FROM Employees e INNER JOIN Departments d
ON e.DepartmentID = d.DepartmentID

DepartmentI DepartmentI
EmployeeID LastName DepartmentName
D D
1 Gilbert 7 7 Production
2 Brown 4 4 Marketing
3 Tamburello 1 1 Engineering
36
… … … … …
Equijoins
 Equijoin == join conditions pushed down to the WHERE clause

SELECT e.EmployeeID, e.LastName, e.DepartmentID,


d.DepartmentID, d.Name AS DepartmentName
FROM Employees e, Departments d
WHERE e.DepartmentID = d.DepartmentID

DepartmentI DepartmentI
EmployeeID LastName DepartmentName
D D
1 Gilbert 7 7 Production
2 Brown 4 4 Marketing
3 Tamburello 1 1 Engineering
37
… … … … …
INNER vs. OUTER Joins

 Inner join
 A join of two tables returning only rows matching the join condition
 Left (or right) outer join
 Returns the results of the inner join as well as unmatched rows from the left (or
right) table
 Full outer join
 Returns the results of an inner join along with al unmatched rows

38
INNER JOIN
SELECT e.LastName EmpLastName,
m.EmployeeID MgrID, m.LastName MgrLastName
FROM Employees e INNER JOIN Employees m
ON e.ManagerID = m.EmployeeID

EmpLastName MgrID MgrLastName


Erickson 3 Tamburello
Goldberg 3 Tamburello
Duffy 109 Sánchez
Johnson 185 Hill
Higa 185 Hill
Ford 185 Hill
Maxwell 21 Krebs
... ... ... 39
LEFT OUTER JOIN
SELECT e.LastName EmpLastName,
m.EmployeeID MgrID, m.LastName MgrLastName
FROM Employees e LEFT OUTER JOIN Employees m
ON e.ManagerID = m.EmployeeID

EmpLastName MgrID MgrLastName


Sánchez NULL NULL
Benshoof 6 Bradley
Miller 14 Maxwell
Okelberry 16 Brown
Hill 25 Mu
Frum 184 Richins
Culbertson 30 Barreto de Mattos
... ... ... 40
RIGHT OUTER JOIN
SELECT e.LastName EmpLastName,
m.EmployeeID MgrID, m.LastName MgrLastName
FROM Employees e RIGHT OUTER JOIN Employees m
ON e.ManagerID = m.EmployeeID

EmpLastName MgrID MgrLastName


Lertpiriyasuwat 38 Liu
NULL 39 Hines
NULL 40 McKay
Berglund 41 Wu
Koenigsbauer 123 Hay
NULL 124 Zabokritski
NULL 125 Decker
... ... ... 41
FULL OUTER JOIN
SELECT e.LastName EmpLastName,
m.EmployeeID MgrID, m.LastName MgrLastName
FROM Employees e FULL OUTER JOIN Employees m
ON e.ManagerID = m.EmployeeID

EmpLastName MgrID MgrLastName


Sanchez NULL NULL
… … …
Cracium 3 Tamburello
Gilbert 16 Brown
… … …
NULL 17 Hartwig
NULL 1 Gilbert
… … … 42
Three-Way Joins
 A three-way join is a join of three tables

SELECT e.FirstName, e.LastName,


t.Name as Towns, a.AddressText
FROM Employees e
JOIN Addresses a ON e.AddressID = a.AddressID
JOIN Towns t ON a.TownID = t.TownID

FirstName LastName Towns AddressText


Guy Gilbert Monroe 7726 Driftwood Drive
Kevin Brown Everett 2294 West 39th St.
Roberto Tamburello Redmond 8000 Crane Court
... ... ... ... 43
Self-Join
 Self-join means to join a table to itself

SELECT e.FirstName + ' ' + e.LastName +


' is managed by ' + m.LastName as Message
FROM Employees e JOIN Employees m
ON (e.ManagerId = m.EmployeeId)

Message
Ovidiu Cracium is managed by Tamburello
Michael Sullivan is managed by Tamburello
Sharon Salavaria is managed by Tamburello
Dylan Miller is managed by Tamburello
… 44
Cross Join
 TheCROSS JOIN clause produces the cross-
product of two tables
Same as a Cartesian product, rarely used
SELECT LastName [Last Name], Name [Dept Name]
FROM Employees CROSS JOIN Departments

Last Name Dept Name


Duffy Document Control
Wang Document Control
Duffy Engineering
Wang Engineering
… … 45
Additional Conditions in Joins
 You can apply additional conditions in the WHERE clause:

SELECT e.EmployeeID, e.LastName, e.DepartmentID,


d.DepartmentID, d.Name AS DepartmentName
FROM Employees e
INNER JOIN Departments d
ON e.DepartmentID = d.DepartmentID
WHERE d.Name = 'Sales'

EmployeeI LastNam DepartmentI DepartmentI


DepartmentName
D e D D
268 Jiang 3 3 Sales
273 Welcker 3 3 Sales46
275 Blythe 3 3 Sales
Complex Join Conditions
 Joins can use any Boolean expression in the ON clause:

SELECT e.FirstName, e.LastName, d.Name as DeptName


FROM Employees e
INNER JOIN Departments d
ON (e.DepartmentId = d.DepartmentId
AND e.HireDate > '1/1/1999'
AND d.Name IN ('Sales', 'Finance'))

FirstName LastName DeptName


Deborah Poe Finance
Wendy Kahn Finance
… … … 47
SQL Language: INSERT
Inserting Data in Tables
Inserting Data
 The SQL INSERT command
 INSERT INTO <table> VALUES (<values>)
 INSERT INTO <table>(<columns>) VALUES
(<values>)
 INSERT INTO <table> SELECT <values>

INSERT INTO EmployeesProjects VALUES (229, 25)


INSERT INTO Projects(Name, StartDate)
VALUES ('New project', GETDATE())
INSERT INTO Projects(Name, StartDate)
SELECT Name + ' Restructuring', GETDATE()
FROM Departments 49
Bulk Insert
 Bulk insert multiple values through a single SQL command:

INSERT INTO EmployeesProjects VALUES


(229, 1),
(229, 2),
(229, 3),
(229, 4),
(229, 5),
(229, 6),
(229, 8),
(229, 9),
(229, 10),
(229, 26) 50
SQL Language: UPDATE
Updating Data in Tables
Updating Data

 The SQL UPDATE command


 UPDATE <table> SET <column=expression>
WHERE <condition>
 Note: Don't forget the WHERE clause!

UPDATE Employees
SET LastName = 'Brown'
WHERE EmployeeID = 1
UPDATE Employees
SET Salary = Salary * 1.10, JobTitle = 'Senior ' + JobTitle
WHERE DepartmentID = 3 52
Updating Joined Tables
 We can update tables based on condition from joined tables

UPDATE Employees
SET JobTitle = 'Senior ' + JobTitle
FROM Employees e
JOIN Departments d
ON e.DepartmentID = d.DepartmentID
WHERE d.Name = 'Sales'

53
SQL Language: DELETE
Deleting Data From Tables
Deleting Data
 Deleting rows from a table
 DELETE FROM <table> WHERE <condition>

DELETE FROM Employees WHERE EmployeeID = 1


DELETE FROM Employees WHERE LastName LIKE 'S%'

 Note: Don’t forget the WHERE clause!


 Delete all rows from a table at once (works faster than DELETE)
 TRUNCATE TABLE <table>

TRUNCATE TABLE Users 55


Deleting from Joined Tables
 We can delete records from tables based on condition from joined tables

DELETE FROM Employees


FROM Employees e
JOIN Departments d
ON e.DepartmentID = d.DepartmentID
WHERE d.Name = 'Sales'

56
SQL Syntax in MySQL
MySQL Extensions to the Standard SQL
SQL Syntax in MySQL
SELECT * FROM city LIMIT 100, 10

 Specific MySQL syntax for paging:


SHOW DATABASES
 Commands for retrieving database metadata:
USE <database>

SHOW TABLES

CHECK TABLE <table> / REPAIR TABLE <table>

OPTIMIZE TABLE <table>


58


SQL Syntax in MySQL (2)
 Show table schema
DESCRIBE <table_name>
 Replace data (delete + insert)
REPLACE INTO city(ID, Name, CountryCode, District, Population)
VALUES(100000, 'Kaspichan', 'BGR', 'Shoumen', 3300);
 Regular expression matching
SELECT '0888123456' REGEXP '[0-9]+'
 Enumerations as column types

CREATE TABLE Shirts (Name VARCHAR(20),


59
Size ENUM('XS', 'S', 'M', 'L', 'XL'))

You might also like