Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Introduction. Table of Contents 1. SQL and T-SQL Languages 2. The “SoftUni” Database Schema 3. Introducing the SELECT SQL Statement  SQL Operators.

Similar presentations


Presentation on theme: "SQL Introduction. Table of Contents 1. SQL and T-SQL Languages 2. The “SoftUni” Database Schema 3. Introducing the SELECT SQL Statement  SQL Operators."— Presentation transcript:

1 SQL Introduction

2 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

3 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

4 Relational Databases and SQL The SQL Execution Model

5 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

6 Communicating with the DB 6 SQL command is sent to the DB server SELECT Name FROM Departments Name Engineering Sales Marketing … The result is returned (usually as a record set)

7 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

8 SQL and T-SQL Introduction

9 What is SQL?  Structured Query Language ( SQL ) – en.wikipedia.org/wiki/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

10 SQL – Few Examples 10 SELECT FirstName, LastName, JobTitle FROM Employees INSERT INTO Projects(Name, StartDate) VALUES('Introduction to SQL Course', '1/1/2006') SELECT * FROM Projects WHERE StartDate = '1/1/2006' UPDATE Projects SET EndDate = '8/31/2006' WHERE StartDate = '1/1/2006' DELETE FROM Projects WHERE StartDate = '1/1/2006'

11 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

12 T-SQL – Example 12 CREATE PROCEDURE EmpDump AS DECLARE @EmpId INT, @EmpFName NVARCHAR(100), @EmpLName NVARCHAR(100) DECLARE @EmpId INT, @EmpFName NVARCHAR(100), @EmpLName NVARCHAR(100) DECLARE emps CURSOR FOR DECLARE emps CURSOR FOR SELECT EmployeeID, FirstName, LastName FROM Employees SELECT EmployeeID, FirstName, LastName FROM Employees OPEN emps OPEN emps FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLName FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLName WHILE (@@FETCH_STATUS = 0) BEGIN WHILE (@@FETCH_STATUS = 0) BEGIN PRINT CAST(@EmpId AS VARCHAR(10)) + ' ' PRINT CAST(@EmpId AS VARCHAR(10)) + ' ' + @EmpFName + ' ' + @EmpLName + @EmpFName + ' ' + @EmpLName FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLName FETCH NEXT FROM emps INTO @EmpId, @EmpFName, @EmpLName END END CLOSE emps CLOSE emps DEALLOCATE emps DEALLOCATE empsGO

13 SQL Language Introducing the SELECT Statement

14 Capabilities of SQL SELECT 14 Table 1 Table 2 Selection Take a subset of the rows Projection Take a subset of the columns Join Combine tables by some column

15 The SoftUni Database Schema in SQL Server 15

16 Basic SELECT Statement  SELECT identifies what columns  FROM identifies which table 16 SELECT * | {[DISTINCT] column|expression [alias], …} FROM table

17 SELECT – Example  Selecting all columns from the "Departments" table  Selecting specific columns 17 SELECT * FROM Departments SELECT DepartmentId, Name DepartmentId, Name FROM Departments DepartmentIDNameManagerID 1Engineering12 2 Tool design 4 3Sales273 ……… DepartmentI D Name1Engineering 2 Tool design 3Sales ……

18 Arithmetic Operations  Arithmetic operators are available: +, -, *, /  Examples: 18 SELECT LastName, Salary, Salary + 300 FROM Employees LastNameSalary (No column name) Gilbert 12500.00 12800.00 Brown 13500.00 13800.00 Tamburello 43300.00 43600.00 ……… SELECT (2 + 3) * 4 --> returns 20

19 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 19 SELECT LastName, ManagerID FROM Employees LastNameManagerID SánchezNULL Duffy300 Wang1 …… NULL is displayed as empty string or as " NULL "

20 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 20 SELECT FirstName, LastName, Salary, Salary*0.2 AS Bonus, Salary * 0.2 / 12 AS "Monthly Bonus" FROM Employees FirstNameLastNameSalaryBonus Monthly Bonus GuyGilbert 12500.00 2500.00000208.33333333 KevinBrown 13500.00 2700.00000225.00000000 ……………

21 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 21 SELECT FirstName + ' ' + LastName AS [Full Name], EmployeeID as [No.] FROM Employees Full Name No. Guy Gilbert 1 Kevin Brown 2 Roberto Tamburello 3 ……

22 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' 22 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 …

23 Removing Duplicate Rows  By default SELECT returns all rows, including duplicate rows  Use DISTINCT keyword to eliminate duplicated rows: 23 SELECT DepartmentID FROM Employees DepartmentID 7 7 2... SELECT DISTINCT DepartmentID DISTINCT DepartmentID FROM Employees DepartmentID7 2...

24 Set Operations: UNION, INTERSECT and EXCEPT  UNION combines the results from several SELECT statements  The columns count and types should match  INTERSECT / EXCEPT perform logical intersection / difference between two sets of records 24 SELECT FirstName AS Name FROM Employees UNION SELECT LastName AS Name FROM Employees Name A. Scott Abbas Abercrombie...

25 Filtering the Selected Rows  Restrict the rows returned by using the WHERE clause:  More examples: 25 SELECT LastName, DepartmentID FROM Employees WHERE DepartmentID = 1 SELECT FirstName, LastName, DepartmentID FROM Employees WHERE LastName = 'Sullivan' LastName DepartmentI D Tamburell o 1 Erickson1 Goldberg1...... SELECT LastName, Salary FROM Employees WHERE Salary <= 20000

26 Other Comparison Conditions  Using BETWEEN operator to specify a range:  Using IN / NOT IN to specify a set of values:  Using LIKE operator to specify a pattern:  % means 0 or more chars; _ means one char 26 SELECT LastName, Salary FROM Employees WHERE Salary BETWEEN 20000 AND 22000 SELECT FirstName, LastName, ManagerID FROM Employees WHERE ManagerID IN (109, 3, 16) SELECT FirstName FROM Employees WHERE FirstName LIKE 'S%'

27 Comparing with NULL  Checking for NULL values:  Attention: COLUMN = NULL is always false ! 27 SELECT LastName, ManagerId FROM Employees WHERE ManagerId IS NULL SELECT LastName, ManagerId FROM Employees WHERE ManagerId IS NOT NULL SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID = NULL SELECT LAST_NAME, MANAGER_ID FROM EMPLOYEES WHERE NULL = NULL This is always false !

28 Logical Operators and Brackets  Using NOT, OR and AND operators and brackets: 28 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 (ManagerID = 3 OR ManagerID = 4) AND (Salary >= 20000 OR ManagerID IS NULL) (Salary >= 20000 OR ManagerID IS NULL)

29 Sorting with ORDER BY  Sort rows with the ORDER BY clause  ASC : ascending order, default  DESC : descending order 29 SELECT LastName, HireDate FROM Employees ORDER BY HireDate LastNameHireDateGilbert1998-07-31 Brown1999-02-26 Tamburello1999-12-12 …… SELECT LastName, HireDate FROM Employees ORDER BY HireDate DESC LastNameHireDateValdez2005-07-01 Tsoflias2005-07-01 Abbas2005-04-15 ……

30 Select with Paging in SQL Server  Select the first 5 rows only:  Select rows from 20 to 24: 30 SELECT TOP 5 * FROM Towns TownIDName 1Redmond 2Calgary 3Edmonds 4Seattle 5Bellevue SELECT * FROM Towns ORDER BY Name OFFSET 20 ROWS FETCH NEXT 5 ROWS ONLY TownIDName1Monroe 2Nevada 3 Newport Hills 4Ottawa 5Portland

31 SQL Language Joins: Selecting Data From Multiple Tables

32 Data from Multiple Tables  Sometimes you need data from several tables: 32 LastNam e DepartmentI D Duffy1 Abbas3 Galvin2 Name1 Engineerin g 2 Tool design 3Sales LastName DepartmentNam e DuffyEngineering Galvin Tool design AbbasSales

33 Cartesian Product  This will produce Cartesian product:  The result: 33 SELECT LastName, Name AS DepartmentName FROM Employees, Departments LastName DepartmentName Duffy Document Control Wang Sullivan DuffyEngineering WangEngineering ……

34 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

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

36 Inner Join with ON Clause  To specify a join conditions, use the INNER JOIN … ON clause 36 SELECT e.EmployeeID, e.LastName, e.DepartmentID, d.DepartmentID, d.Name AS DepartmentName d.DepartmentID, d.Name AS DepartmentName FROM Employees e INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID ON e.DepartmentID = d.DepartmentID EmployeeIDLastName DepartmentI D DepartmentName 1Gilbert77Production 2Brown44Marketing 3Tamburello11Engineering ……………

37 Equijoins  Equijoin == join conditions pushed down to the WHERE clause 37 SELECT e.EmployeeID, e.LastName, e.DepartmentID, d.DepartmentID, d.Name AS DepartmentName d.DepartmentID, d.Name AS DepartmentName FROM Employees e, Departments d WHERE e.DepartmentID = d.DepartmentID EmployeeIDLastName DepartmentI D DepartmentName 1Gilbert77Production 2Brown44Marketing 3Tamburello11Engineering ……………

38 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

39 INNER JOIN 39 SELECT e.LastName EmpLastName, m.EmployeeID MgrID, m.LastName MgrLastName m.EmployeeID MgrID, m.LastName MgrLastName FROM Employees e INNER JOIN Employees m ON e.ManagerID = m.EmployeeID ON e.ManagerID = m.EmployeeID EmpLastNameMgrIDMgrLastName Erickson3Tamburello Goldberg3Tamburello Duffy109Sánchez Johnson185Hill Higa185Hill Ford185Hill Maxwell21Krebs.........

40 LEFT OUTER JOIN 40 SELECT e.LastName EmpLastName, m.EmployeeID MgrID, m.LastName MgrLastName m.EmployeeID MgrID, m.LastName MgrLastName FROM Employees e LEFT OUTER JOIN Employees m ON e.ManagerID = m.EmployeeID ON e.ManagerID = m.EmployeeID EmpLastNameMgrIDMgrLastName SánchezNULLNULL Benshoof6Bradley Miller14Maxwell Okelberry16Brown Hill25Mu Frum184Richins Culbertson30 Barreto de Mattos.........

41 RIGHT OUTER JOIN 41 SELECT e.LastName EmpLastName, m.EmployeeID MgrID, m.LastName MgrLastName m.EmployeeID MgrID, m.LastName MgrLastName FROM Employees e RIGHT OUTER JOIN Employees m ON e.ManagerID = m.EmployeeID ON e.ManagerID = m.EmployeeID EmpLastNameMgrIDMgrLastName Lertpiriyasuwat38Liu NULL39Hines NULL40McKay Berglund41Wu Koenigsbauer123Hay NULL124Zabokritski NULL125Decker.........

42 FULL OUTER JOIN 42 SELECT e.LastName EmpLastName, m.EmployeeID MgrID, m.LastName MgrLastName m.EmployeeID MgrID, m.LastName MgrLastName FROM Employees e FULL OUTER JOIN Employees m ON e.ManagerID = m.EmployeeID ON e.ManagerID = m.EmployeeID EmpLastNameMgrIDMgrLastName SanchezNULLNULL ……… Cracium3Tamburello Gilbert16Brown ……… NULL17Hartwig NULL1Gilbert ………

43 Three-Way Joins  A three-way join is a join of three tables 43 SELECT e.FirstName, e.LastName, t.Name as Towns, a.AddressText t.Name as Towns, a.AddressText FROM Employees e JOIN Addresses a ON e.AddressID = a.AddressID JOIN Addresses a ON e.AddressID = a.AddressID JOIN Towns t ON a.TownID = t.TownID JOIN Towns t ON a.TownID = t.TownID FirstNameLastNameTownsAddressText GuyGilbertMonroe 7726 Driftwood Drive KevinBrownEverett 2294 West 39th St. RobertoTamburelloRedmond 8000 Crane Court............

44 Self-Join  Self-join means to join a table to itself 44 SELECT e.FirstName + ' ' + e.LastName + ' is managed by ' + m.LastName as Message ' 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 …

45 Cross Join  The CROSS JOIN clause produces the cross- product of two tables  Same as a Cartesian product, rarely used 45 SELECT LastName [Last Name], Name [Dept Name] FROM Employees CROSS JOIN Departments Last Name Dept Name Duffy Document Control Wang DuffyEngineering WangEngineering ……

46 Additional Conditions in Joins  You can apply additional conditions in the WHERE clause: 46 SELECT e.EmployeeID, e.LastName, e.DepartmentID, d.DepartmentID, d.Name AS DepartmentName d.DepartmentID, d.Name AS DepartmentName FROM Employees e INNER JOIN Departments d INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID ON e.DepartmentID = d.DepartmentID WHERE d.Name = 'Sales' EmployeeI D LastNam e DepartmentI D DepartmentName 268Jiang33Sales 273Welcker33Sales 275Blythe33Sales

47 Complex Join Conditions  Joins can use any Boolean expression in the ON clause: 47 SELECT e.FirstName, e.LastName, d.Name as DeptName FROM Employees e INNER JOIN Departments d INNER JOIN Departments d ON (e.DepartmentId = d.DepartmentId ON (e.DepartmentId = d.DepartmentId AND e.HireDate > '1/1/1999' AND e.HireDate > '1/1/1999' AND d.Name IN ('Sales', 'Finance')) AND d.Name IN ('Sales', 'Finance')) FirstNameLastNameDeptName DeborahPoeFinance WendyKahnFinance ………

48 SQL Language: INSERT Inserting Data in Tables

49 Inserting Data  The SQL INSERT command  INSERT INTO VALUES ( )  INSERT INTO ( ) VALUES ( )  INSERT INTO SELECT 49 INSERT INTO EmployeesProjects VALUES (229, 25) INSERT INTO Projects(Name, StartDate) VALUES ('New project', GETDATE()) INSERT INTO Projects(Name, StartDate) SELECT Name + ' Restructuring', GETDATE() SELECT Name + ' Restructuring', GETDATE() FROM Departments FROM Departments

50 Bulk Insert  Bulk insert multiple values through a single SQL command: 50 INSERT INTO EmployeesProjects VALUES (229, 1), (229, 1), (229, 2), (229, 2), (229, 3), (229, 3), (229, 4), (229, 4), (229, 5), (229, 5), (229, 6), (229, 6), (229, 8), (229, 8), (229, 9), (229, 9), (229, 10), (229, 10), (229, 26) (229, 26)

51 SQL Language: UPDATE Updating Data in Tables

52 Updating Data  The SQL UPDATE command  UPDATE SET WHERE  Note: Don't forget the WHERE clause! 52 UPDATE Employees SET LastName = 'Brown' WHERE EmployeeID = 1 UPDATE Employees SET Salary = Salary * 1.10, JobTitle = 'Senior ' + JobTitle WHERE DepartmentID = 3

53 Updating Joined Tables  We can update tables based on condition from joined tables 53 UPDATE Employees SET JobTitle = 'Senior ' + JobTitle FROM Employees e JOIN Departments d JOIN Departments d ON e.DepartmentID = d.DepartmentID ON e.DepartmentID = d.DepartmentID WHERE d.Name = 'Sales'

54 SQL Language: DELETE Deleting Data From Tables

55 Deleting Data  Deleting rows from a table  DELETE FROM WHERE  Note: Don’t forget the WHERE clause!  Delete all rows from a table at once (works faster than DELETE )  TRUNCATE TABLE 55 DELETE FROM Employees WHERE EmployeeID = 1 DELETE FROM Employees WHERE LastName LIKE 'S%' TRUNCATE TABLE Users

56 Deleting from Joined Tables  We can delete records from tables based on condition from joined tables 56 DELETE FROM Employees FROM Employees e JOIN Departments d JOIN Departments d ON e.DepartmentID = d.DepartmentID ON e.DepartmentID = d.DepartmentID WHERE d.Name = 'Sales'

57 MySQL Extensions to the Standard SQL

58 SQL Syntax in MySQL  Specific MySQL syntax for paging:  Commands for retrieving database metadata:  Database table maintenance commands: 58 SELECT * FROM city LIMIT 100, 10 SHOW DATABASES USE USE SHOW TABLES CHECK TABLE / REPAIR TABLE CHECK TABLE / REPAIR TABLE OPTIMIZE TABLE OPTIMIZE TABLE

59 SQL Syntax in MySQL (2)  Show table schema  Replace data (delete + insert)  Regular expression matching  Enumerations as column types 59 DESCRIBE DESCRIBE REPLACE INTO city(ID, Name, CountryCode, District, Population) VALUES(100000, 'Kaspichan', 'BGR', 'Shoumen', 3300); SELECT '0888123456' REGEXP '[0-9]+' CREATE TABLE Shirts (Name VARCHAR(20), Size ENUM('XS', 'S', 'M', 'L', 'XL'))


Download ppt "SQL Introduction. Table of Contents 1. SQL and T-SQL Languages 2. The “SoftUni” Database Schema 3. Introducing the SELECT SQL Statement  SQL Operators."

Similar presentations


Ads by Google