Imgt Midterm Rev 2
Imgt Midterm Rev 2
3. Log files
● used to store changes to the
database before these changes
are recorded in the data files
Database Layout themselves
● It enables SQL Server to use these
files as an important part of its
recovery process
● The recommended file name
extension for log files is .ldf.
Creating a Database
Query Editor (T-SQL)
database_name
Specifies that associated file list defines
the primary file.
PRIMARY
name of the new database.
NAME
Specifies the logical name for the file
logical_file_name
Viewing Information of DB
Is the name used to reference the file any
T-SQL executed after the DB is created
max_size
Initial maximum size of the file. If not
specified, the file grows until the disk is full
FILEGROWTH
Specifies the growth increment of the file
growth_increment
The amount of space added to the file
each time new space is needed. Minimum
value is 64 KB. Default is 10% of the file
Renaming Database Creating Database
Query Editor (T-SQL) Using Object Explorer
sp_renamedb 1. Right-click on the Databases in the
change the name of the database Object Explorer, then select New
Databases…from the Context Menu that
pops up, as
you can see at the following figure:
2. Type Database1 at the Database Name
box. Lastly, click the OK button3
Change the name of the accounting
database to financial.
Deleting a Database
Using Object Explorer
1.Right-click on databases to be deleted
2.Select Delete
Creating Table
Using Object Explorer
1. Select and expand the Database where
you want to create the table
2. Right-click Tables
3. Select New Table
Deleting a Database
Query Editor (T-SQL)
4. In the Table Designer, supply the Using Object Explorer
Column Name, Data Type and Allow Nulls ● Enter name of the table
5. Below the column grid, you can modify
the other properties of the column
Creating Table
Query Editor (T-SQL)
owner
Optional. Owner of the table. Default is
dbo
table_name
Required. Name of the new table
column_name
Required. Name of the column
data_type
Required. Data type of the column
including the argument (length, precision,
scale) if applicable
nullability
Optional. Indicates whether null values
are allowed in the column. Default is
NULL
Creating Table DEFAULT
Optional. The value you want to be used
for the column for any row that is inserted
without explicitly supplying a value for that
particular column
IDENTITY
Optional. Indicates that the column is an
identity column. The (seed, increment)
values will default to (1,1) if not specified
Creating Table
Modifying Table
Query Editor (T-SQL)
Modifying Table
Using Object Explorer
1. Select and expand the Database
where table exists
2. Expand Tables
3. Right click the table you want to edit
4. Select Modify
C. Alter a table to change the data type Dropping Table
of a column Query Editor (T-SQL)
RELATIONSHIP
►is a way of relating one entity to another.
Entities can therefore participate in a
relationship.
► It is commonly thought as a verb
connecting the entities or nouns.
►It is normally represented by a diamond TYPES OF RELATIONSHIP (CROW
shape. NOTATION)
ATTRIBUTE
EXAMPLES OF ENTITIES WITH ►Refers to the characteristic or basic fact
RELATIONSHIP or field of an Entity or Relationship.
►For example a Student entity could have
the following attributes ID Number, Last
Name, First Name, Address, Birth Date
etc.
►A relationship could also have an
attribute for example an Entity name
Student enrolls (relationship) to a
Course/Program. Now, when you enroll
you enroll on a certain date so you will
have an attribute of Enrollment Date under
Enroll relationship.
TYPES OF RELATIONSHIP ►It is normally represented by a circle.
►One-to-One
►One-to-Many
►Many-to-Many
EXAMPLES OF ATTRIBUTES
ERD (MORE EXAMPLES)
LOGICAL OPERATORS
● The Logical operators are those
that are true or false. They return a
true or false values to combine one
or more true or false values.
RECURSIVE RED
LIKE OPERATOR
● LIKE is the ANSI/ISO standard
operator for comparing a column
RELATIONAL OPERATORS value to another column value, or
● A comparison (or relational) to a quoted string. Returns either 1
operator is a mathematical symbol (TRUE) or 0 (FALSE)
which is used to compare two ● The SQL LIKE operator is only
values. applied on a field of types CHAR or
● Relational operators are used in VARCHAR to match a pattern.
conditions that compares one ● To match a pattern from a word,
expression with another. The result special characters, and wildcards
of a comparison can be TRUE, characters may have used with
FALSE, or UNKNOWN (an LIKE operator.
operator that has one or two NULL ● The LIKE operator can be used
expressions returns UNKNOWN). within any valid SQL statement,
such as SELECT,INSERT
INTO,UPDATE or DELETE.
1
LEARNING OBJECTIVES
2
Select Clause
3
Select Clause
Syntax
Select <List of Columns and expressions (usually involving
columns)>
From <List of Tables & Join Operators>
Where <List of Row conditions joined together by And, Or,
Not>
Group By <list of grouping columns>
Having <list of group conditions connected by And, Or, Not
>
Order By <list of sorting specifications>
4
Select Clause
Conceptual Evaluation
From Tables: Cross
product and join 1
operations
Restriction on
where conditions 2
Compute
Sort on aggregates Restriction
Group
Group BY and reduce on HAVING
By? Yes columns each group conditions
to 1 row
No
3
5
4
Order By?
Sort
Yes
No columns in 6
ORDER BY
Project columns in
7
SELECT
finish
5
Select Clause
Example
Query: Output:
Select movie_title, studio_id Movie_Title Studio_ID
From Movies ----------------------------------------
Where movie_type = ‘Comedy’ Vegetable house 1
Broccoli Wars 2
Carrot Affairs 4
Chocolat 1
Cranberry House 2
Notes:
Database looks in the movie_type column until it locates a
comedy. When it finds comedy it retrieves the value of
movie_title & studio_id
The where clause is optional. When not specified the columns
from all the records are extracted.
Changing the order in the select_list changes the order in
which the columns are displayed
Using a * for the select_list selects all the columns from the
table. They are listed in the same order as in the original
table.
6
Select Clause
Expressions in Select List
Expressions can be used to change the values prior to
printing
Example:
Select ‘Random Text’ movie_title, studio_id, 2 + 2
From Movies
Where movie_type = ‘Comedy’
Output:
RandomText Movie_Title Studio_ID 2+2
-----------------------------------------------------------------------------
‘Random Text’ Vegetable house 1 4
‘Random Text’ Broccoli Wars 2 4
‘Random Text’ Carrot Affairs 4 4
‘Random Text’ Chocolat 1 4
‘Random Text’ Cranberry House 2 4
7
Select Clause
Expressions in Select List
Example:
Select movie_title, gross, gross*1.5
From Movies
Output:
Movie_Title gross gross*1.5
----------------------------------------
Vegetable house 30 45
Broccoli Wars 20 30
Carrot Affairs 11 16.5
Chocolat 10 15
Cranberry House 50 75
8
Select Clause
Operators
Arithmetic operators supported by SQL
() Parentheses
/ Division
* Multiplication
- Subtraction
+ Addition
Associativity and Precedence:
Precedence is the order in which operators are evaluated
Associativity is the order in which operators of same
precedence are evaluated
Multiplication and Division have the same precedence
and Subtraction and Division have the same precedence.
Equal precedence operators are evaluated from right to
left
Parentheses can be used to control the sequence of
evaluation of various operators
9
Select Clause
Alias (as)
Used to assign names to the columns when they are
retrieved from the database table.
Syntax:
Select expr1 [as alias1], expr2 [as alias2] [, … ]
From table1 [, table2, …]
[Where condition]
Example:
Select city, ((1.8 + avg_temp) + 32) AS temperature
From Temperature
Output
City Temperature
----------------------------------------
London 61.7
Albany 78.4
Paris 66.2
10
Select Clause
Alias (as)
A multiword heading needs to be enclosed
in double quotes
Example:
Select city, ((1.8 + avg_temp) + 32) AS “Average
Temperature”
From Temperature
Output:
City Average Temperature
-----------------------------------------------------
London 61.7
Albany 78.4
Paris 66.2
11
Where Clause
Basics
Conditional statements in the select clause restrict
the selection of rows in the database.
It can be used in a variety of SQL Statements
Syntax:
Update table Set (column = value, column = …) [Where
condition]
Delete From table [Where condition]
Select list from table [Where condition]
Condition is a Boolean expression which evaluates
to true or false
Complex expressions can be generated by using
logical operators
12
Where Clause
Operators
Arithmetic Operators used in the where clause
= equal
<>, != not equal
> Greater Than
< Less Than
>= Greater than or equal to
<= Less than or equal to
Logical operators
AND
OR
NOT
For numeric operator comparison you should not
use quotes around the number
You should put single quotes around characters and
strings
13
Where Clause
Null Values
Null values are unknown so the regular operators
can not be used for comparison
IS NULL is used to check if the field contains a null value
or not.
IS NOT NULL is used to see if a field is not null
Example
Select movie_title
From movies
Where gross is null
Select movie_title
From movies
Where gross is not null
14
Where Clause
Examples
Example:
Select movie_title, studio_id , gross
From Movies
Where studio_id = 3 and gross Is Null
Output:
Movie_Title Studio_ID GROSS
----------------------------------------------------------------
Bill Durham 3
Example:
Select movie_title, studio_id , gross
From Movies
Where studio_id = 3 OR gross Is Null
Output
Movie_Title Studio_ID GROSS
----------------------------------------------------------------
Bill Durham 3
Prince Kong 2
SQL Strikes Back 3 10
The Programmer 25.5
15
Where Clause
Examples
Example:
Select movie_title, studio_id , gross
From Movies
Where studio_id = 3 and NOT gross Is Null
Output
Movie_Title Studio_ID GROSS
----------------------------------------------------------------
SQL Strikes Back 3 10
The Programmer 3 25.5
Example:
Select movie_title, studio_id, gross
From Movies
Where studio_id = 3
or studio_id = 2
or studio_id = 1
Output
Movie_Title Studio_ID GROSS
----------------------------------------------------------------
SQL Strikes Back 3 10
The Programmer 3 25.5
16
Where Clause
IN condition
IN condition checks if the values in a column are present in
list list when selecting
Syntax:
Select select_list
From table
Where column [not] in (value_list)
Example (Using IN):
Select movie_title, studio_id
From Movies
Where studio_id in(2, 3)
20
Where Clause
String Comparison
Example
Select movie_title, studio_id
From Movies
Where movie_title = ‘Independence Day’
Output
Movie_title Stuodio_ID
-----------------------------------------
Independence Day 1
22
Select Clause
Distinct
Eliminates all the duplicate entries in the table
resulting from the query.
Syntax:
Select [DISTINCT] select_list
From table[, table, …]
[Where expression]
[Order By expression]
Example:
Select DISTINCT studio_id, director_id
From Movies
studio_id director_id
1 1
2 2
2 10
3 1
3 9
23
Select Clause
Distinct
Eliminates all the duplicate entries in the table
resulting from the query.
Syntax:
Select [DISTINCT] select_list
From table[, table, …]
[Where expression]
[Order By expression]
Example:
Select DISTINCT studio_id, director_id
From Movies
studio_id director_id
1 1
2 2
2 10
3 1
3 9
24
Select Clause
Order By - Syntax
Used to sort the results based on contents of a
column
Multiple levels of sort can be done by specifying
multiple columns
An expression can be used in Order By clause
Syntax:
Select function (column)
From table1 [, table2 …]
[Where condition]
[Order By {Column | alias | position} [ASC | DESC]]
25
Select Clause
Order By - Example
Query: Sort Movies by profits in Ascending order
Select MovieTitle, Gross, Budget, (Gross – Budget) as
profits
From movies
Order BY profits
Movie_title Gross Budget Profit
Great Escape 67.5 70 -2.5
Upside Down 54 50 4
Green Warrior 96 80 16
Blue Oranges 28 7 21
26
Select
Aggregate Queries
Aggregate queries provides a more holistic view of
the data by further processing the retrieved data.
Categorizes the query results according to the
contents of a column in the database
Multiple levels of subgroups can be created by
specifying multiple columns
They can work on
On all the rows in a table
A subset of rows in a table selected using a where clause
Groups of selected data organized using Group By clause.
27
Select - Aggregate Queries
Group By (Syntax)
Syntax:
Select function(column)
From <list of tables>
Where <condition>
Group By <list of columns>
Having <condition>
28
Aggregate Queries
Functions
Functions:
Sum() Returns a sum of the column
Count() Returns a total number of rows returned by a query
Avg() Returns the average of a column
Min() Returns minimum value of the column returned by
query
Max() Returns maximum value of the column returned by
query
Count function
does not include columns containing null values in total
can be used with distinct to count the number of distinct rows
Example:
Query: Select sum(budget) Output: Sum(budget)
From movies ---------------
Where studio_id = 3 65.1
29
Select - Aggregate Queries
Group By (Examples)
Problem 1:
Get # of movies by each director for each studio
Select studio_id, director_id, count(*)
From Movies
Group By director_id, studio_id
Problem 2:
Get # of movies by each studio ordered by
studio_id
Select studio_id, count(*)
From Movies
Group By studio_id
Order By studio_id
30
Select - Aggregate Queries
Group By (Examples)
Problem 3: (Summation)
31
Join Queries
Definition
A Join Query uses data from multiple tables
Multiple tables are specified in the From Clause
A join query without any restrictions will join every row in
one table with each row in the other table.
For two tables to be joined in a sensible manner, they need
to have data in common
The join condition should usually specify the foreign key
equivalence condition
Problem: Get names of the directors for movies listed
in the movie table
Schema: Movies (movie_title, director_id, release_date)
People(person_fname, person_lname, person_id)
Query: Select movie_title, person_fname, person_lname
From Movies, People
Where director_id = person_id
32
Join Queries
Joining Condition
For a useful Join query a joining condition is
required
Defined in where clause as relationships between
columns
Multiple conditions may be defined if multiple
columns shared
More than two tables can be joined in a query
Problem: Find people who live in same state as studio
Schema:
Studios(studio_id, studio_state, studio_name, studio_city)
People(person_fname, person_lname, person_id, person_state,
person_city)
Query:
Select person_fname, person_lname, studio_name
From Movies, People
Where studio_city = person_city
AND studio_state = person_state
33
Join Queries
More than two tables
Separate condition is required to join each
table
Problem: Get title, director, studio, city for all movies
in the database
Schema:
Studios(studio_id, studio_state, studio_name, studio_city)
People(person_fname, person_lname, person_id, person_state,
person_city)
Movies(movie_title, director_id, studio_id)
Query:
Select M.movie_title, M.studio_id, P.person_fname, P.person_lname,
S.studio_city
From Movies M, People P, Studio S
Where M.director_id = P.person_id
AND M.studio_id = P.person_id
34
Join Queries
Self Join
Required to compare values within a single
column
Need to define aliases for the table names
Problem: Find actors living in the same state
Schema:
People(person_fname, person_lname, person_id, person_state,
person_city)
Query:
Select p1.person_id, p1.person_fname, p1.person_lname,
p1.person_state
From People p1, People p2
Where p1.person_state = p2.person_state
AND p1.person_id != p2.person_id
36
Join Queries
Union
Union Joins allow multiple query results to be combined
into a single result set
Syntax Example
Select select_list
Select person_id, person_city, person_state
From table [,table, ….]
[Where condition] From People
Union [All] Union
Select select_list Select studio_id, studio_city, studio_state
From table [,table, ….] From Studios
[Where condition]
Notes:
The number of columns selected for both the queries should
be the same
The columns are merged in order in which they are selected
The duplicates are eliminated from the combined table
More than two tables can be joined together
37
Join Queries
Union (All & Order By)
Union query eliminates all duplicates in the resultant
table
All option is used when we do not want to eliminate the
duplicates
Union and Order By can be used together to order
the results of the combined table
This clause is not allowed when a single column result is
obtained and the all keyword is used since the duplicates
are eliminated and there is nothing to order by
Example
Select studio_id, studio_state
From Studios
Union
Select Person_id, person_state
From People
Order By studio_state
38
Join Queries
Intersect
In the Intersect Query results of two separate
queries are concatenated, however, only common
elements of the two queries are included in the
resultset
Example
Select person_state
From People
Intersect
Select studio_state
From Studios
39
Join Queries
Minus
Minus Query lists all the records which are
present in the first but not in the second.
Example
Select person_state
From People
Minus
Select studio_state
From Studios
40
Join Queries
SQL 92 Syntax
More verbose than pervious versions of SQL
Need to define aliases for the table names
Separates the condition for joining from condition for
filtering
Example: Find actors living in the same state
Schema:
People(person_fname, person_lname, person_id, person_state, person_city)
Movies(movie_title, director_id, studio_id)
Query:
Select movie_title, person_fname, person_lname
From Movies INNER JOIN People
ON director_id = person_id
Query:
Select Movies.movie_title, Movies.studio_id, Person.person_fname,
Person.person_lname, Studio.studio_city
From (People Inner Join
(Movies Inner Join Studio
On Studio.studio_id = Movie.studio_id)
On Movie.director_id = Person.person_id
42
Join Queries
SQL 92 Syntax (Left/Right/Full Join)
Schema:
People(person_fname, person_lname, person_id, person_state,
person_city)
Movies(movie_id, movie_title, director_id, studio_id)
Location(movie_id, city, state)
Query: Includes all
Select movie_title, city, state non-matched
From Movies Left Join Locations movie titles
On Movies.movie_id = Locations.movie_id
Includes
Select movie_title, person_fname, person_lname all people
From Movies Right Join People not-matching
On Movies.director_id = Person.person_id to directors
Includes
Select movie_title, person_fname, person_lname non-matched
From Movies Full Join People People and
On Movies.director_id = Person.person_id directors
43
Nested Queries
Definitions
A nested query is a query inside another query
The enclosing query also called outer query
Nested query is called inner query
It usually appears as a condition in where or having
clauses.
There can be multiple levels of nesting
There are two kinds of nested queries
Correlated
Non-Correlated
Example:
Select movie_title
From movies
Where director_id IN (
Select person_id
From People
Where person_state = ‘TX’)
44
Nested Queries
Non-Correlated
Generates data required by outer query before it can be executed
Inner query does not contain any reference to outer query
Behaves like a procedure
The result should not contain any column from the nested query
Example
Schema: People(person_fname, person_lname, person_id, person_state,
person_city)
Movies(movie_id, movie_title, director_id, studio_id)
Query: Select movie_title, studio_id
From Movies
Where director_id IN (Select person_id
From People
Where person_state = ‘TX’)
Steps:
1. Subquery is executed
2. Subquery results are plugged into the outer query
3. The outer query is processed
45
Nested Queries
Correlated
Contains reference to the outer query
Behaves like a loop
Example:
Schema: People(person_fname, person_lname, person_id,
person_state, person_city)
Cast_Movies(cast_member_id, role, movie_id)
Query: Select person_fname, person_lname
From People p1
Where ‘Pam Green’ in ( Select role
From Cast_Movies
Where p1.person_id =
cast_member_id)
Steps:
1. Contents of the table row in outer query are read
2. Sub-query is executed using data in the row being processed.
3. Results of the inner query are passed to the where in the outer
query
4. The Outer query is Processed
5. Loop continues till all rows are exhausted
46
Nested Queries
Equivalent Join Query
Example:
People(person_fname, person_lname, person_id, person_state,
person_city)
Cast_Movies(cast_member_id, role, movie_id)
Select person_fname, person_lname
From People, Cast_Movies
Where Cast_member_id = person_id
And role = ‘Pam Green’
47
Nested Queries
Equivalent Join Query
Example:
People(person_fname, person_lname, person_id, person_state,
person_city)
Cast_Movies(cast_member_id, role, movie_id)
Select person_fname, person_lname
From People, Cast_Movies
Where Cast_member_id = person_id
And role = ‘Pam Green’
48
Crosstab Queries
Definition
Crosstab queries analyze one field in a table and view
by two or more other fields in a table.
i.e. standard aggregate functions, such as sum, count and
average can be computed
Scenarios
Crosstab queries can be used to keep track of product sales
in certain areas of a country, and you can narrow that search
into cities of each of those countries.
Outstanding receivables that are 30, 60, or 90 days or more in
arrears can be tracked in the same table
49
Crosstab Queries
Examples
Book Database
TRANSFORM COUNT(Title) Value
SELECT Price Row
FROM Publishers, Books
WHERE Publishers.pubID=Books.PubId
GROUP BY Price Row
PIVOT PubName; Column
Sales Database
Transform Count(*)
Select SalesPersonName
From Orders
Group By SalesPersonName
Pivot CustName
51
Parameter Queries
Definitions
A parameter query is a query in which the criteria for selection
records are determined when the query is executed rather than
when the query is designed.
When access encounters a variable during execution it
attempts to bin the variable to some value. To do this it
performs the following.
First it checks whether the variable is the name of a field or a
calculated field in the query.
1. It attempts to resolve the parameter as a reference to something
from the current environment e.g. a value in an open form
2. If both of the above do not succeed access asks the user for the
value using a parameter value dialog box
By default access expects the value that you put in the box to
the literal strings of text and puts double quotes around them.
To get around this you need to put square brackets around your
parameters.
52