Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
78 views

Handout 3 - Introduction To SQL

This document provides an introduction to SQL and the Transact-SQL (T-SQL) language. It begins with an overview of some basic T-SQL data types and their storage sizes. It then discusses naming conventions for database objects like tables and columns. The document also covers using NULL values in columns and how to open and run queries using SQL Server Query Analyzer. Finally, it provides an overview of basic SQL queries, focusing on SELECT statements and concepts like projection, selection, and joins.

Uploaded by

Roha Cbc
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Handout 3 - Introduction To SQL

This document provides an introduction to SQL and the Transact-SQL (T-SQL) language. It begins with an overview of some basic T-SQL data types and their storage sizes. It then discusses naming conventions for database objects like tables and columns. The document also covers using NULL values in columns and how to open and run queries using SQL Server Query Analyzer. Finally, it provides an overview of basic SQL queries, focusing on SELECT statements and concepts like projection, selection, and joins.

Uploaded by

Roha Cbc
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

CCI – Computer Science Dept 655445328.

doc

Haramaya University
College of Computing and Informatics

Computer Science Department

Comp 221: Database with SQL Server

Handout 3 – Introduction to SQL

RECOMMENDED TEXTS:

• Ref A: “SQL Server 2000 – The Complete Reference”


Jeffrey R. Shapiro,
Osborne McGraw Hill

1 Transact-SQL Data Types

Some of the basic T-SQL data types are shown in the table below. Every column in a table
must have a data type. The other DBMSs we have mentioned in class also have these data
types, although some may vary in terms of the number of characters allowed and the storage
space.
The storage size refers to the amount of disk space required to store the value. Whilst this
may not be important when working with small databases, space may be an issue when
working with larger databases.
The data type of a column affects how the column is treated in SQL queries e.g. comparison
values for a character type should be in string delimiters, numerical types do not need
delimiters.

Type Full name (from Description Storage size


SQL-92 standard)
Int Integer Whole numbers from - 2^31 (- 4 bytes
2,147,483,648) through to 2^31 -
1 (2,147,483,647)
Float(n) Double precision floating point number data from - 1<=n<=24 is 4 bytes
1.79E + 308 through 1.79E + 308 25<=n<=53 is 8 bytes
n is the number of bits used to
store the mantissa of the float
number in scientific notation – it
can be in the range 1 to 53
char(n) Character(n) Fixed-length character data n bytes
where the length is n; n must be
in the range 1 to 8000.
If n is not specified, the default is
1.
varchar(n) Character varying Variable-length character data Depends on the number

Page 1 of 9
CCI – Computer Science Dept 655445328.doc

where the maximum length is n; of characters entered (1


n must be in the range 1 to 8000. character = 1 byte)
If n is not specified, the default is
1.
datetime DateTime Date or date-time values in the 8 bytes
range January 1, 1753 through to
December 31, 9999 - to an
accuracy of one three-hundredth
of a second (so if

2 Naming of Objects
Tables in SQL are referred to by the table name.
The name is usually also qualified with the owner of the table – this is the SQL Server user
that created the table. The ‘dbo’ user owns objects created by the database administrator. The
db owner usually creates objects.
Therefore the fully qualified name for a table named ‘Titles’ would be:

dbo.Titles

The name can be further qualified by putting the database name in front of it. This is to
avoid confusion if tables of the same name exist in different databases. For example:

Pubs.dbo.Titles

refers to the Titles table in the Pubs database.

The owner name can be omitted in some cases:

Pubs..Titles
(note the two dots, to indicate that the owner name is omitted).

Columns in a table are referred to by prefixing them with the table name. For example:
Titles.Title_ID
Titles.type

All other objects in a database are named (views, indexes, stored procedures etc) and can be
referred to by name, in the same way as tables i.e. owner.object_name.

3 Using NULLs
In a relational database, it is possible to specify that a column can contain a NULL value.
If a column contains the value NULL, it means that the value is unknown or could not be
determined. This is different to a blank or zero value.

Using NULLs means that you can distinguish between entries that represent a deliberately
placed zero or where either the data is not recorded (blanks) and where a NULL has been
explicitly entered.

For example, in the pubs database, a NULL in the Titles.Price column does not mean that the
book is free or has no price. It means that the price is not known or has not yet been
determined.

Page 2 of 9
CCI – Computer Science Dept 655445328.doc

NULL values cannot be used in a column that is used to distinguish one row from another –
i.e. in primary and foreign keys. When creating a table with SQL, it is necessary to specify if
each column allows NULLs or not.
When carrying out comparisons, NULL values in different tables are not seen as being equal
to each other.

4 Using the SQL Server Query Analyzer


Now – you need to start writing some queries!
4.1 Starting the Query Analyzer
There are two ways to start the Query Analyzer. The first is to start it through the Programs
menu –
Start -> Programs - > MS SQL Server -> Query Analyzer
When it opens, it will present a dialog to login to a server:
- Choose the server
- Choose Windows Authentication if your network login has access to the SQL Server,
otherwise you need a SQL login name and password.

The Query Analyzer will open with a blank query window.


The menu across the top includes a drop-down list of the available databases on the
server.
If no other default database has been set, it will be in the Master database.
You should change this to the database you want to work in. Always check that you are in
the correct database before running a query.

The second way to open it is from inside the Enterprise Manager.


- Choose Tools on the menu
- Choose SQL Query Analyzer
- The Query Analyzer will open, and if you were already connected to a database in the
Enterprise Manager, it will be open in that database.

The main pane in Query Analyzer is the Editor Pane, in which you type your queries.
The Object Browser to the left of the Editor Pane (if you cannot see it, choose Tools ->
Object Browser from the menus) shows you all the objects in each database on the server.

4.2 Running a Query


To run a query:
- type the query text into the Editor Pane
- to execute the query –
 choose Query -> Execute
 OR hit the F5 key
 OR click the Execute button on the toolbar (the green arrow head)
 OR hit CTRL and E

For example, to select all the records from the publishers table:
- Type in 'select * from publishers', in the Editor Pane
- Hit F5
- the results of the query are displayed in the Results Pane, below the Editor Pane

Page 3 of 9
CCI – Computer Science Dept 655445328.doc

(see Figure 1 below – this shows the Query Analyzer – the query is typed into the Editor
Pane, the resulting data appears in the Results Pane).

The Results Pane has two tabs – Grids and Messages.


- The data is displayed on the Grids tab.
- If the query was successful, the Messages tab indicates how many rows were returned.
- If the query was not successfully executed, the Messages tab contains any error messages
that were returned.

Figure 1 – the SQL Server Query Analyzer

5 The basics of SQL Queries


The most important SQL command is the SELECT statement. With this statement, sets of
data can be retrieved from the relational database.
Recall that SQL is a set processing language. The SELECT statement deals with operations
on sets; the operations are:
- Projections – retrieving specific columns of data
- Selections – retrieving specific rows of data
- Joins – bringing data together from two or more tables

Note: In these handouts, we will use the same syntax conventions as in the SQL Server
Books Online. See Appendix A – Syntax Conventions for T-SQL' at the end of this handout
for a description of the syntax conventions (taken from Books Online).

Page 4 of 9
CCI – Computer Science Dept 655445328.doc

5.1 Basic SELECT – projection and selection


The basic syntax of a SELECT statement is as follows:

SELECT select_list
FROM table_source
[ WHERE search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]

select_list is a list of columns – the projection


table_source is the table to get the columns from
search_condition is the criteria to apply if you want to narrow the selected rows down to a
subset of all the rows in the table – the selection (the WHERE clause can be omitted if it is
required to select all the records in a table)
order_expression is a list of one or more of the columns in the table_source, by which to
order the results – they can be ordered in ASCending or DESCending order; ASC is the
default.

[Note: SQL is not case-sensitive; however, it is good practice to use upper-case or proper
case – where first letters are capitalised – for key words such as SELECT, as it makes your
SQL easier to read.]

Example – this query selects Title_ID, Title and Type from the Title table (the projection)
where the Type is “Business” (the selection) and it orders the results by Title:

SELECT title_id, title, type


FROM titles
WHERE type = 'business'
ORDER BY title ASC

Some things to note about this query:


- Character strings are delimited by single or double quotes – but it must be consistent i.e.
if a single quote is used to begin, a single quote should be used to end the string.
- The default ORDER BY order is ASC – so if ASC was omitted from the above query, it
would still order the results by Title in ascending order.

Example – to select ALL the columns from one table:

SELECT * FROM titles


WHERE type = 'business'
ORDER BY title

- the asterisk (*) can be used to select all the columns from a table

5.2 Introducing Joins


Joins between tables can also be performed in the SELECT statement.
The main types of join are INNER, LEFT OUTER and RIGHT OUTER joins.
When performing a join between tables, the values in one or more columns in each table are
compared. The columns being compared are usually a primary key in one table and the
corresponding foreign key in another table.
Join syntax is used in a select query. It consists of keywords to specify the type of join and to
indicate what fields the join is being made on.

Page 5 of 9
CCI – Computer Science Dept 655445328.doc

5.2.1 Cross Join (Cartesian)

The most basic type of join retrieves the cross product (or Cartesian product) of all the data in
two tables. For each record in the first table, all the records in the second table are joined.
This creates a very big record set (the number of rows = number of rows in table A x number
of rows in table B).
This is not a particularly useful join, so it is rarely used.

Example:
This cross join would result in a row for every Title-Publisher combination (regardless of
matching columns or keys):

SELECT t.title_id, t.title, p.pub_id, p.pub_name


FROM titles t CROSS JOIN publishers p

This query is the same (the CROSS JOIN keyword does not have to be specified):

SELECT t.title_id, t.title, p.pub_id, p.pub_name


FROM titles t, publishers p

5.2.2 Inner join

An inner join is used to retrieve rows from the tables where there are corresponding rows,
based on matching values in specified columns in each of the tables.
This is equivalent to choosing to discard unmatched rows from a cross-product – by adding
join criteria to the query.
Suppose we want to find the names of the publishers for the titles we selected above
('business' titles). This is an inner join between titles and pubs, based on the values in the key
field pub_id being equal.

Example:
SELECT title_id, title, type , p.pub_name
FROM titles AS t INNER JOIN publishers AS p ON t.pub_id = p.pub_id

We can also add the search criteria and the order by clause onto this query, if desired:
SELECT title_id, title, type , p.pub_name
FROM titles AS t INNER JOIN publishers AS p ON t.pub_id = p.pub_id
WHERE t.type = 'business'
ORDER BY t.title

Things to note about this query:


- The 'AS' keyword in the FROM clause is used to specify an alias for each table. The alias
can be used as short-hand to refer to fields in the table in the WHERE, ORDER BY and
SELECT clauses. If a field name is unique across the two tables, then it is not necessary
to specify the alias e.g. as pub_name only exists in the Publishers table, it could be stated
just as 'pub_name' and not 'p.pub_name'. However, it is useful to show what table each
field has come from.

5.2.3 Left Outer Join

Page 6 of 9
CCI – Computer Science Dept 655445328.doc

An outer join retrieves data from the tables where there are corresponding rows, but also
includes rows from one side of the join that have no matching records in the other table in the
join.
A left outer join includes all rows from the table on the left side of the join, regardless of
whether there are matching records in the other table. Columns from the right table where
there is no matching record return NULL values.

Suppose we want to find the Sales for all Titles, including those that do not have any Sales.
As it is possible that there are no Sales for a Title, this is a left outer join with Titles being on
the left side of the join.

Example:
SELECT t.title_id, t.title, s.ord_num, qty
FROM titles t LEFT OUTER JOIN sales s ON t.title_id = s.title_id

Things to note about this query:


- The AS can be omitted when specifying the alias names for the tables in the FROM
clause.

5.2.4 Right Outer Join

A right outer join includes all rows from the table on the right side of the join, regardless of
whether there are matching records in the other table. Columns from the left table where there
is no matching record return NULL values.

If we take the same query as above i.e. to find the Sales for all Titles, including those that do
not have any Sales, but place the Titles table on the right hand side of the join, then it is a
right outer join.
Example:
SELECT t.title_id, t.title, s.ord_num, qty
FROM sales s RIGHT OUTER JOIN titles t ON t.title_id = s.title_id

5.2.5 Full Outer Join

A full outer join includes all rows from both tables in the join, regardless of matching records
in the other table. The result set shows NULL values where there are no matching records.

Consider Authors and Publishers – both have a City attribute. A LEFT OUTER JOIN on City
would produce all Authors who are in the same City as a Publisher, and Authors who do not
live in the same City as a Publisher.
A RIGHT OUTER JOIN would produce all Publishers who are in the same City as an
Author, and Publishers who do not live in the same City as an Author.

SELECT a.au_fname, a.au_lname, p.pub_name


FROM authors a LEFT OUTER JOIN publishers p
ON a.city = p.city
ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC

SELECT a.au_fname, a.au_lname, p.pub_name


FROM authors a RIGHT OUTER JOIN publishers p
ON a.city = p.city
ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC

Page 7 of 9
CCI – Computer Science Dept 655445328.doc

Alternatively, an INNER JOIN would produce Authors who live in the same City as a
Publisher. If we wish to see all Authors and Publishers, including those who have a City in
common and those who do not, we can do a FULL OUTER JOIN:

SELECT a.au_fname, a.au_lname, p.pub_name


FROM authors a FULL OUTER JOIN publishers p
ON a.city = p.city
ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC

5.2.6 Non-ANSI Syntax for Joins

There is an alternative syntax for joins, used by non-ANSI standard implementations of SQL
Server. It is also possible to use this syntax in SQL Server. This style of join is called theta
style. In this style, the join is specified in the WHERE clause, using =, *= or =* operators.
The non-ANSI syntax for each join is shown below.

Inner Join
This syntax is often used instead of the ANSI syntax and is still supported by SQL Server.

SELECT title_id, title, type , p.pub_name


FROM titles AS t, publishers AS p
WHERE t.pub_id = p.pub_id

Left outer join


This syntax is harder to read/understand than the ANSI syntax, as the words 'LEFT OUTER
JOIN' make it clear what the type of join is and which table is the left table. This syntax may
not be supported by Microsoft in future versions of SQL Server, so it is advisable not to use
it.
SELECT t.title_id, t.title, s.ord_num, qty
FROM titles t , sales s
WHERE t.title_id *= s.title_id

Right outer join


This syntax is harder to read/understand than the ANSI syntax, as the words 'RIGHT OUTER
JOIN' make it clear what the type of join is and which table is the right table. This syntax
may not be supported by Microsoft in future versions of SQL Server, so it is advisable not to
use it.
SELECT t.title_id, t.title, s.ord_num, qty
FROM sales s , titles t
WHERE t.title_id =* s.title_id

5.2.7 Multiple Tables & Columns in Joins

It is possible to include multiple tables and multiple columns in all of the join types.

All of the above joins are based on matching values in one column. A join can be on more
than one column.
For example, to retrieve all Authors who live in the same City and State as a Publisher:

Page 8 of 9
CCI – Computer Science Dept 655445328.doc

SELECT a.au_fname, a.au_lname, p.pub_name


FROM authors AS a INNER JOIN publishers AS p
ON a.city = p.city
AND a.state = p.state
ORDER BY a.au_lname ASC, a.au_fname ASC

More than two tables can be joined also – because the result set from a join between two
tables is effectively a table itself.
For example, if we want to get a list of Titles and Authors, we have to join the Titles, Authors
and TitleAuthor tables (remember the many-to-many relationship!):

SELECT title, au_fname, au_lname, royaltyper


FROM authors INNER JOIN titleauthor
ON authors.au_id = titleauthor.au_id
INNER JOIN titles ON titleauthor.title_id = titles.title_id

6 Appendix A – Syntax Conventions for T-SQL


(taken from MS SQL Server 2000 Books Online)

Syntax Used for


UPPERCASE Transact-SQL keywords.
italic User-supplied parameters of Transact-SQL syntax.
| (vertical bar) Separating syntax items within brackets or braces. You can choose
only one of the items.
[ ] (brackets) Optional syntax items. Do not type the brackets.
{} (braces) Required syntax items. Do not type the braces.
[,...n] Indicating that the preceding item can be repeated n number of times.
The occurrences are separated by commas.
[ ...n] Indicating that the preceding item can be repeated n number of times.
The occurrences are separated by blanks.
bold Database names, table names, column names, index names, stored
procedures, utilities, data type names, and text that must be typed
exactly as shown.
<label> ::= The name for a block of syntax. This convention is used to group and
label portions of lengthy syntax or a unit of syntax that can be used in
more than one place within a statement. Each location in which the
block of syntax can be used is indicated with the label enclosed in
chevrons: <label>.

Notes prepared by: Terri O'Sullivan, FBE Computer Science Department.

Page 9 of 9

You might also like