Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Section 3 - Select Statement u The Select statement allows you to... –Display Data –Specify Selection Criteria –Sort Data –Group Data for reporting –Use.

Similar presentations


Presentation on theme: "1 Section 3 - Select Statement u The Select statement allows you to... –Display Data –Specify Selection Criteria –Sort Data –Group Data for reporting –Use."— Presentation transcript:

1 1 Section 3 - Select Statement u The Select statement allows you to... –Display Data –Specify Selection Criteria –Sort Data –Group Data for reporting –Use Functions –Join Tables –Nest Selects within other Selects

2 2 Basic SELECT Syntax u SELECT list_of_columns FROM table[s] [WHERE search_conditions]

3 3 Example u Sample data in table: Au_lnameAu_fnameCity -------------------------------------- AdamsJohnNew York SmithSamChicago ThomsonTomLos Angeles

4 4 Example - cont. u SELECT city FROM authors WHERE au_lname = 'Smith'; u Results: City ------------ Chicago

5 5 Discussion u This statement returns one row from the sample data where the last name was equal to 'Smith' u Then the city column is the only column displayed from that row

6 6 WHERE Clause u The Where clause restricts the number of rows returned from a table u SELECT au_lname, au_fname, state FROM authors WHERE state = 'CA'; –Returns only rows where the author lives in California u SELECT au_lname, au_fname, state FROM authors; –Returns all the rows in the table

7 7 Full SELECT Syntax u SELECT [ALL|DISTINCT] select_list FROM {table_name|view_name} [,{table_name|view_name}]... [WHERE search_conditions] [GROUP BY column_1 [, column_2]...] HAVING search_conditions] [ORDER BY {column_1 | 1} [ASC| DESC] [,{column_2| 2 } [ASC | DESC ]...] ;

8 8 Discussion u Each of these clauses will be explained in detail as we proceed through the class Lessons u The ‘search-conditions’ part of the statement will be expanded greatly

9 9 Order of Clauses u SQL is a Free-form language –You may add spaces, skip lines, etc. u But, the CLAUSEs must be in syntactical order –e.g. FROM must come before WHERE GROUP BY must come before HAVING

10 10 Qualification of Names u Prefix column names with the table name and/or owner id –e.g. SELECT dba.authors.au_lname u Qualification is always allowed u Qualification MUST be used if there is any ambiguity –e.g. you are referencing two tables in the SELECT statement and both tables have a column named CITY

11 11 The SELECT list u You may include the following in a Select list: –ALL vs. DISTINCT (removes duplicates) –Column(s)... or * (show all columns) –Expressions (e.g. price * 2) –Constants (e.g. 'DOG') –Functions (e.g. Avg(advance) ) –Any Combination of Above

12 12 Examples u SELECT * FROM authors; u SELECT title, price * 2 FROM titles; u SELECT 'BOOK: ', title, 14.95/5 FROM titles u SELECT AVG(advance) FROM titles

13 13 Computations with Constants u Available arithmetic operators +addition -subtraction /division *multiplication u Used with Numeric datatypes –+ may be used with character types to concatenate strings (SQLAnywhere only)

14 14 Arithmetic Order Precedence u Expressions inside parenthesis are interpreted first u Then from left to right multiplication & division are calculated u Last from left to right subtraction & addition are computed

15 15 What Happens Here? u SELECT title_id, ytd_sales - price * advance FROM titles;

16 16 Discussion u SELECT title_id, price - 2 * advance FROM titles; For each row returned, first the ‘2 * advance’ is calculated, then it is subtracted from the price

17 17 Parenthesis to Clarify u SELECT title_id, (price - 2) * advance FROM titles; u Here we subtract 2 from the price, then multiply it by the advance u Always use parenthesis to aid with clarity

18 18 Exercise u List all books and their price. Reduce the price by $3.00 then reduce it again by 25%. Display each book's current revenue based on the original price.

19 19 Discussion u First we list the books and their price SELECT title, price FROM titles

20 20 Discussion u Now we reduce the price by $3.00 SELECT title, price - 3 FROM titles

21 21 Discussion u Now we reduce the price by another 25% SELECT title, price - 3 *.75 FROM titles

22 22 Discussion u Wait a minute, that won't work. It will first multiply 3 *.75 and then subtract it from price. Let's use parenthesis. SELECT title, (price - 3) *.75 FROM titles

23 23 Discussion u How do we get the current revenue for each book? We multiple the price by the ytd_sales count. SELECT title, (price - 3) *.75, ytd_sales * price FROM titles

24 24 FROM Clause u Lists the tables or views that contain the columns referred to in the Select list or other clauses u Syntax: SELECT FROM [qualifier] {table|view} [, [qualifier] {table|view} ]... ;

25 25 Examples u SELECT city FROM authors; u SELECT city FROM dba.authors; u SELECT title, pub_name FROM titles, publishers WHERE title.pub_id = publishers.pub_id;

26 26 Aliases u Use may use table name aliases to save typing u Specify a short-name for a table at least one space after the table name (e.g. FROM authors a, titleauthors ta 'a' could now be used in the rest of the statement to represent the table authors and 'ta' could be used instead of titleauthors

27 27 Examples –instead of: SELECT authors.au_id, au_ord FROM authors, titleauthors WHERE authors.au_id = titleauthors.au_id; –use: SELECT a.au_id, au_ord FROM authors a, titleauthors ta WHERE a.au_id = ta.au_id;

28 28 Exercise u Produce a list of all books printed by each publisher. Use aliases.

29 29 Discussion u SELECT pub_name, title FROM publishers p, title t WHERE p.pub_id = t.pub_id; This connects (joins) the publishers table to the titles table using the pub_id column they share in common.

30 30 WHERE Clause u Used to select rows from a set of search criteria –Syntax: SELECT select_list FROM table_list WHERE search_conditions;

31 31 Comparison Operators u =, Equal, Not Equal u Less than, Greater than u >=, <= Greater than or Equal to, Less than or Equal to u NOTNegates the entire expression

32 32 Example u SELECT title, advance FROM titles WHERE advance > ytd_sales * price; This displays the title and advance where the advance is greater than the product of ytd_sales multiplied by price

33 33 Numeric vs. Character, Date u You can use comparison operators with all datatypes... –Numeric: > 3means greater than three –Character: > 'C'means 'D' or later in the alphabet –Date: > '97/10/02' means greater than Oct. 2, 1997

34 34 Example u SELECT title, price FROM titles WHERE price > 15.00; Returns all rows that have a price greater than $15.00

35 35 Example u SELECT au_lname, au_fname FROM authors WHERE au_lname > 'McBadden'; Returns all authors whose last name comes after McBadden alphabetically

36 36 Logical Operators u Use when there is more than one condition u AND –both conditions must be true for a row to be returned in the result u OR –At least one condition must be true for a row to be returned in the result u NOT –Negates the results of the following condition

37 37 Example u SELECT au_lname, au_fname FROM authors WHERE city = 'Springfield' ANDstate = 'CA'; This will return authors who live in Springfield, CA but not authors who live in Springfield, IL

38 38 Example u SELECT au_lname, au_fname FROM authors WHERE zip_code = '92008' ORzip_code = '92009'; This will return authors who live in zip code 92008 and authors who live in zip code 92009

39 39 Example u SELECT au_lname, au_fname FROM authors WHERE NOT state = 'CA'; This determines which authors live in California and then negates the result and returns all authors who do not live in California

40 40 Example u SELECT au_lname, au_fname FROM authors WHERE state <> 'CA'; This returns the authors who do not live in California. This is another way to get the same result as the last statement.

41 41 Combinations of Conditions u You can combine conditions u SELECT title, advance, ytd_sales, price FROM titles WHERE (advance = 5000) AND (NOT price > 20.00);

42 42 Logical Operator Precedence u Parenthesis u Multiplication & Division u Subtraction & Addition u NOT u AND u OR

43 43 Exercise u List all business books and list all psychology books that have an advance greater than $5000

44 44 Discussion u SELECT title, type, advance FROM titles WHERE type = 'business' ORtype = 'psychology' ANDadvance > 5000; What's the order of precedence?

45 45 Discussion u The AND is evaluated before the OR so the statement will work, but it is always better to use parenthesis for clarity u SELECT title, type, advance FROM titles WHERE type = 'business' OR(type = 'psychology' ANDadvance > 5000);

46 46 Question u What question does this SQL statement answer? SELECT title, type, advance FROM titles WHERE (type = 'business' ORtype = 'psychology') ANDadvance > 5000;

47 47 Answer u Which psychology or business books have been given an advance greater than $5000?

48 48 Exercise u Find all books that were published before Oct. 15, 1985 whose current revenue is less than twice the advance paid to the author. HINT: ytd_sales column represents number of books sold.

49 49 Discussion u SELECT title FROM titles WHERE (pubdate < '98/10/15' ) AND (ytd_sales * price) < (2 * advance); Parenthesis not necessary, but makes the statement easier to understand

50 50 Ranges u Comparison operators > and < –exclusive range check u BETWEEN and NOT BETWEEN –inclusive range check

51 51 Question u What does this find? SELECT title, ytd_sales FROM titles WHERE ytd_sales BETWEEN 4095 and 9000;

52 52 Answer u All of the books who have sold 4095 books or greater, but less than 9001 books u Range check is inclusive

53 53 Question u What values does this return? SELECT title, ytd_sales FROM titles WHERE ytd_sales > 4095 AND ytd_sales < 12000;

54 54 Answer u Returns all books who have sold more than 4095 books (if they have sold exactly 4095 books the row would not be returned), but less than 12000 books

55 55 Question u What values does this return? SELECT title, ytd_sales FROM titles WHERE ytd_sales 12000;

56 56 Answer u This returns no rows since a book cannot have both sold less than 4095 books and sold more than 12000 books at the same time

57 57 Exercise u List all books whose advance is not more than $10,000 and whose advance is not less than $5,000

58 58 Answer u SELECT title FROM titles WHERE advance BETWEEN 5000 and 10000

59 59 Comparing Lists of Values u Instead of this... –SELECT au_lname, au_fname FROM authors WHERE state = 'CA' OR state = 'IN' OR state = 'MD' u Try the IN (or NOT IN ) clause –SELECT au_lname, au_fname FROM authors WHERE state IN ('CA', 'IN', 'MD');

60 60 Exercise u Find all authors that live in 'San Francisco', 'Oakland' or 'Los Angeles'

61 61 Answer u SELECT au_lname, au_fname FROM authors WHERE city IN ('San Francisco', 'Oakland', 'Los Angeles');

62 62 Comparison with NULLs u Do these two statements return all rows in the titles table? –SELECT title, advance FROM titles WHERE advance < 5000; –SELECT title, advance FROM titles WHERE advance >= 5000;

63 63 Answer u No, because if a book has an advance of NULL it will not be returned by these two statements

64 64 Finding the NULLs u IS NULL or IS NOT NULL –SELECT title, advance FROM titles WHERE advance IS NULL; –SELECT title, advance FROM titles WHERE advance IS NOT NULL;

65 65 Exercise u List the books that have been advanced at least $10,000 or whose advance has not yet been negotiated

66 66 Discussion u SELECT title FROM titles WHERE advance >= 10000 OR advance IS NULL; –We use an OR since we want the book returned if either condition is true –We look for where the advance is NULL, since this means "We don't know". If we knew we were advancing nothing for this book, than the value would be zero.

67 67 Pattern Matching u When you search for patterns use the LIKE keyword instead of the = u This works with character data only u Syntax: –SELECT FROM WHERE column_name [NOT] LIKE "pattern"

68 68 Wildcard Characters u Patterns are enclosed in quotes and include wildcard characters u Wildcard characters are symbols that take the place of missing letters or strings in the pattern u %means any string of zero or more characters u _means any single character

69 69 Example u Find the authors with Scottish surnames: –SELECT au_lname, city FROM authors WHERE au_lname LIKE 'Mc%' OR au_lname LIKE 'Mac%';

70 70 Example u Find all books that have the word 'exercise' in the notes column –SELECT title, notes FROM titles WHERE notes LIKE '%exercise%';

71 71 Example u Find all author phone numbers that have area codes with a '1' in the second digit –SELECT phone FROM authors WHERE phone LIKE '_1%';

72 72 Exercises u List books whose title includes the word 'Computer'

73 73 Discussion u We need to find all books that have a title that has the word ‘computer’ anywhere in the column SELECT title FROM titles WHERE title LIKE '%computer%';

74 74 Exercise u What authors have a '1' in the 2nd digit of their social security number and a '4' in the fourth digit (5th character) –e.g. 210-40-1000

75 75 Discussion u SELECT au_lname, au_fname FROM authors WHERE au_id LIKE '_1_ _4%'; You can combine the _ and % characters within a pattern

76 76 Section 3 - Last Slide u Please complete Assignment 2


Download ppt "1 Section 3 - Select Statement u The Select statement allows you to... –Display Data –Specify Selection Criteria –Sort Data –Group Data for reporting –Use."

Similar presentations


Ads by Google