Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamental of Database Systems

Similar presentations


Presentation on theme: "Fundamental of Database Systems"— Presentation transcript:

1 Fundamental of Database Systems 1401312-3
By Dr Abdullah Alzahrani د. عبدالله الزهراني SQL Queries

2 Reference الكتاب المرجع
Fundamentals of Database Systems, 5th ed., by Elmasri and Navathe, Pearson International Edition, Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

3 SQL Queries Outlines: SQL queries: Attribute Data Types Nulls
3-valued logic Select Ordering JOIN Aggregate functions Grouping Sub-queries Some of the materials and examples are taken from: and the reference book Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

4 SQL Queries Attribute Data Types: Numeric: Character-string:
includes integer numbers of various sizes (INTEGER or INT, and SMALLINT) and floating-point (real) numbers of various precision (FLOAT or REAL, and DOUBLE PRECISION). Formatted numbers can be declared by using DECIMAL(i,j)—or DEC(i,j) or NUMERIC(i,j)—where i, the precision, is the total number of decimal digits and j, the scale, is the number of digits after the decimal point. The default for scale is zero, and the default for precision is implementation- defined Character-string: either fixed length {CHAR(n) or CHARACTER(n)}, where n is the number of characters or varying length {VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n)}, where n is the maximum number of characters. When specifying a literal string value, it is placed between single quotation marks (apostrophes), and it is case sensitive (a distinction is made between uppercase and lowercase). Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

5 SQL Queries Attribute Data Types: Boolean: DATE TIME
has the traditional values of TRUE or FALSE. In SQL, because of the presence of NULL values, a three-valued logic is used, so a third possible value for a Boolean data type is UNKNOWN. DATE data type has ten positions, and its components are YEAR, MONTH, and DAY in the form YYYY-MM-DD. Only valid dates and times should be allowed by the SQL implementation. This implies that months should be between 1 and 12 and dates must be between 1 and 31 TIME The TIME data type has at least eight positions, with the components HOUR,MINUTE, and SECOND in the form HH:MM:SS. Only valid dates and times should be allowed by the SQL implementation. Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

6 SQL Queries Nulls: An important concept is that of NULL values, which are used to represent the values of attributes that may be unknown, do not exist, or may not apply to a tuple. A special value, called NULL, is used in these cases. For example, Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

7 SQL Queries Three-Valued Logic (3-Valued )
SQL has various rules for dealing with NULL values. NULL is used to represent a missing value, but that it usually has one of three different interpretations value unknown(exists but is not known), value not available(exists but is purposely withheld), value not applicable(the attribute is undefined for this tuple). Consider the following examples to illustrate each of the meanings of NULL. Unknown value. A person’s date of birth is not known, so it is represented by NULL in the database. Unavailable or withheld value. A person has a home phone but does not want it to be listed, so it is withheld and represented as NULL in the database. Not applicable attribute. An attribute LastCollegeDegree would be NULL for a person who has no college degrees because it does not apply to that person. It is often not possible to determine which of the meanings is intended; for example, a NULL for the home phone of a person can have any of the three meanings. Hence, SQL does not distinguish between the different meanings of NULL. Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

8 SQL Queries SELECT is used to retrieve rows selected from one or more tables, and can include UNION statements and subqueries. The basic form of the SELECT statement, sometimes called a mapping or a select-from-where block, is formed of the three clauses SELECT, FROM, and WHERE and has the following form: SELECT <attribute list> FROM <table list> WHERE <condition> ; Where: <attribute list> is a list of attribute names whose values are to be retrieved by the query. <table list> is a list of the relation names required to process the query. <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved by the query. Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

9 SQL Queries Customers" table: CustomerID CustomerName ContactName
Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

10 SQL Queries SELECT Column Example SELECT * Example
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table: Example #1 SELECT CustomerName,City FROM Customers; SELECT * Example The following SQL statement selects all the columns from the "Customers" table: Example #2 SELECT * FROM Customers; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

11 SQL Queries Example #1 Results Example #2 Results CustomerID
CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden Example #2 Results Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

12 SQL Queries SELECT with WHERE Clause
The WHERE clause is used to extract only those records that fulfil a specified criterion. SELECT with WHERE Clause (Text Fields) The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table: Example #3 SELECT * FROM Customers WHERE Country='Mexico'; SELECT with WHERE Clause (Numeric Fields) SQL requires single quotes around text values (most database systems will also allow double quotes). However, numeric fields should not be enclosed in quotes: Example #4 SELECT * FROM Customers WHERE CustomerID=1; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

13 SQL Queries Example #3 Results Example #4 Results CustomerID
CustomerName ContactName Address City PostalCode Country 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 Example #4 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

14 SQL Queries The AND & OR operators in SELECT with WHERE Clause
The AND & OR operators are used to filter records based on more than one condition The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. The following SQL statement selects all customers from the country "Germany" AND the city "Berlin", in the "Customers" table: Example #5 SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; The following SQL statement selects all customers from the city "Berlin" OR "'London", in the "Customers" table: Example #6 SELECT * FROM Customers WHERE City='Berlin‘ OR City='London'; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

15 SQL Queries Example #5 Results Example #6 Results CustomerID
CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany Example #6 Results CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

16 SQL Queries Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa 9/20/2016
Fundamental of Database Systems 9/20/2016

17 SQL Queries Operators with WHERE Clause examples
<> not equal operator The following SQL statement selects all the customers from the any country EXCEPT "Mexico", in the "Customers" table: Example #W.1 SELECT * FROM Customers WHERE Country <> 'Mexico'; BETWEEN operator The following SQL statement selects all the customers whose ID numbers BETWEEN 3 and 4, in the "Customers" table: Example #W.2 SELECT * FROM Customers WHERE CustomerID BETWEEN 3 and 4; IN operator The following SQL statement selects all the customers whose ID numbers IN the set (“Mexico”, “Sweden”), in the "Customers" table: Example #W.3 SELECT * FROM Customers WHERE Country IN (“Mexico”, “Sweden”); Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

18 SQL Queries Customers" table: CustomerID CustomerName ContactName
Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

19 SQL Queries Example #W.1 Results Example #W.2 Results
CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden Example #W.2 Results CustomerID CustomerName ContactName Address City PostalCode Country 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #W.3 Results CustomerID CustomerName ContactName Address City PostalCode Country 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 05023 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

20 SQL Queries Operators with WHERE Clause examples LIKE operator
Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern. Example #W.4.1 The following SQL statement selects all customers with a PostalCode starting with the letters “WA” , in the "Customers" table: SELECT * FROM Customers WHERE PostalCode LIKE “WA%”; Example #W.4.2 The following SQL statement selects all customers with a ContactName ending with the letters “ardy” , in the "Customers" table: SELECT * FROM Customers WHERE ContactName LIKE “%ardy” ; Example #W.4.3 The following SQL statement selects all customers with a CustomerName containing “Moreno” , in the "Customers" table: SELECT * FROM Customers WHERECustomerName LIKE “%Moreno%” ; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

21 SQL Queries Example #W.4.1 Results Example #W.4.2 Results
CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #W.4.2 Results CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #W.4.3 Results CustomerID CustomerName ContactName Address City PostalCode Country 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

22 SQL Queries Ordering of Query Results
SQL allows the user to order the tuples in the result of a query by the values of one or more of the attributes that appear in the query result, by using the ORDER BY clause. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. General form when using ORDER BY SELECT column_name, column_name FROM table_name ORDER BY column_name ASC|DESC, column_name ASC|DESC; The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column: Example #7 SELECT * FROM Customers ORDER BY Country; The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by the "Country" column: Example #8 SELECT * FROM Customers ORDER BY Country DESC; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

23 SQL Queries Example #7 Results Example #8 Results CustomerID
CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 5023 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK Example #8 Results CustomerID CustomerName ContactName Address City PostalCode Country 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S Sweden 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 5021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 5023 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

24 SQL Queries JOIN An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN returns all rows from multiple tables where the join condition is met. The types of the different SQL JOINs you can use: INNER JOIN: Returns all rows when there is at least one match in BOTH tables LEFT JOIN: Return all rows from the left table, and the matched rows from the right table RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table FULL JOIN: Return all rows when there is a match in ONE of the tables Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

25 SQL Queries Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa 9/20/2016
Fundamental of Database Systems 9/20/2016

26 SQL Queries Examples of JOINS Common attribute
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

27 SQL Queries Natural JOIN Examples of JOINS Example #9
select first_name, ,order_id, order_date, amount from customers c join orders on c.customer_id = orders.customer_id where c.customer_id = 3 Here, we’re joining the two tables using the join keyword, and specifying what key to use when joining the tables in the on customers.customer_id = orders.customer_id line following the join statement. Here is the result of the above SQL query, which includes two orders placed by Thomas Jefferson (customer_id = 3): Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

28 SQL Queries Examples of JOINS Example #9 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

29 SQL Queries Inner JOIN Examples of JOINS Example #10
select first_name, last_name, order_date, amount from customers c inner join orders o on c.customer_id = o.customer_id Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

30 SQL Queries Examples of JOINS Example #10 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

31 SQL Queries LEFT JOIN Examples of JOINS Example #11
select first_name, last_name, order_date, amount from customers c left join orders o on c.customer_id = o.customer_id Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

32 SQL Queries Examples of JOINS Example #11 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

33 SQL Queries RIGHT JOIN Examples of JOINS Example #12
select first_name, last_name, order_date, amount from customers c right join orders o on c.customer_id = o.customer_id Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

34 SQL Queries Examples of JOINS Example #12 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

35 SQL Queries SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions: AVG() - Returns the average value COUNT() - Returns the number of rows MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

36 SQL Queries Examples of SQL Aggregate Functions
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

37 SQL Queries SQL Aggregate Functions AVG() General form: Example #13
SELECT AVG(column_name) FROM table_name Example #13 The following SQL statement gets the average value of the “Amount" column from the “Orders" table: SELECT AVG(Amount) AS PriceAverage FROM Orders; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

38 SQL Queries Examples of SQL Aggregate Functions Example #13 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

39 SQL Queries SQL Aggregate Functions COUNT() General form:
SELECT COUNT(column_name) FROM table_name The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column SELECT COUNT(DISTINCT column_name) FROM table_name; SELECT COUNT(*) FROM table_name; The COUNT(*) function returns the number of records in a table Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

40 SQL Queries SQL Aggregate Functions COUNT() Example #14 Example #15
The following SQL statement counts the number of orders for "CustomerID"=3 from the "Orders" table: SELECT COUNT(Customer_ID) AS OrdersFromCustomerID3 FROM Orders WHERE Customer_ID=3; Example #15 The following SQL statement counts the total number of orders in the "Orders" table: SELECT COUNT(*) AS NumberOfOrders FROM Orders; Example #16 The following SQL statement counts the number of unique customers in the "Orders" table SELECT COUNT(DISTINCT Customer_ID) AS NumberOfCustomers FROM Orders; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

41 SQL Queries Examples of SQL Aggregate Functions IMPORTANT NOTE:
The DISTINCT keyword can be used to return only distinct (different) values. Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

42 SQL Queries Examples of SQL Aggregate Functions Example #14 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

43 SQL Queries Examples of SQL Aggregate Functions Example #15 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

44 SQL Queries SQL Aggregate Functions MAX() MIN() SUM() General form:
SELECT MAX(column_name) FROM table_name; MIN() SELECT MIN(column_name) FROM table_name; SUM() SELECT SUM(column_name) FROM table_name; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

45 SQL Queries SQL Aggregate Functions MAX() MIN() SUM() Example #17
The following SQL statement gets the Largest value of the “amount" column from the " orders" table: SELECT MAX(amount) AS LargestOrderPrice FROM orders; MIN() Example #18 The following SQL statement gets the smallest value of the “amount" column from the " orders" table: SELECT MIN(amount) AS SmallestOrderPrice FROM orders; SUM() Example #19 The following SQL statement gets the total value of the “amount" column from the " orders" table: SELECT SUM(amount) AS Total FROM orders; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

46 SQL Queries Examples of SQL Aggregate Functions Example #17 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

47 SQL Queries Examples of SQL Aggregate Functions Example #19 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

48 SQL Queries Grouping The GROUP BY statement is used in conjunction with the aggregate functions to group the resultset by one or more columns. To subgroups tuples in a relation, where the subgroups are based on some attribute values. For example, we may want to find the average salary of employees in each department or the number of employees who work on each department . Each group (partition) will consist of the tuples that have the same value of some attribute(s), called the grouping attribute(s). The GROUP BY clause specifies the grouping attributes, which should also appear in the SELECT clause, so that the value resulting from applying each aggregate function to a group of tuples appears along with the value of the grouping attribute(s). General form SELECT [column_names], aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name ORDER BY column_name; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

49 SQL Queries Examples of Grouping
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

50 SQL Queries Required Action (Query):
Examples of Grouping Example #20 Required Action (Query): From orders table, retrieve the customer ID for each customer, and the sum amount of their orders. SELECT customer_id,SUM(amount) AS Total FROM orders group by customer_id; Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

51 SQL Queries Orders table Examples of Grouping Example #20 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

52 SQL Queries Sub-queries
A subquery is a SELECT statement within another statement. Here is an example of a subquery: SELECT * FROM table1 WHERE column1 = (SELECT column1 FROM table1 ); In this example, SELECT * FROM t1 ... is the outer query (or outer statement), and (SELECT column1 FROM t2) is the subquery The main advantages of subqueries are: They allow structured queries so that it is possible to isolate each part of a statement. They provide alternative ways to perform operations that would otherwise require complex joins and unions. Subqueries more readable than complex joins or unions. Example #21 The following SQL statement selects the " customer_id " and " amount " records that have an above average amount : SELECT customer_id, amount FROM orders WHERE amount>(SELECT AVG(amount) FROM orders); Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

53 SQL Queries Examples of Sub-queries Outer Query Sub-Query
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

54 SQL Queries Examples of Sub-queries Example #21 Results
Dr Abdullah Alzahrani. Fundamental of Database Systems 9/20/2016

55 End SQL Queries Dr Abdullah Alzahrani. aahzahrani@uqu.edu.sa 9/20/2016
Fundamental of Database Systems 9/20/2016


Download ppt "Fundamental of Database Systems"

Similar presentations


Ads by Google