Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.

Similar presentations


Presentation on theme: "Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections."— Presentation transcript:

1 Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections

2 Always Test Your Work In any form of programming, work that has not been tested practically never works Programming consists mostly of debugging Your work in this class is no exception. Don’t turn in any code you have not tested; if you do, it is almost certain to be wrong.

3 Basic Queries Basic format is: SELECT field_name1, field_name2,... FROM table_name; To automatically select ALL fields: SELECT * FROM table_name;

4 Basic Examples List all attributes of all artists. SELECT * FROM Artists; List the first names of all members. ? List all artists and the countries where they are located ?

5 Basic Examples List all attributes of all artists. SELECT * FROM Artists; List the first name of all members. SELECT FirstName FROM Members List all artists and the countries where they are located SELECT ArtistName, Country FROM Artists

6 Basic Queries Basic format is: SELECT field_name1, field_name2,... FROM table_name; To automatically select ALL fields: SELECT * FROM table_name;

7 The SELECT Clause In a SELECT clause you can perform simple calculations, even if you don’t select any data from a table Examples: SELECT 1 + 2; SELECT (1 + 3)*2 – 7;

8 The FROM Clause When combined with the FROM clause, the SELECT clause pulls data from the table specified in the FROM clause Syntax: -- To list specific attributes... SELECT attribute1, attribute2,... FROM tablename; -- To list all attributes... use the * character... SELECT * FROM tablename;

9 SELECT FROM Examples Examples: List all attributes for all artists. SELECT * FROM Artists; -- List the first names of all members. SELECT FirstName FROM Members;

10 Basic Examples List all attributes of all artists. SELECT * FROM Artists; List the first name of all members. SELECT FirstName FROM Members List all artists and the countries where they are located SELECT ArtistName, Country FROM Artists

11 Basic Examples List all attributes of all artists. SELECT * FROM Artists; List the first name of all members. ? List all artists and the countries where they are located ?

12 Calculated Columns You can use attributes in mathematical expressions of the SELECT clause. Examples: -- List each track title along with the length of the track in minutes. SELECT TrackTitle, LengthSeconds/60 FROM Tracks;

13 The WHERE Clause Use the WHERE clause to filter results Syntax: SELECT attribute1, attribute2,... FROM tablename WHERE boolean_expression; The expression in the WHERE clause is executed once per row. If expression is true, row is retrieved. If expression is false or null, row is not retrieved.

14 The WHERE Clause SELECT firstname FROM members WHERE gender = "f"; Output: +-----------+ | firstname | +-----------+ | Caroline | | Mary | | Carol | | Bonnie | | Michelle | +-----------+

15 WHERE Clause Examples Examples: -- List the names of all artists from Canada. SELECT ArtistName FROM Artists WHERE Country = 'Canada';

16 Operators Arithmetic +, -, *, /, % Conditional operators:, =, =, <>, BETWEEN BETWEEN is inclusive Logical operators: AND, OR, NOT

17 Boolean Value Expressions Logical Operators AND (binary) OR (binary) NOT (unary) Comparison Operators, =, =, <>, != IS NULL, IS NOT NULL BETWEEN

18 Operators with NULL No value is equal to NULL, not even another NULL. NULL = NULL is NULL! NOT(NULL = NULL) is also NULL! Use IS NULL or IS NOT NULL instead: NULL IS NULL is true NULL IS NOT NULL is false

19 IS NULL Examples Examples: -- Select all artist names for whom we do not have web addresses in the database. SELECT ArtistName FROM Artists WHERE WebAddress IS NULL; -- Select all artist names for whom we do have web addresses. SELECT ArtistName FROM Artists WHERE WebAddress IS NOT NULL;

20 Lab/Exam Questions About NULL At least one lab and at least one exam will contain questions like this one: Consider this SQL query: SELECT (NULL = (NOT NULL)) = (NULL = NULL); Why does this query return NULL? You may answer these questions in a few sentences, like this: Tests for equality or inequality to NULL return NULL. Therefore, NULL = (NOT NULL) and NULL = NULL each evaluate to NULL. We then test whether the left side NULL is equal to the right side NULL, and this evaluation also returns NULL. You may also answer with a simplified proof, like this: SELECT (NULL = (NOT NULL)) = (NULL = NULL); SELECT NULL=NULL; SELECT NULL; NULL

21 AND Syntax: boolean_arg1 AND boolean_arg2 Returns: TRUE, FALSE, or NULL Description: Returns TRUE if both arguments are TRUE Examples: SELECT TRUE AND TRUE; -- TRUE SELECT TRUE AND FALSE; -- FALSE SELECT FALSE AND FALSE; -- FALSE

22 OR Syntax: boolean_arg1 OR boolean_arg2 Returns: TRUE, FALSE, or NULL Description: Returns TRUE if any argument is TRUE Examples: SELECT TRUE OR TRUE; -- TRUE SELECT TRUE OR FALSE; -- TRUE SELECT FALSE OR FALSE; -- FALSE

23 NOT Syntax: NOT boolean_arg Returns: TRUE, FALSE, or NULL Description: Returns TRUE if argument is FALSE, FALSE if argument is TRUE, and NULL otherwise. Examples: SELECT NOT TRUE; -- FALSE SELECT NOT FALSE; -- TRUE SELECT NOT NULL; -- NULL

24 AND, OR, and NOT Examples: -- Display all member names from California or Texas. SELECT FirstName, LastName, Region FROM Members WHERE Region='CA' OR Region='TX'; -- Display all titles whose genre is not alternative. SELECT * FROM Titles WHERE NOT (Genre = 'alternative'); -- Display the names of all members from California or Texas who are represented by salesperson #2 SELECT FirstName, LastName FROM Members WHERE (Region='CA' OR Region='TX') AND SalesID=2;

25 AND, OR, and NOT Not has higher precedence than and; and has higher precedence than or Be careful to use parentheses when ambiguity could trip you up SELECT FirstName, LastName FROM Members WHERE (Region='CA' OR Region='TX') AND SalesID=2; SELECT FirstName, LastName FROM Members WHERE Region='CA' OR Region='TX' AND SalesID=2; OUCH! 2 nd query does not return the right result.

26 Using NOT Correctly If the intention is to negate the result of the boolean expression in the WHERE clause, always surround the expression with parentheses. Example: Do the following two queries return the same result? SELECT * FROM Artists WHERE NOT TRUE AND FALSE; SELECT * FROM Artists WHERE NOT (TRUE AND FALSE);

27 BETWEEN Like saying fieldname >= x AND fieldname <= y -- List the titles and tracks of all tracks with lengths between 240 and 300 seconds. SELECT TrackTitle, LengthSeconds FROM Tracks WHERE LengthSeconds BETWEEN 240 AND 300;

28 LIKE Used for pattern matching (within strings) %  any zero or more characters _  any single character Example: -- List all member names and their emails whose emails have a.org domain. SELECT FirstName, LastName, Email FROM Members WHERE Email LIKE '%.org';

29 LIKE What’s wrong with this: -- List the names and emails of all members whose emails have an.org domain. SELECT FirstName, LastName, Email FROM Members WHERE Email LIKE ‘_.org'; How do we find any date in 2001? How do we find any date in March, regardless of year? There will be one or more test questions on this. Many people got similar questions wrong last term!

30 NOT LIKE Negation of LIKE Ignores comparing NULL strings Example: -- List all member names and their emails whose emails do not come from a.org domain. SELECT FirstName, LastName, Email FROM Members WHERE Email NOT LIKE '%.org';

31 Ordering By Attributes Syntax: SELECT A 1, A 2,... FROM tablename WHERE conditions ORDER BY F 1 [ASC | DESC], F 2 [ASC | DESC],... Example: List all artist names in decreasing order. SELECT ArtistName FROM Artists ORDER BY ArtistName DESC;

32 Ordering By Attributes Note that the ORDER BY clause can take multiple field names. Example: -- List all artists and their respective countries, sorted by country first, then by artist name. SELECT ArtistName, Country FROM Artists ORDER BY Country, ArtistName;

33 Ordering By Attributes Note that you can also mix ASC and DESC. Example: -- List all member’s first and last names along with their respective countries, sorted by country first in ascending order, followed by first name in descending order. SELECT FirstName, LastName, Country FROM Members ORDER BY Country ASC, FirstName DESC;

34 If() if(condition, true_expr, false_expr)‏ condition is a boolean expression true_expr is what to do if the condition is true false_expr is what to do if the condition is false SELECT M.LastName, IF(M.LastName = 'sanders', 'yes', 'no') from Members M Select If(grade > 90, “A”, if(grade > 80, “B”, if(grade > 70, “C”, “F”))) FROM Students

35 CASE Statements Use in the SELECT clause when you want to check and possibly modify/replace a column value before it is displayed For example, we can use CASE statements to replace NULL values Let’s go over the syntax first, and then go over some tips and examples

36 CASE Syntax: CASE WHEN condition THEN statement_list WHEN condition THEN statement_list … ELSE statement_list END It’s like saying: if(condition) then statement_list; else if(condition) then statement_list; … else statement_list;

37 CASE Examples -- List all track titles and their length in minutes. If the length of the track is less than 3 minutes, display ‘Short Track’; otherwise, display ‘Long Track.’ SELECT TrackTitle, LengthSeconds/60, CASE WHEN LengthSeconds/60 < 3 THEN 'Short Track' ELSE 'Long Track' END FROM Tracks;

38 CASE Examples SELECT TrackTitle, LengthSeconds/60, CASE WHEN LengthSeconds/60 < 3 THEN 'Short Track‘ WHEN LengthSeconds/60 < 4 THEN 'Medium Track ELSE 'Long Track’ END FROM Tracks

39 CASE Examples What happens if we leave out the ‘else’ clause in the previous example?

40 Column Aliases Last CASE example had a long column name. To get rid of that we can use column aliases SELECT expression AS alias FROM … Example: SELECT TrackTitle, LengthSeconds/60, CASE WHEN LengthSeconds/60 < 3 THEN 'Short Track' WHEN LengthSeconds/60 < 4 THEN 'Medium Track' ELSE 'Long Track' END AS 'Track Description' FROM Tracks;

41 SELECT DISTINCT Use when you want to remove duplicate results Example: Display a list of unique countries that all members come from. SELECT Country FROM Members; // WRONG!!! SELECT DISTINCT Country FROM Members; // CORRECT!!!

42 Note about SQL Queries For all assignment questions that involve writing SQL queries: Write queries to find the information specified based on exactly the information given in the question. Do not assume you know any other information from the database

43 Note about SQL Queries Example: show the base salary of salesperson Lisa Williams correct: select base from salespeople where lastName = “Williams” and firstName = “Lisa” incorrect: select base from salespeople where salesID = 2 Do not assume you know that Lisa Williams’ salesID is 2! also incorrect: select base from salespeople where lastName = “Williams” there won’t always be exactly one salesperson with the last name Williams!”

44 SQL Scripts You can run a series of queries by writing a text file, saving it with the filename extension.sql, and running it with source We have already done this with lyric.sql

45 Copy and Paste to Command Line You can also write a series of queries in a text editor, copy it, and paste to a command line Right click on the window border, not at the cursor, and choose “edit/paste” This is also a convenient way to copy and paste statements from the lecture notes to a command line

46 Comments Comments are always ignored Simple Comments double minus signs followed by a space -- This is a simple comment # also works Bracketed (C-Style) Comments Place comment inside the asterisks /* */ /* This is a comment */

47 Databases and Applications In this course, we will be managing databases directly using SQL, Data Manipulation Language, and Data Definition Language that we write by hand. The main point of this is to learn these languages. Later in your career, you will write or use programming code that generates SQL queries using parameters that are set programmatically or from user input User sees a GUI with input and output, does not see the SQL Near the end of the course, I will show some examples to help you see how this works

48 SQL Data Types Strings 'Peterson', ‘Joe’ Escapes: “Eat at Joe’s” or ‘Eat at Joe\’s’ ‘A\\B’ Integers 1, 2, 3, etc. Decimals; actually several types; we’ll cover this later 1.45, 2.83, 3.14159 NULL NULL, null

49 SQL Data Types (Cont.) Dates '2005-02-14', '1973-08-13' Dates are in 'YEAR-MONTH-DAY' string format Boolean TRUE = 1 FALSE = 0

50 Questions 1) Consider a query intended to find Lisa Williams’ base salary and written this way: select base from salespeople where salesID = 2 What might happen in the database in the future that would make this query return an incorrect answer? 2) Consider a query intended to find the same information and written this way: select base from salespeople where lastName = “Williams” What might happen that would make this query return an incorrect answer?


Download ppt "Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections."

Similar presentations


Ads by Google