0% found this document useful (0 votes)
21 views54 pages

9.1 - Chapter 6 - Simple Queries in SQL

The document discusses SQL queries and operations like selection, projection, joins, and ordering. It covers basic SQL syntax and keywords, and provides examples of different types of queries and clauses like SELECT, FROM, WHERE, and ORDER BY.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views54 pages

9.1 - Chapter 6 - Simple Queries in SQL

The document discusses SQL queries and operations like selection, projection, joins, and ordering. It covers basic SQL syntax and keywords, and provides examples of different types of queries and clauses like SELECT, FROM, WHERE, and ORDER BY.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 54

ĐẠI HỌC FPT CẦN THƠ

Chapter 6
Simple Queries in SQL
Objectives

1 Understand why must use Bags concept

2 Understand how to write simple queries

3 Understand about NULL values

4 Understand about the string data type, date-time data type

5 Know how to order the output


Contents

1 Bag concept

2 Projection in SQL

3 Selection in SQL

4 Comparison of Strings and Pattern matching in SQL

5 Date time data type

6 NULL values

7 Ordering the output


6.1 Relational operations on Bags

A bag or multiset is like a set, but an element may


appear more than once.
Exp: {1,2,1,3} is a bag.
Order in a bag is unimportant.
Some operations, like projection or union, are
much more efficient on bags than sets. Why?
6.1 Relational operations on Bags

Some operations, like projection or union, are


much more efficient on bags than sets because
duplicates are not eliminated.
Selection applies to each tuple, product and join
are done on each pair of tuples, so duplicates in
bags have no effect.
6.1 Relational operations on Bags

Some operations, like projection or union, are


much more efficient on bags than sets because
duplicates are not eliminated.
Selection applies to each tuple, product and join
are done on each pair of tuples, so duplicates in
bags have no effect.
6.1 Relational operations on Bags

Some operations, like projection or union, are


much more efficient on bags than sets because
duplicates are not eliminated.
Selection applies to each tuple, product and join
are done on each pair of tuples, so duplicates in
bags have no effect.

Bag projection yields


always the same
number of tuples as
the original relation
6.1 Relational operations on Bags
6.1 Relational operations on Bags
6.1 Relational operations on Bags
6.1 Relational operations on Bags
6.1 Relational operations on Bags
The Extended Algebra
Outerjoin
6.2 Relational algebra and
Datalog
6.2 Relational algebra and
Datalog
6.2 Relational algebra and
Datalog
6.2 Relational algebra and
Datalog
6.2 Relational algebra and
Datalog
Operations
6.3 SQL Overview

The most commonly used relational DBMS’s query and


modify the database through a language called SQL.

SQL (stands for Structured Query Language) is the set


of statements with which all programs and users access
data in an database.

The language, Structured English Query Language


("SEQUEL") was developed by IBM Corporation. SEQUEL
later became SQL (still pronounced "sequel").

Today, SQL is accepted as the standard RDBMS language.


6.3 SQL Revisions
Year Name Alias Comments

1986 SQL-86 SQL-87 First published by ANSI. Ratified by ISO in 1987.

1989 SQL-89 FIPS 127-1 Minor revision, adopted as FIPS 127-1.

1992 SQL-92 SQL2, FIPS 127-2 Major revision (ISO 9075), Entry Level SQL-92 adopted as FIPS 127-2.

1999 SQL:1999 SQL3 Added regular expression matching, recursive queries, triggers, support for procedural
and control-of-flow statements, non-scalar types, and some object-oriented features.

2003 SQL:2003 Introduced XML-related features, window functions, standardized sequences, and
columns with auto-generated values (including identity-columns).

2006 SQL:2006 ISO/IEC 9075-14:2006 defines ways in which SQL can be used in conjunction with
XML. It defines ways of importing and storing XML data in an SQL database,
manipulating it within the database and publishing both XML and conventional SQL-
data in XML form. In addition, it provides facilities that permit applications to integrate
into their SQL code the use of XQuery, the XML Query Language published by the
World Wide Web Consortium (W3C), to concurrently access ordinary SQL-data and
XML documents.

2008 SQL:2008 Defines more flexible windowing functions, clarifies SQL 2003 items that were still
unclear [1]
6.3 Transact SQL (T-SQL)

Transact-SQL (T-SQL) is Microsoft's and


Sybase's proprietary extension to SQL

T-SQL

SQL
6.3 Sub-languages of T-SQL

T - SQL

DDL
(Data Definition Language)

DML
(Data Manipulation Language)

DCL
(Data Control Language)
6.3 Sub-languages of T-SQL
6.4 SELECT commands
A SELECT statement retrieves information from the database. Using a SELECT
statement, you can do the following:
• Projection: You can use the projection capability in SQL to choose the
columns in a table that you want returned by your query.
• Selection: You can use the selection capability in SQL to choose the
rows in a table that you want returned by a query (with WHERE clause)
• Joining: You can use the join capability in SQL to bring together data that
is stored in different tables by creating a link between them.
6.4 SELECT commands

A keyword refers to an individual SQL element.


For example, SELECT and FROM are keywords.
A clause is a part of a SQL statement.
For example, SELECT employee_id, last_name, ... is
a clause.
A statement is a combination of two or more
clauses.
For example, SELECT * FROM employees is a SQL
statement.
6.4 Basic Syntax
for a simple SELECT queries
SELECT [ ALL | DISTINCT ]
[ TOP n [ PERCENT ] ]
* | {column_name | expression [alias],…}
[FROM table]

 SELECT identifies what columns


 ALL: Specifies that duplicate rows can appear in the result set. ALL is
the default
 DISTINCT: Specifies that only unique rows can appear in the result
set. Null values are considered equal for the purposes of the
DISTINCT keyword
 TOP n [ PERCENT ]:Specifies that only the first n rows are to be output
from the query result set. n is an integer between 0 and 4294967295. If
PERCENT is also specified, only the first n percent of the rows are
output from the result set. When specified with PERCENT, n must be
an integer between 0 and 100
 FROM identifies which table
6.4 A trick for
reading & writing queries

It’s generally easiest to examine a SELECT-FROM-


WHERE query by:
First looking at the FROM clause to learn which relations are
involved in the query
Then, move to the WHERE clause to learn what it is about
tuples that is important to the query
Finally, look at the SELECT clause to see what the output
format is
The same order: FROM, then WHERE, then SELECT is
often useful when writing queries of your own as well
6.4 Projection in SQL

We can, if we wish, eliminate some of the components


of the chosen tuples; that is, we can project the
relation produced by a SQL query onto some of its
attributes
In place of the * of the SELECT clause, we may list
some of the attributes of the relation mentioned in the
FROM clause. The result will be projected onto the
attributes listed
Example: SELECT all columns
Example: Projection in SQL
Example: Extended projection using
Arithmetic Operators

 Note that the resultant calculated column SALARY+300 is not


a new column in the EMPLOYEES table; it is for display only.
 By default, the name of a new column comes from the
calculation that generated it— in this case, salary+300.
6.4 Renaming or Defining a
Column Alias
A column alias:
Renames a column heading
Is useful with calculations
Immediately follows the column name - there can also be
the optional AS keyword between the column name and
alias
Example: ALIAS
SELECT last_name AS ‘Name’,

salary*12 AS ‘Annual Salary’

FROM employees

The example displays the last names and annual salaries of


all the employees.
Because Annual Salary contain a space, it has been enclosed
in double quotation marks.
Notice that the column heading in the output is exactly the
same as the column alias.
6.4 Duplication Eliminating
with SELECT distinct
6.5 Selection in SQL or Restricting data

While retrieving data from the database, you may


need to restrict the rows of data that are displayed
In that case, the solution is to use the WHERE clause
The WHERE clause is equal to the selection operator
of relational algebra
The expression that may follow WHERE include
conditional expressions like those found in C or Java
6.5 Selection in SQL or Restricting data

SELECT [ ALL | DISTINCT ]


[ TOP n [ PERCENT ] ]
* | {column_name | expression [alias],…}
[FROM table]
[WHERE conditions]

WHERE: restricts the query to rows that meet a


condition
The WHERE clause follows the FROM clause.
Condition: is composed of column names,
expressions, constants, and a comparison operator
Example: Restricting data
Example: Restricting data
6.5 Comparison of Strings

Two strings are equal if they are the same sequence


of characters. Recall from the section 2.3.2 that
strings can be stored as fixed-length strings (using
CHAR) or variable-length strings (using VCHAR)
When comparing strings with different declarations,
only the actual strings are compared (SQL ignores any
“pad” characters that must be presenet in the
database in order to give a string its required length)
We can use “<“, “>”, “=“ and “<>” operators to
compare two strings
6.5 Pattern matching in SQL

SQL also provides the capability to compare strings on


the basis of a simple pattern match. An alternative
form of comparision expression is:
s LIKE p
where:
S: is a string
P: is a pattern (with the optional use of some special
characters: “%”, “_” ..)
Similarly, “s NOT LIKE p” is true if and only if string s
does not match pattern p
6.5 Dates and Times

SQL generally support dates and times as special data


types. These values are often representable in a
variety of formats such as:
‘05/14/1948’ or
’14 May 1948’
We can compare dates or times using the same
comparison operators we use for numbers or strings
6.5 NULL values

Null means 'nothing' or without value or consequence


Null is a special marker used in SQL to indicate that a data
value does not exist in the database. Introduced by the creator
of the relational database model
Since Null is not a member of any data domain, it is not
considered a "value", but rather a marker (or placeholder)
indicating the absence of value. Because of this, comparisons
with Null can never result in either True or False, but always in
a third logical result, Unknown
However, certain operations on Null can return values if the
value of Null is not relevant to the outcome of the operation
6.5 The Truth-value ‘Unknown’

Null is untyped in SQL, meaning that it is not


designated as an integer, character, or any other
specific data type
6.5 Ordering the Output

While retrieving data from the database, you may


need to specify the order in which the rows are
displayed.
In that case, the solution is to use the ORDER BY
clause
6.5 Ordering the Output

SELECT [ ALL | DISTINCT ]


[ TOP n [ PERCENT ] ]
* | {column_name | expression [alias],…}
FROM table
[WHERE conditions]
[ORDER BY {expression [ASC | DESC] ,…} ]

If you use the ORDER BY clause, it must be the last clause of the SQL
statement.
Expression: Specifies a column on which to sort.
A sort column can be specified as a name or column alias (which can be
qualified by the table or view name), an expression, or a nonnegative
integer representing the position of the name, alias, or expression in
select list.
Multiple sort columns can be specified. The sequence of the sort
columns in the ORDER BY clause defines the organization of the sorted
result set.
Example: Ordering output
Exercise 1

Write SQL queries to create the following tables:


• STUDIOS (name, address)
• STARS (name, address, phone)
• MOVIES (title, year, length, genre)

After creating, write SQL queries to drop them


Exercise 2

Write SQL queries to do following tasks:


• Add a column named DESCRIPTION into MOVIES
table (you must determine the data type for it)

• Add a column named HOBBIES into STARS table


(you must determine the data type for it)

• Add a column named BIRTHDAY into STARS table


(you must determine the data type for it)
Exercise 3

Write SQL queries to do following tasks:


• Remove the column named DESCRIPTION from
MOVIES table

• Remove the column named HOBBIES from STARS


table

• Remove the column named BIRTHDAY from


STARS table
Exercise 4

Create relation EMPLOYEES with the columns


LAST_NAME, DEPARTMENT_ID, SALARY
Insert the tuples (see figure above) into the
relation EMPLOYEES
Write a SQL query to show all tuples in table
EMPLYEES
Exercise 5

Write a SQL query to show all SALARY (but


eliminating duplications) in table EMPLYEES

Write a SQL query to show all DEPARTMENT_ID


(but eliminating duplications) in table EMPLYEES
Exercise 6

Write a SQL query to delete all tuples in


EMPLOYEES table

Write a SQL query to delete all tuples with NULL


value in DEPARTMENT_ID
Exercise 7

Write a SQL query to set DEPARTMENT_ID to the


value 10

Write a SQL query to set DEPARTMENT_ID to the


value 10 if DEPARTMENT_ID is NULL
Exercise 8

Write a SQL query to insert some new tuples into


EMPLOYEES
ĐẠI HỌC FPT CẦN THƠ

You might also like