Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 Candidate Keys A unique identifier (may contain multiple attributes). Examples: Movies table  MovieID and Title Members table  MemberID and Username

3 Primary Keys A candidate key that has been singled out to uniquely identify each record. Difference between candidate key and primary key? A table may have more than one candidate key, but can only have one primary key. Out of all candidate keys, which key do you choose to be the primary key? Movies table  MovieID or (Title, ReleaseDate)? Best to choose MovieID.

4 Foreign Keys Most table relationships almost always involve a primary key. A foreign key is just a key at the other end of the relationship. We usually say a foreign key ‘references’ a primary key. Example: In Ratings table, MemberID is a foreign key that references the primary key MemberID in the Members table.

5 Operators Arithmetic +, -, *, /, % Conditional operators:, =, =, <>, BETWEEN Logical operators: AND, OR, NOT Other operators: IS NULL

6 What is an SQL Selection Query? An SQL selection query is a list of SQL clauses, starting with the SELECT clause The SELECT clause is ALWAYS the first clause in a selection query Selection query: SELECT select_clause_arguments FROM from_clause_arguments WHERE where_clause_arguments GROUP BY group_by_clause_arguments HAVING having_clause_arguments ORDER BY order_by_clause_arguments;

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 SQL Data Types Strings (C-syntax) 'Peterson', 'Joe\ 's ', 'Peterson', "Joe 's", "A\\B" Integers 1, 2, 3, etc. Decimals 1.45, 2.83, 3.14159 NULL NULL, null

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

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

11 NULL NULL essentially means unknown You can do math with NULL SELECT 10 + NULL; SELECT NULL - NULL; SELECT 15*NULL; SELECT 10/NULL; You can compare NULL SELECT NULL < NULL; SELECT NULL = NULL;

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

13 SELECT FROM Examples Examples: -- Display a list of all movie titles. SELECT Title FROM Movies; -- List all attributes for all companies. SELECT * FROM Companies;

14 Calculated Columns You can use attributes in mathematical expressions of the SELECT clause. Examples: -- List the names of all movie-related people along with their height in inches. SELECT FirstName, LastName, 39.37*Height FROM People;

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

16 WHERE Clause Examples Examples: -- List the names of all production companies from Canada. SELECT Name FROM Companies WHERE Country = 'CAN';

17 Boolean Value Expressions AND OR NOT

18 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

19 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

20 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

21 AND, OR, and NOT Examples Examples: -- Display all members from the United States or Australia. SELECT Username FROM Members WHERE Country = 'USA' OR Country = 'AUS'; -- Display all male members from the United States. SELECT Username FROM Members WHERE Country = 'USA' AND Gender = 'M'; -- Display all members who are not Pro Members. SELECT Username FROM Members WHERE NOT ProMember;

22 Mixing ANDs and ORs Be careful of parentheses!!! -- Display all male members from the United States or Australia (correct). SELECT Username FROM Members WHERE (Country = 'USA' OR Country = 'AUS') AND Gender = 'M'; -- Display all male members from the United States or Australia (wrong). SELECT Username FROM Members WHERE Country = 'USA' OR Country = 'AUS' AND Gender = 'M';

23 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 Movies WHERE NOT TRUE AND FALSE; SELECT * FROM Movies WHERE NOT (TRUE AND FALSE);

24 BETWEEN Like saying attribute >= x AND attribute <= y Note that comparison includes boundaries Example: -- List the titles of all movies with a runtime between one to two hours. SELECT Title, Runtime/60 FROM Movies WHERE Runtime/60 BETWEEN 1 AND 2;

25 IS NULL Do not use conditional operators to compare NULL NULL is a special keyword, not a specific value Why? Consider: SELECT (NULL = NULL); -- NULL SELECT (NULL IS NULL); -- TRUE To determine if something is NULL Use the IS NULL keyword To determine if something is not NULL Use the IS NOT NULL keyword

26 IS NULL Examples Examples: -- List the first and last names of all movie-related people whose heights are known. SELECT FirstName, LastName FROM People WHERE Height IS NOT NULL; -- List the first and last names of all movie-related people whose heights are unknown. SELECT FirstName, LastName FROM People WHERE Height IS NULL;

27 LIKE Predicate Used for pattern matching strings %  placeholder for zero or more characters _  placeholder for any single character Syntax: StringExpression LIKE PatternConstant Returns TRUE, FALSE or NULL Examples: '% sql %' means any number of characters followed by a space, then sql followed by a space, then any number of characters.

28 LIKE Example Example: -- List all member usernames and their emails for only those members that come from a.com domain. SELECT FirstName, LastName, Email FROM Members WHERE Email LIKE '%.com';

29 NOT LIKE Negation of LIKE Ignores comparing NULL strings Example: -- List all member usernames and their emails for only those members that do not come from a.com domain. SELECT FirstName, LastName, Email FROM Members WHERE Email NOT LIKE '%.com';

30 The ORDER BY Clause To sort the result of a selection query, use the ORDER BY clause Syntax: SELECT A 1, A 2,... FROM tablename ORDER BY F 1 [ASC | DESC], F 2 [ASC | DESC],... Example: -- List all movie titles in descending order. SELECT Title FROM Movies ORDER BY Title DESC;

31 Ordering By Multiple Attributes Note that the ORDER BY clause can take multiple attribute names. Example: -- List the first and last names of all movie-related people along with their gender. Sort by gender in descending order then by first name in ascending order. SELECT FirstName, LastName, Gender FROM People ORDER BY Gender DESC, FirstName ASC;

32 CASE Statements Use in the SELECT clause when you want to check and possibly modify a column value before it is displayed Let’s go over the syntax first, and then go over some tips and examples

33 CASE: Switch Style Syntax: CASE case_value WHEN when_value THEN statement WHEN when_value THEN statement … ELSE statement END It’s like saying (in C/C++/Java): if(case_value = when_value) statement; else if(case_value = when_value) statement; … else statement;

34 CASE: IF-ELSE Style Syntax: CASE WHEN condition THEN statement WHEN condition THEN statement … ELSE statement END It’s like saying (in C/C++/Java): if(condition) statement; else if(condition) statement; … else statement;

35 CASE Example #1 Example: -- List the names of all movie-related people along with their height in meters. If their height is unknown, display 'Unknown' instead of NULL. SELECT FirstName, LastName, CASE WHEN Height IS NULL THEN 'Unknown' ELSE Height END FROM People;

36 CASE Example #2 Example: List the names of all movie-related people along with their gender. Males should be listed as ‘Male’ and females should be listed as ‘Female’. SELECT FirstName, LastName, CASE Gender WHEN 'M' THEN 'Male' ELSE 'Female' END FROM People;

37 Column Aliases Last CASE example had a really long column name. To get rid of that we can use column aliases SELECT expression AS alias FROM … alias can be a single or compound word string AS 'Gender' AS 'Male or Female' alias can be a single word identifier AS Gender AS MaleOrFemale

38 Column Alias Example Example: SELECT FirstName, LastName, CASE Gender WHEN 'M' THEN 'Male' ELSE 'Female' END AS 'Gender' FROM People;

39 DISTINCT Use when you want to remove duplicate results Example: --Display a list of unique countries that all members come from (wrong answer). SELECT Country FROM Members; --Display a list of unique countries that all members come from (correct answer). SELECT DISTINCT Country FROM Members;


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

Similar presentations


Ads by Google