380 likes | 463 Views
SQL – the real things. Chapter 4. Structured Query Language. Structured Query Language (SQL) was developed by the IBM Corporation in the late 1970s. SQL was endorsed as a United States national standard by the American National Standards Institute (ANSI) in 1992 [ SQL-92 ].
E N D
SQL – the real things Chapter 4
Structured Query Language • Structured Query Language (SQL) was developed by the IBM Corporation in the late 1970s. • SQL was endorsed as a United States national standard by the American National Standards Institute (ANSI) in 1992 [SQL-92].
SQL as a Data Sublanguage • SQL is not a full featured programming language as are C, C#, and Java. • SQL is a data sublanguage for creating and processing database data and metadata. • SQL is ubiquitous in enterprise-class DBMS products. • SQL programming is a critical skill.
The SQL SELECT Statement • The simplest sturcute for SQL query states is the SQL SELECT statement: SELECT {ColumnName(s)} FROM {TableName(s)} • All SQL statements end with a semi-colon (;), unless you are using Microsoft products such as SQL Server or Access
Specific Columns on One Table SELECT PERSON_GIVEN_NAME, PERSON_FAMILY_NAME, PERSON_ADDRESS_COUNTRY FROM PERSON; Get every person’s given name, family name, and country
Change the column order SELECT PERSON.PERSON_FAMILY_NAME, PERSON.PERSON_GIVEN_NAME, PERSON.PERSON_ADDRESS_COUNTRY FROM PERSON; Get every person’s family name, given name, and country
The DISTINCT Keyword SELECT PERSON_FAMILY_NAME FROM PERSON; • SELECT DISTINCT PERSON_FAMILY_NAME FROM PERSON; DISTINCT removes all duplicated rows
Show everything SELECT * FROM LANGUAGE; This one shows the entire table
Specific Rows from One Table SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON.PERSON_FAMILY_NAME ='Schmidt'; NOTE: SQL wants a plain ASCII single quote: ' NOT ‘!
Sorting the Results: ORDER BY SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON_FAMILY_NAME ='Schmidt‘ ORDER BY PERSON_GIVEN_NAME
Sorting the Results: ORDER BY SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON_FAMILY_NAME ='Schmidt‘ ORDER BY PERSON_GIVEN_NAME DESC NOTE: The default sorting order is ASC – does not have to be specified.
WHERE Clause Options: AND SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON_FAMILY_NAME='Schmidt' AND PERSON_GIVEN_NAME = 'Karl'
WHERE Clause Options: OR SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON_FAMILY_NAME='Schmidt' OR PERSON.PERSON_ADDRESS_STATE_PROV='CO‘
WHERE Clause Options: OR SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON_ADDRESS_STATE_PROV ='CA' OR PERSON_ADDRESS_STATE_PROV='CO'
WHERE Clause Options: IN SELECT PERSON_FAMILY_NAME, PERSON_GIVEN_NAME FROM PERSON WHERE PERSON_ADDRESS_STATE_PROV in ('CA', 'CO') NOTE: This is the same result but very different approach!
WHERE Clause Options:LIKE and Wildcards • The SQL keyword LIKE can be combined with wildcard symbols: • SQL 92 Standard (SQL Server, Oracle, etc.): • _ = Exactly one character • % = Any set of one or more characters • MS Access (based on MS DOS) • ? = Exactly one character • * = Any set of one or more characters
Like In MS Access -- list languages with the letter c in names SELECT LANGUAGE.* FROM [LANGUAGE] WHERE LANGUAGE.[language_name] Like '*c*'; In other DBMS and standard, this should be SELECT LANGUAGE.* FROM [LANGUAGE] WHERE LANGUAGE.[language_name] Like ‘%c%';
Subquery • Generally, another SELECT statement can be part of the FROM clause or the Where clause. When it is part of the WHERE clause, we call it a subquery. • For example – list movie titles that are more expensive than average VHS price SELECT.MOVIE_TITLE FROM MOVIE WHERE RETAIL_PRICE_VHS> ( SELECT avg(MOVIE.RETAIL_PRICE_VHS) FROM MOVIE);
Subquery (2) SELECT MOVIE_TITLE, MPAA_RATING_CODE FROM MOVIE where MPAA_RATING_CODE in (select MPAA_RATING_CODE from MPAA_RATING where MPAA_RATING_CODE like 'PG%‘ )
Join • Like subquery, join allows you to take advantage of this “Integrated” characteristic of databases • When pulling (displaying) data from two tables, you must use join • Join start from PRODUCT, see page 128 and 129 for an example and discussion on PRODUCT or CARTESIAN PRODUCT • JOIN, without indexes, is the most expensive operation
Join example • List the movie title and genre description SELECT MOVIE_TITLE, MOVIE_GENRE_DESCRIPTION FROM MOVIE_GENRE INNER JOIN MOVIE ON MOVIE_GENRE.MOVIE_GENRE_CODE = MOVIE.MOVIE_GENRE_CODE; Or SELECT MOVIE_TITLE, MOVIE_GENRE_DESCRIPTION FROM MOVIE_GENRE, MOVIE Where MOVIE_GENRE.MOVIE_GENRE_CODE = MOVIE.MOVIE_GENRE_CODE; These two SQL statements ALWAYS give the same result
Join example -- more • List the movie titles and genre descriptions for movies with title starting with letter c SELECT MOVIE_TITLE, MOVIE_GENRE_DESCRIPTION FROM MOVIE_GENRE INNER JOIN MOVIE ON MOVIE_GENRE.MOVIE_GENRE_CODE = MOVIE.MOVIE_GENRE_CODE where movie_title like 'c*‘ SELECT MOVIE_TITLE, MOVIE_GENRE_DESCRIPTION FROM MOVIE_GENRE, MOVIE Where MOVIE_GENRE.MOVIE_GENRE_CODE = MOVIE.MOVIE_GENRE_CODE and movie_title like 'c*'
Subqueries versus Joins • Subqueries and joins both process multiple tables. • Since SQL statement can only “output” data on the top level, columns in a subquery cannot be displayed if they are not from the top level tables. • Join can be used together with subquery. • All the other clause such as WHERE and ORDER BY can be combined with JOINs and subqueries
Outer Join • The following statement SELECT MOVIE_GENRE_DESCRIPTION, MOVIE_TITLE FROM MOVIE_GENRE Inner JOIN MOVIE ON MOVIE_GENRE.MOVIE_GENRE_CODE = MOVIE.MOVIE_GENRE_CODE; Shows a genre description iff a movie of the genre exists • This statement SELECT MOVIE_GENRE_DESCRIPTION, MOVIE_TITLE FROM MOVIE_GENRE LEFT OUTER JOIN MOVIE ON MOVIE_GENRE.MOVIE_GENRE_CODE = MOVIE.MOVIE_GENRE_CODE Shows ALL genre description regardless if a movie of the genre exists, if no movie exists, show NULL on the title
Self Join SELECT A.PERSON_ID, B.PERSON_ID FROM EMPLOYEE AS B INNER JOIN EMPLOYEE AS A ON B.SUPERVISOR_PERSON_ID = A.PERSON_ID; Shows the manager’s id and her people. A few things to notice: (1) we can rename our tables, and (2) we can join a table with itself only after renaming it
More interesting self join SELECT PA.PERSON_GIVEN_NAME + ' '+ PA.PERSON_FAMILY_NAME + ' manages ' + PB.PERSON_GIVEN_NAME + ' '+ PB.PERSON_FAMILY_NAME as Manager FROM PERSON AS PB INNER JOIN (PERSON AS PA INNER JOIN (EMPLOYEE AS B INNER JOIN EMPLOYEE AS A ON B.SUPERVISOR_PERSON_ID = A.PERSON_ID) ON PA.PERSON_ID = A.PERSON_ID) ON PB.PERSON_ID = B.PERSON_ID;
Even more self join • List movies with the same price SELECT M2.MOVIE_TITLE, Movie.MOVIE_TITLE, MOVIE.RETAIL_PRICE_VHS, M2.RETAIL_PRICE_VHS FROM MOVIE INNER JOIN MOVIE AS M2 ON (MOVIE.RETAIL_PRICE_VHS = M2.RETAIL_PRICE_VHS) and movie.movie_id < m2.movie_id;
SQL Built-in Functions • There are five SQL Built-in Functions: • COUNT • SUM • AVG • MIN • MAX
Buildin Function Example SELECT Count(*) AS Movie_Count, Avg(RETAIL_PRICE_DVD) AS Average_DVD_Price, Min(RETAIL_PRICE_DVD) AS min_DVD_Price FROM MOVIE; Notice, that this always return just one row. If two or more rows are necessary, we need to use GROUP BY
Build in Function With – GROUP BY SELECT MOVIE_GENRE_CODE, Count(*) AS Movie_Count, Avg(RETAIL_PRICE_DVD) AS Average_DVD_Price, Min(RETAIL_PRICE_DVD) AS min_DVD_Price FROM MOVIE group by MOVIE_GENRE_CODE
Build in Function With – GROUP BY SELECT MOVIE_GENRE_CODE, Count(*) AS Movie_Count, Avg(RETAIL_PRICE_DVD) AS Average_DVD_Price, Min(RETAIL_PRICE_DVD) AS min_DVD_Price FROM MOVIE group by MOVIE_GENRE_CODE HAVING count(*) > 2
DDL – Create table CREATE TABLE Persons(P_Idint NOT NULL,LastNamevarchar(255) NOT NULL,FirstNamevarchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))
Update operators in SQL - Insert • Insert with values INSERT INTO TEMP (PNo, Color) Values(‘P200’, ‘Green’) • Insert is implemented by INSERT INTO INSERT INTO TEMP (PNo, Color) SELECT PNumber, Color FROM P WHERE COLOR = ‘Red’;
Update operators in SQL - Delete • Delete is implemented by DELETE DELETE FROM SP WHERE PNO = ‘P2’; • Deletes all shipments for part P2 • To delete P2 from part, you need to delete P2 records from SP first
Update operators in SQL - Update • Update is implemented by UPDATE UPDATE S SET STATUS = 2 * STATUS, CITY = ‘Rome’ WHERE CITY = ‘Paris’; • Doubles the status of the Parisian suppliers and moves them to Rome.
Some books • SQL Cookbook (Cookbooks (O'Reilly)) • SQL in a Nutshell (In a Nutshell (O'Reilly)) • Sams Teach Yourself SQL in 10 Minutes (4th Edition) • Microsoft SQL Server 2012 T-SQL Fundamentals