intro to t-sql – 2nd session
DESCRIPTION
22 may 2011 by Me in DevMixTRANSCRIPT
Agenda
1. Select the DBMS we will use2. Select Database to work on3. PUBS Database4. Databases and tables5. Connecting to your database6. Change databases7. Some rules for SQL8. Overview of PUBS database9. First Select Command
Agenda cont.
10. Concatenate two columns11. Alias12. Where & compound criteria13. Comparison operators14. Range15. Wild cards16. Escape characters17. Pattern matching18. Negation
Database Management System
• There are many RDBMSs that is used such as: Oracle SQL server MySQL SQLite … etc.
• In this class we will use the SQL server as our DBMS, Because it’s the most interactive one in out case.
SQL server 2005 or 2008
• We need a SQLserver to interact with Database through queries as DBMS.
• Download from :http://www.microsoft.com/sqlserver/2005/en/us/express.aspx
• We need any version of SQL server(2005 or 2008).
Select Database to work on
• I selected the Northwind simple database to make our queries on.
• You can download it from: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034
title_id = title_id
title_id = title_id
title_id = title_id
stor_id = stor_id
stor_id = stor_id
pub_id = pub_id
pub_id = pub_id
pub_id = pub_id
job_id = job_id
au_id = au_id
authors
au_id varchar(11)au_lname varchar(40)au_fname varchar(20)phone char(12)address varchar(40)city varchar(20)state char(2)zip char(5)contract bit
authors_tmp
au_lname varchar(40)au_fname varchar(20)phone char(12)address varchar(40)city varchar(20)state char(2)zip char(5)
discounts
discounttype varchar(40)stor_id char(4)lowqty smallinthighqty smallintdiscount decimal
employee
emp_id char(9)fname varchar(20)minit charlname varchar(30)job_id smallintjob_lvl tinyintpub_id char(4)hire_date datetime
jobs
job_id smallintjob_desc varchar(50)min_lvl tinyintmax_lvl tinyint
pub_info
pub_id char(4)logo imagepr_info text
publishers
pub_id char(4)pub_name varchar(40)city varchar(20)state char(2)country varchar(30)
roysched
title_id varchar(6)lorange inthirange introyalty int
sales
stor_id char(4)ord_num varchar(20)ord_date datetimeqty smallintpayterms varchar(12)title_id varchar(6)
stores
stor_id char(4)stor_name varchar(40)stor_address varchar(40)city varchar(20)state char(2)zip char(5)
titleauthor
au_id varchar(11)title_id varchar(6)au_ord tinyintroyaltyper int
titles
title_id varchar(6)title varchar(80)type char(12)pub_id char(4)price moneyadvance moneyroyalty intytd_sales intnotes varchar(200)pubdate datetime
PUBS Database
Databases At the most basic level a database is really just a file.
Databases come in all shapes and sizes. Some are large and some are small. But each database generally serves a particular purpose.
Examples: Tracking employee payroll, sales data on a particular sales line, stock data for a particular industry
All databases are made up of objects. The most important object (and the one we will learn how to use in this class) is a table.
A table is a storage structure made up of rows and columns. (Sort of like a spreadsheet.)
Due to the differing terminologies, there are interchangeable sets of terms:
Database Mathematical Data ProcessingTable Relation FileRow Tuple RecordColumn Attribute Field
These terms are used interchangeably, but we will generally use the table – row – column terminology
Tables
A query as the term implies is a question we ask the database.
The same procedure gives the same result with the same database in any other DBMS.
Regardless of name, they all perform the same purpose. This is to give you an interface for sending SQL statements and receiving results.
Connect to a database
1. Startup ISQL/W2. Login window3. A SQL Server can have many different databases running on it at
the same time. 4. Database setup on the server 5. Assign databases6. Your first SQL statement7. use <database>8. This tells the SQL Server what database you will be using to
perform your queries.9. Example: use PUBS1
SQL Server Login
• To check the database you are accessing use:• select db_name()• Throughout this course some of the things we
discuss will be MS SQL Server specific. The DBMS you are using should have a command or function similar to this, but not necessarily the same.
Verify your database
SQL keywords (use, select, from, where, etc.) are case insensitive.
select is the same as SELECT is the same as SeLeCt, etc.
However depending on the DBMS (Database Management System), the columns might be case sensitive.
The databases we have setup on our server are case insensitive.
Basic syntax rules
Spacing does not matter (for the most part).
select CustomerID…is the same asselect CustomerID …
However, you must still separate words. You can not use the following:
selectCustomerID… This will give a syntax error, because SQL Server must be able to find your SQL keywords.
Rules cont.
Carriage returns are ignored
select CustomerID from Customersis the same asselect CustomerIDfrom Customers
The spacing and carriage returns just make reading your SQL a lot easier.
The general format used by most people is to place the separate clauses of the statement on different lines
Rules cont.
This is the database for which you have an ER diagram for.
ER diagram explanation
You will generally get an ER diagram at each client when you begin work on a project. If you don’t have one, ask for one. This will save time in trying to determine what data is where and how everything is linked together. If you can’t get one, don’t panic! There are ways to get the database to tell you what it contains.
PUBS Database
PUBS Database example
title_id = title_id
title_id = title_id
title_id = title_id
stor_id = stor_id
stor_id = stor_id
pub_id = pub_id
pub_id = pub_id
pub_id = pub_id
job_id = job_id
au_id = au_id
authors
au_id varchar(11)au_lname varchar(40)au_fname varchar(20)phone char(12)address varchar(40)city varchar(20)state char(2)zip char(5)contract bit
authors_tmp
au_lname varchar(40)au_fname varchar(20)phone char(12)address varchar(40)city varchar(20)state char(2)zip char(5)
discounts
discounttype varchar(40)stor_id char(4)lowqty smallinthighqty smallintdiscount decimal
employee
emp_id char(9)fname varchar(20)minit charlname varchar(30)job_id smallintjob_lvl tinyintpub_id char(4)hire_date datetime
jobs
job_id smallintjob_desc varchar(50)min_lvl tinyintmax_lvl tinyint
pub_info
pub_id char(4)logo imagepr_info text
publishers
pub_id char(4)pub_name varchar(40)city varchar(20)state char(2)country varchar(30)
roysched
title_id varchar(6)lorange inthirange introyalty int
sales
stor_id char(4)ord_num varchar(20)ord_date datetimeqty smallintpayterms varchar(12)title_id varchar(6)
stores
stor_id char(4)stor_name varchar(40)stor_address varchar(40)city varchar(20)state char(2)zip char(5)
titleauthor
au_id varchar(11)title_id varchar(6)au_ord tinyintroyaltyper int
titles
title_id varchar(6)title varchar(80)type char(12)pub_id char(4)price moneyadvance moneyroyalty intytd_sales intnotes varchar(200)pubdate datetime
Ok, Lets talk about commands (Queries)
Select
A select statement is used to retrieve data from a database.
In order to get information from the database, you must tell the database what you are looking for. The first step along this journey is to get some simple information from the database.
select 'Mary had a little lamb.'
--------------Mary had a little lamb.(1 row affected)
Select An asterisk (*) is used to designate all columns in a table.
select *
We also need to tell it which table to get the data from.
select * from authors
The main sections in every SQL statement are called clauses. The three clauses we will focus on are the select, from, and where
We can limit the columns returned by specifying them instead of using *.
select author_id , author_name from authors
Concatenation
We can also combine data together. This is called concatenation.
We really want to display the first name and the last name separated by a space and then the rest of the data. The plus symbol (+) is the most widely used symbol for concatenation.
Concatenation is used for string (character) data. If a concatenation operator (+) is used on numeric data, the data is simply added together.
The title for our previous result set isn't too informative, and we really don't want to display our formula.
We can rename or alias a column in two ways Use a space and then the alias Specify the keyword as and then the alias
We can apply aliases in two places within our SQL statements Select clause From clause
Aliases
Where
• So far we have returned the entire contents of a table.
• This is usually not very practical
• Suppose we wanted to see the authors that live in California.
• We could do a select * from authors and scroll through the result set looking for those where state = CA
• While feasible for a small table, this is not practical.
Compound criteria
• This limited our result set to just those authors in CA• But our list of authors could begin to get very large and
we’re only looking for those authors with a last name of Green.
• We would do this with the following:select au_lname, au_fname, state from authors where
state = 'CA' and lname = 'Green'
• Important Note : our DBMS might be case insensitive but the actual values of the data is case sensitive.
• So, Green not equal to GREEN
Compound criteria
• Now that we know how to get just those authors who live in CA, how do we get the authors that live in KS also?
• We accomplish this through the use of an OR instead of an AND
• select * from authors where state = 'CA' or state = 'KS'
Compound criteria
• So, what is the difference between using an AND and an OR?
• The AND is exclusive– This means that the row must meet all of the conditions in order to be
selected
• The OR is inclusive– This means that for a row to be selected, it has to meet just one of the criteria
Compound criteria
• You group by using parenthesis• The proper SQL statement is as follows:• select * from authors where (state = 'KS' and
lname = 'Smith') or state = 'CA'
• Note that: this is differ from the group by clause that will be discussed later in this class
Comparison
• Besides using an =, you can also use any of the other comparison operators: >, <, <=, >=,<>.
• If you want to get employees whose salary greater than 2000.
• It will be:select * from employees where salary > 2000
Range
• Suppose we want to select all authors who live in CA, MI, KS, and UT.. What will you do ??
• Instead of using multiple ORs, we can use an IN operator
select au_lname, state from authors where state in ('CA','KS','MI','UT')
Range
• We now want to select all books that have a price greater than or equal to $10, but also less than or equal to $20.. What will you do ?
• SQL has given us a between operatorselect title_id, price from titles where price between 10 and 20
Wild Cards
• SQL has two wildcard characters– The percent (%) symbol designates any string of
zero or more characters– The underscore (_) designates a single character
• Suppose we wanted to select all authors whose first names start with M
select au_fname, au_lname from authors where au_fname like 'M%'
Escape Characters
• But what happens when we really want to find a % inside of the data
• To find this data we will employ an escape character
select notes from titles where notes like '%@%%' escape '@'
• This tells the DBMS to treat the next character after the escape character (@) as a literal string
Pattern Matching
• Suppose we wanted to retrieve all of the authors whose last names started with either an L, M, or Sselect au_lname, au_fname from authors where au_lname like '[LMS]%‘
• We do not want to retrieve name names like McDayselect au_lname, au_fname from authors where au_lname like '[A-Z][a-z][a-z][a-z]'
Pattern Matching
• We now want to retrieve just those authors whose first name is four characters longselect au_lname, au_fname from authors where au_fname like '____' (That's four underscore characters)
---------------------------------------------------------------------select * from authors where au_fname like '[^ ] [^ ] [^ ] [^ ]‘
• The caret is a negation operator. The query above says to retrieve any first names that do not have a space as one of the four characters
Negation
• We briefly touched on negation a few slides before.
• The negation operator is NOT or in patterns a caret (^)select au_fname, au_lname from authors where au_fname not like '[^ ] [^ ] [^ ] [^ ]'
• Select all authors who do not live in CAselect * from authors where state <> 'CA'
The End
OkLets Query*
* Means to write queries in SQL server