Tarik Booker CS 122. What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses,

Slides:



Advertisements
Similar presentations
Writing Basic SQL SELECT Statements. Capabilities of SQL SELECT Statements A SELECT statement retrieves information from the database. Using a SELECT.
Advertisements

Introduction to Structured Query Language (SQL)
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
2 Copyright © 2004, Oracle. All rights reserved. Restricting and Sorting Data.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 5: Subqueries and Set Operations.
Introduction to Structured Query Language (SQL)
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the 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 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
Chapter 2 Basic SQL SELECT Statements
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 2 Basic SQL SELECT Statements Oracle 10g: SQL.
Chapter 10 Queries and Updating Part C. SQL Copyright 2005 Radian Publishing Co.
Chapter 3 Single-Table Queries
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
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 =,
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting MySQL – Selecting Data.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
IFS Intro to Data Management Chapter 5 Getting More Than Simple Columns.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
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.
2 Copyright © 2004, Oracle. All rights reserved. Restricting and Sorting Data.
2 Copyright © 2009, Oracle. All rights reserved. Restricting and Sorting Data.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
1 Chapter 2 Basic SQL SELECT Statements. 2 Chapter Objectives Distinguish between an RDBMS and an ORDBMS Identify keywords, mandatory clauses, and optional.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Simple Queries DBS301 – Week 1. Objectives Basic SELECT statement Computed columns Aliases Concatenation operator Use of DISTINCT to eliminate duplicates.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
Limiting Selected Rows. 2-2 Objectives Sort row output using the ORDER BY clause. Sort row output using the ORDER BY clause. Enter search criteria using.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 2. Single Table Queries.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
CS 122: Lecture 3 Joins (Part 1) Tarik Booker CS 122 California State University, Los Angeles October 7, 2014.
Lecture 7: Subqueries Tarik Booker California State University, Los Angeles.
Oracle 10g Retrieving Data Using the SQL SELECT Statement.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
CHAPTER 7 DATABASE ACCESS THROUGH WEB
Chapter 5 Introduction to SQL.
CS122 Using Relational Databases and SQL
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Writing Basic SQL SELECT Statements
JDBC.
CS122 Using Relational Databases and SQL
Writing Basic SQL SELECT Statements
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
CS122 Using Relational Databases and SQL
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
CS122 Using Relational Databases and SQL
Shelly Cashman: Microsoft Access 2016
Presentation transcript:

Tarik Booker CS 122

What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses, Boolean clauses, LIKE, BETWEEN, IS NULL, IN, AND, OR, NOT, CASE ORDER BY

Tables (Review) Remember Tables! Organized list of elements. Lyric Database Composed of Various Tables Different Keys Primary Key – Entirely Distinct Values Primary Key for GET? Now we want to retrieve data from those tables.

The SELECT Statement Remember this statement from the MySQL install verification SELECT * FROM Salespeople; Used to retrieve info from a database Can use to select and display specific data Specified by user

SELECT Statement (2) Structure of a SELECT Statement SELECT columns FROM tablename WHERE condition ORDER BY columns Rows Columns

SELECT Statement (3) SELECT Selects what columns you want to display Using * Selects ALL Columns SELECT * FROM Salespeople; For a few columns, (not all) use comma to separate: SELECT ArtistName, City FROM Artists; FROM Determines what table to SELECT from SELECT FROM most common SQL statement SELECT ArtistName FROM Artists; SELECT * FROM Artists;

Select Statement (4) After loading (source) the Lyric Database: Try: SELECT * from Artists; SELECT ArtistName from Artists;

SELECT DISTINCT Eliminates Duplicates from the selection SELECT DISTINCT ArtistName FROM Artists; Will only display one copy of each name For multiple fields, will only display unique combinations SELECT DISTINCT City, Region FROM Members;

Calculated Columns You can perform calculations on columns! SELECT Expression AS new_column_name FROM Table; The results of the expression is made into “new_column_name” Called a column Alias AS Keyword not required (in MySQL), but still good practice Required in MS Access!!! SELECT LengthSeconds/60 AS LengthMinutes FROM Tracks;

Calculated Columns (2) Common Mathematic Operators (for MySQL) +Addition -Subtraction *Multiplication /Division Mod (x,y)Modulo Function Returns Remainder Mod (5,3) Mod (9,3) Mod (8,2)

Other (Note: If your field or table names contain a space in them, use square brackets [] around them. Also use if names are the same as SQL commands (such as group, order, etc.) Good practice to not use SQL keywords as names

WHERE Clauses Remember: SELECT columns FROM tablename WHERE condition ORDER BY columns SELECT retrieves ALL the rows What if I only want to retrieve a few rows? Use WHERE to restrict rows in the result set Can compare a field to a value, a field to a field Can also compare any calculated expression to a field, value, or other calculated expression (super fancy!)

WHERE (2) Keep correct order! The WHERE clause is always AFTER the FROM statement! Not case-sensitive in MySQL, but is in others! Use Comparisons! Comparison Operators (MySQL): = <> or != =

WHERE (3) Example: SELECT TrackTitle, LengthSeconds FROM Tracks WHERE LengthSeconds > 240;

Date WHERE Clauses WHERE can compare Dates MySQL uses single quotes to specify dates ‘30-Sep-2014’ SELECT FirstName, LastName, Birthday FROM Members WHERE Birthday >=‘01-Jun-1979’; Read as “on or after”

Boolean Where Clauses Boolean – Results in True or False Usually True = 1 and False = 0 (for MySQL) This convention not used for all DBMS Not even used for all Programming Languages! SELECT TrackTitle, RealAud FROM Tracks WHERE RealAud = 0;

LIKE Allows you to test text fields for a group of letters Uses symbols to stand for other letters WHERE TrackTitle LIKE ‘%time%’ % Can Represent any string of characters Called a wildcard What happens if I use ‘%time’ ? ‘time%’ ? ‘%a%k%’ ? Remember, MySQL is not case-sensitive!

BETWEEN Way to choose results between two values Inclusive ( Includes both values in result) Works well with dates, numeric and text values Dates and Text, fairly obvious Text Value Sorting Alphabetically Nulls before any character! Null – Empty, or End of Text Value Ex: Tom vs. Tommy Ex: WHERE LastName Between ‘A’ and ‘Mzzzz’ Be careful with ending Nulls!!!

BETWEEN (2) BETWEEN some_value AND some_other_value SELECT LastName, FirstName FROM Members WHERE LastName BETWEEN ‘A’ and ‘Mzzz’; What happens if I use: WHERE LastName BETWEEN ‘A’ and ‘M’; ? Watch your ending nulls.

IS NULL Tests for Empty Field Values Explained Null!! However… Text Fields can Vary Can be text value, null, or empty text value Empty text? WHERE condition: fieldname=‘’ Two single quotes with nothing between Counts as “empty text” instead of null! Sometimes used in databases! Be careful!!

IS NULL (2) SELECT ArtistName FROM Artists WHERE WebAddress IS NULL; Where are the nulls?

IN Tests if a field matches a specified value WHERE field_value IN (value1, value2, etc) Use single quotes for text ‘test1’ For multiple values it’s either/or Either in value1, or value2, or… Note: MySQL can not use IN with dates! SELECT LastName, FirstName, City, Region FROM Members WHERE Region IN (‘IN’, ‘IL’, ‘OH’);

AND & OR Boolean operators Operate on boolean values True (1) or False (0) WHERE Region=‘GA’ AND SalesID=2 WHERE Region=‘GA OR SalesID=2 AND True AND True = ? True AND False = ? False AND True = ? False AND False = ? OR True OR True = ? True OR False = ? False OR True = ? False OR False = ?

AND & OR (2) If one thing is FALSE, the AND statement is always FALSE The only way an AND statement is TRUE is if all statements are TRUE If one thing is TRUE, the OR statement is always TRUE The only way to make an OR statement FALSE is if all statements are FALSE AND True AND True = T True AND False = F False AND True = F False AND False = F OR True OR True = T True OR False = T False OR True = T False OR False = F

AND & OR (3) Can be used with parentheses! WHERE (Region=‘GA’ OR Region=‘TX’) AND SalesID=2 Process parentheses first! You can string together as many AND’s and OR’s as you’d like Use parentheses when needed

NOT Another boolean operator Returns values that don’t match the value Use parentheses around statement you want to declare NOT Parentheses are mandatory in MySQL (for NOT) SELECT ArtistName, WebAddress FROM Artists WHERE NOT (WebAddress IS NULL);

NOT (2) SELECT ArtistName, WebAddress FROM Artists WHERE NOT (WebAddress IS NULL); What is returned?

Mixing AND, OR, NOT You can always mix these operators to create various statements Be careful Use parentheses when necessary SELECT FirstName, Region, Gender FROM Members WHERE Not (Region=’VA’ And Gender=’F’) Results?

CASE Statement SQL Has CASE statements Will see in other languages (Java, C++, etc) Allows you to evaluate multiple fields at once Returns into an column Alias (remember?) Two versions of CASE Simple CASE Searched CASE

Simple CASE Statement SELECT Field, Field, CASE Field | Expression WHEN value THEN result ELSE result END As alias FROM Table ELSE Statement is optional

Simple CASE Statement (2) Select Artistname, Region, Case Region When 'NC' Then 'South' When 'VA' Then 'South' When 'IL' Then 'Midwest' When 'VT' Then 'New England' Else 'Somewhere Else' End As Area From Artists

Searched CASE Statement SELECT Field, Field, CASE WHEN Field | Expression comparison Value | Field | Expression THEN result WHEN Field | Expression comparison Value | Field | Expression THEN result ELSE result END As alias FROM Table

Searched CASE Statement (2) Select TrackNum, TrackTitle, LengthSeconds, Case When TrackNum=1 And LengthSeconds<240 Then ‘Short 1st Track’ When TrackNum=1 And LengthSeconds>480 Then ‘Long 1st Track’ Else ‘Another Track’ End as Eval From Tracks Where TrackNum<3

ORDER BY Sorts Results in a Particular Order Default is ascending order Choose descending order with DESC SELECT ArtistName FROM Artists ORDER BY ArtistName DESC; ORDER BY is the last line in the SQL Statement!

ORDER BY (2) You can use multiple ORDER BY statements Used as “tie-breakers” Second statement orders duplicate fields in the first statement (and so on) Select Title, Genre From Titles Order By Genre, Title

ORDER BY (3) Can use expressions in ORDER BY The extreme case: Select TrackNum, TrackTitle, LengthSeconds, Case When TrackNum=1 And LengthSeconds<240 Then ‘Short 1st Track’ When TrackNum=1 And LengthSeconds>480 Then ‘Long 1st Track’ Else ‘Another Track’ End as Eval From Tracks Where TrackNum < 3 Order By Case When TrackNum = 1 And LengthSeconds < 240 Then ‘Short 1st Track’ When TrackNum = 1 And LengthSeconds > 480 Then ‘Long 1st Track’ Else ‘Another Track’ End