770 likes | 775 Vues
Section 3 - Select Statement . 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. Basic SELECT Syntax. SELECT list_of_columns FROM table[s] [WHERE search_conditions].
E N D
Section 3 - Select Statement • 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
Basic SELECT Syntax • SELECT list_of_columnsFROM table[s][WHERE search_conditions]
Example • Sample data in table:Au_lname Au_fname City------------ ------------- -------------Adams John New YorkSmith Sam ChicagoThomson Tom Los Angeles
Example - cont. • SELECT cityFROM authorsWHERE au_lname = 'Smith'; • Results:City------------Chicago
Discussion • This statement returns one row from the sample data where the last name was equal to 'Smith' • Then the city column is the only column displayed from that row
WHERE Clause • The Where clause restricts the number of rows returned from a table • SELECT au_lname, au_fname, stateFROM authorsWHERE state = 'CA'; • Returns only rows where the author lives in California • SELECT au_lname, au_fname, stateFROM authors; • Returns all the rows in the table
Full SELECT Syntax • SELECT [ALL|DISTINCT] select_listFROM {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 ] ...] ;
Discussion • Each of these clauses will be explained in detail as we proceed through the class Lessons • The ‘search-conditions’ part of the statement will be expanded greatly
Order of Clauses • SQL is a Free-form language • You may add spaces, skip lines, etc. • But, the CLAUSEs must be in syntactical order • e.g. FROM must come before WHERE GROUP BY must come before HAVING
Qualification of Names • Prefix column names with the table name and/or owner id • e.g. SELECT dba.authors.au_lname • Qualification is always allowed • 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
The SELECT list • 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
Examples • SELECT * FROM authors; • SELECT title, price * 2 FROM titles; • SELECT 'BOOK: ', title, 14.95/5 FROM titles • SELECT AVG(advance)FROM titles
Computations with Constants • Available arithmetic operators + addition - subtraction / division * multiplication • Used with Numeric datatypes • + may be used with character types to concatenate strings (SQLAnywhere only)
Arithmetic Order Precedence • Expressions inside parenthesis are interpreted first • Then from left to right multiplication & division are calculated • Last from left to right subtraction & addition are computed
What Happens Here? • SELECT title_id, ytd_sales - price * advanceFROM titles;
Discussion • SELECT title_id, price - 2 * advanceFROM titles;For each row returned, first the‘2 * advance’ is calculated, then it is subtracted from the price
Parenthesis to Clarify • SELECT title_id, (price - 2) * advanceFROM titles; • Here we subtract 2 from the price, then multiply it by the advance • Always use parenthesis to aid with clarity
Exercise • 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.
Discussion • First we list the books and their priceSELECT title, priceFROM titles
Discussion • Now we reduce the price by $3.00SELECT title, price - 3FROM titles
Discussion • Now we reduce the price by another 25%SELECT title, price - 3 * .75FROM titles
Discussion • 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) * .75FROM titles
Discussion • 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
FROM Clause • Lists the tables or views that contain the columns referred to in the Select list or other clauses • Syntax: SELECT <select_list> FROM [qualifier] {table|view} [, [qualifier] {table|view} ] ... ;
Examples • SELECT cityFROM authors; • SELECT cityFROM dba.authors; • SELECT title, pub_nameFROM titles, publishersWHERE title.pub_id = publishers.pub_id;
Aliases • Use may use table name aliases to save typing • 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
Examples • instead of:SELECT authors.au_id, au_ordFROM authors, titleauthorsWHERE authors.au_id = titleauthors.au_id; • use:SELECT a.au_id, au_ordFROM authors a, titleauthors taWHERE a.au_id = ta.au_id;
Exercise • Produce a list of all books printed by each publisher. Use aliases.
Discussion • SELECT pub_name, titleFROM publishers p, title tWHERE 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.
WHERE Clause • Used to select rows from a set of search criteria • Syntax:SELECT select_listFROM table_listWHERE search_conditions;
Comparison Operators • =, < > Equal, Not Equal • <, > Less than, Greater than • >=, <= Greater than or Equal to, Less than or Equal to • NOT Negates the entire expression
Example • SELECT title, advanceFROM titlesWHERE advance > ytd_sales * price;This displays the title and advance where the advance is greater than the product of ytd_sales multiplied by price
Numeric vs. Character, Date • You can use comparison operators with all datatypes... • Numeric: > 3 means greater than three • Character: > 'C' means 'D' or later in the alphabet • Date: > '97/10/02' means greater than Oct. 2, 1997
Example • SELECT title, priceFROM titlesWHERE price > 15.00;Returns all rows that have a price greater than $15.00
Example • SELECT au_lname, au_fnameFROM authorsWHERE au_lname > 'McBadden';Returns all authors whose last name comes after McBadden alphabetically
Logical Operators • Use when there is more than one condition • AND • both conditions must be true for a row to be returned in the result • OR • At least one condition must be true for a row to be returned in the result • NOT • Negates the results of the following condition
Example • SELECT au_lname, au_fnameFROM authorsWHERE city = 'Springfield'AND state = 'CA';This will return authors who live in Springfield, CA but not authors who live in Springfield, IL
Example • SELECT au_lname, au_fnameFROM authorsWHERE zip_code = '92008'OR zip_code = '92009';This will return authors who live in zip code 92008 and authors who live in zip code 92009
Example • SELECT au_lname, au_fnameFROM authorsWHERE 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
Example • SELECT au_lname, au_fnameFROM authorsWHERE 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.
Combinations of Conditions • You can combine conditions • SELECT title, advance, ytd_sales, priceFROM titlesWHERE (advance < 500 OR ytd_sales >= 5000) AND (NOT price > 20.00);
Logical Operator Precedence • Parenthesis • Multiplication & Division • Subtraction & Addition • NOT • AND • OR
Exercise • List all business books and list all psychology books that have an advance greater than $5000
Discussion • SELECT title, type, advanceFROM titlesWHERE type = 'business' OR type = 'psychology'AND advance > 5000;What's the order of precedence?
Discussion • The AND is evaluated before the OR so the statement will work, but it is always better to use parenthesis for clarity • SELECT title, type, advanceFROM titlesWHERE type = 'business' OR (type = 'psychology'AND advance > 5000);
Question • What question does this SQL statement answer?SELECT title, type, advanceFROM titlesWHERE (type = 'business' OR type = 'psychology')AND advance > 5000;
Answer • Which psychology or business books have been given an advance greater than $5000?
Exercise • 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.
Discussion • SELECT titleFROM titlesWHERE (pubdate < '98/10/15' )AND (ytd_sales * price) < (2 * advance);Parenthesis not necessary, but makes the statement easier to understand
Ranges • Comparison operators > and < • exclusive range check • BETWEEN and NOT BETWEEN • inclusive range check