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

Slides:



Advertisements
Similar presentations
WHERE Clause Chapter 2. Objectives Limit rows by using a WHERE clause Use the LIKE operator Effect of NULL values Use compound conditions Use the BETWEEN.
Advertisements

1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
Restricting and Sorting Data. Consider the table employee(employee_id,last_name,job_id, department_id ) assume that you want to display all the employees.
Databases Week 1, lab 2 Simple selects. About the environment We are using SQL Server for the moment. The server we are using is: –Cian.student.comp.dit.ie.
2 Copyright © 2004, Oracle. All rights reserved. Restricting and Sorting Data.
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
Microsoft Access 2010 Chapter 7 Using SQL.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
Ceng 356-Lab2. Objectives After completing this lesson, you should be able to do the following: Limit the rows that are retrieved by a query Sort the.
1 Section 5 - Grouping Data u The GROUP BY clause allows the grouping of data u Aggregate functions are most often used with the GROUP BY clause u GROUP.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
IFS Intro. to Data Management Chapter 6 Filtering your data.
Spreadsheets Objective 6.02
2 Explain advanced spreadsheet concepts and functions Advanced Calculations 1 Sabbir Saleh_Lecture_17_Computer Application_BBA.
Rationale Aspiring Database Developers should be able to efficiently query and maintain databases. This module will help students learn the Structured.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
SQL/lesson 2/Slide 1 of 45 Retrieving Result Sets Objectives In this lesson, you will learn to: * Use wildcards * Use the IS NULL and IS NOT NULL keywords.
Views: Limiting Access to Data A view is a named select statement that is stored in a database as an object. It allows you to view a subset of rows or.
SQL/Lesson 4/Slide 1 of 45 Using Subqueries and Managing Databases Objectives In this lesson, you will learn to: *Use subqueries * Use subqueries with.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Restricting and Sorting Data. ◦ Limiting rows with:  The WHERE clause  The comparison conditions using =,
LECTURE 8.  Consider the table employee(employee_id,last_name,job_id, department_id )  assume that you want to display all the employees in department.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Upgrading to SQL Server 2000 Kashef Mughal. Multiple Versions SQL Server 2000 supports multiple versions of SQL Server on the same machine It does that.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IFS Intro to Data Management Chapter 5 Getting More Than Simple Columns.
Copyright © 2004, Oracle. All rights reserved. Retrieving Data Using the SQL SELECT Statement Satrio Agung Wicaksono, S.Kom., M.Kom.
Copyright © 2004, Oracle. All rights reserved. Lecture 4: 1-Retrieving Data Using the SQL SELECT Statement 2-Restricting and Sorting Data Lecture 4: 1-Retrieving.
Structured Query Language
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
2 Copyright © 2004, Oracle. All rights reserved. Restricting and Sorting Data.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
2 Copyright © 2009, Oracle. All rights reserved. Restricting and Sorting Data.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
IST 220 – Intro to DB Lab 2 Specifying Criteria in SELECT Statements.
Advanced Select Statements Select List Variations SELECT *SELECT * Column NamingColumn Naming Arithmetic ExpressionsArithmetic Expressions ConstantsConstants.
9/29/2005From Introduction to Oracle:SQL and PL/SQL, Oracle 1 Restricting and Sorting Data Kroenke, Chapter Two.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 2. Single Table Queries.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Tarik Booker CS 122. What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses,
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
1 Section 8 - Manipulating Data u The INSERT statement adds rows of data to the database u The UPDATE statement changes columns of existing data u The.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
Joining Tables Steve Perry
IST 220 – Intro to DB Lab 2 Specifying Criteria in SELECT Statements.
1 Section 9 - Views, etc. u Part 1: Views u Part 2:Security Issues u Part 3:Transaction Management u Part 4:Set Operations u Part 5:Triggers and Stored.
Restricting and Sorting Data
Structured Query Language
Connect to SQL Server and run select statements
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
Restricting and Sorting Data
Writing Basic SQL SELECT Statements
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Section 4 - Sorting/Functions
Restricting and Sorting Data
Chapter 3: Selection Structures: Making Decisions
Shelly Cashman: Microsoft Access 2016
Restricting and Sorting Data
Lab 2: Retrieving Data from the Database
Presentation transcript:

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 Basic SELECT Syntax u SELECT list_of_columns FROM table[s] [WHERE search_conditions]

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

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

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 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 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 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 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 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 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 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 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 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 What Happens Here? u SELECT title_id, ytd_sales - price * advance FROM titles;

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 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 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 Discussion u First we list the books and their price SELECT title, price FROM titles

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

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

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 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 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 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 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 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 Exercise u Produce a list of all books printed by each publisher. Use aliases.

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 WHERE Clause u Used to select rows from a set of search criteria –Syntax: SELECT select_list FROM table_list WHERE search_conditions;

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 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 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 Example u SELECT title, price FROM titles WHERE price > 15.00; Returns all rows that have a price greater than $15.00

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 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 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 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 and authors who live in zip code 92009

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 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 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 Logical Operator Precedence u Parenthesis u Multiplication & Division u Subtraction & Addition u NOT u AND u OR

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

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

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 Question u What question does this SQL statement answer? SELECT title, type, advance FROM titles WHERE (type = 'business' ORtype = 'psychology') ANDadvance > 5000;

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

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 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 Ranges u Comparison operators > and < –exclusive range check u BETWEEN and NOT BETWEEN –inclusive range check

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

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 Question u What values does this return? SELECT title, ytd_sales FROM titles WHERE ytd_sales > 4095 AND ytd_sales < 12000;

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 books

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

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

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

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

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 Exercise u Find all authors that live in 'San Francisco', 'Oakland' or 'Los Angeles'

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

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 Answer u No, because if a book has an advance of NULL it will not be returned by these two statements

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 Exercise u List the books that have been advanced at least $10,000 or whose advance has not yet been negotiated

66 Discussion u SELECT title FROM titles WHERE advance >= 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 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 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 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 Example u Find all books that have the word 'exercise' in the notes column –SELECT title, notes FROM titles WHERE notes LIKE '%exercise%';

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 Exercises u List books whose title includes the word 'Computer'

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 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

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 Section 3 - Last Slide u Please complete Assignment 2