Download The SELECT Command

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Business intelligence wikipedia , lookup

Data vault modeling wikipedia , lookup

Microsoft Access wikipedia , lookup

Operational transformation wikipedia , lookup

Tandem Computers wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

SAP IQ wikipedia , lookup

Relational algebra wikipedia , lookup

Versant Object Database wikipedia , lookup

Database wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
Introduction to Databases
Chapter 6:
Understanding the SQL
Language
Introducing the SQL Language
• Two primary aspects:
– Data definition:
• Requires data definition language (DDL)
that defines tables, attributes, and indexes
in DBMS
– Data manipulation:
• Requires data manipulation language
(DML) for issuing data manipulation
commands to DBMS
Introducing the SQL Language
• Data retrieval statements:
– Sometimes placed in different category,
(separate from DML), as data query language
(DQL) statements
• SQL:
– Standard current relational DBMS language
– Incorporates DDL and DML features
SQL Features
• ANSI SQL standard
• Basic features of standard SQL:
– Data definition language (DDL): Used to create and
maintain database objects
– Data manipulation language (DML): Used to retrieve and
manipulate data
– Command operators: Symbols and keywords used to
run arithmetic, comparison, and logical operations
– Functions: Special executables that return values
– Transaction control: Statements to initiate and complete
or abort transaction processing
Using SQL
• Two basic options for executing SQL
commands:
– Interactive SQL:
• SQL statements that you run directly,
interacting with database server
– Embedded SQL:
• SQL functionality embedded in procedure or
part of application written in different
programming language
Interactive SQL
• All DBMS provide command interface or
command prompt for running interactive
SQL commands
• Microsoft SQL Server - Two options:
– Command prompt: Issuing statements one at a time or
several in set or batch
– Loading and running scripts, groups of SQL Server
commands stored as file
• Text-based interfaces: Complex, but allow
execution of SQL language commands
through batch files
• Some DBMS also have graphic user
interface (GUI)
Sqlcmd Command Interface
SQL Server Management Studio
Embedded SQL
• Uses same SQL language commands as
interactive SQL statements
• Are included as part of executable
program
– For example: SQL Server’s stored procedures
and user-defined functions, which provide
embedded SQL support
• Also used in application programs:
– Programming environment provides
connectivity tools to communicate with
database server and execute SQL commands
Command Basics
• Command syntax:
– Includes command name and any command
keywords and parameters
• Command keywords:
– Describe specific actions that command will
take
• Command parameters:
– Values supplied so command can run
• Example:
SELECT select_list FROM table [WHERE
qualifying_conditions]
Command Basics
• Commands typically run in context of
default database
– Each connection will have associated user
• Query results vary according to command:
– SELECT command returns result set (relational
result) of columns and rows
– DML statements usually return count of rows
affected
The SELECT Command
• SELECT commands: Declarative
statements (not procedural)
• Relational DBMS:
– Analyzes SQL SELECT statement
– Creates access path—plan for steps to take in
responding to query
• SQL SELECT commands can be run in
interactive query or embedded mode
Example: Simple Data Retrieval
Example: Simple Data Retrieval
To find commission percentage and year of hire of salesperson
186:
SELECT COMMPERCT, YEARHIRE FROM
SALESPERSON WHERE SPNUM=186
To retrieve entire record for salesperson 186:
SELECT * FROM SALESPERSON WHERE SPNUM=186
To list salesperson number and salesperson name of all of
salespersons:
SELECT SPNUM, SPNAME FROM SALESPERSON
To return all rows and columns of data in Salesperson table:
SELECT * FROM SALESPERSON
Retrieving Other Values
• In Microsoft SQL Server, SELECT statement can
be used to evaluate expressions
– Syntax:
SELECT expression
• Expression: Any mathematical or logical
expression that returns result
• For example:
SELECT 5 + 7
will return “12”
• Syntax for resolving function:
SELECT function [(parameter_list)]
Operators and Functions
• SQL operators:
– Arithmetic operators
– Logical operators
• Used in WHERE clause to build search conditions that depend on
more than one qualifying condition
• Unary operator:
– Operator applied to only one operand
– Typical format : operator operand
– For example: NOT A
• Binary operator:
– Operator applied to two operands
– Typical format: operand operator operand
– For example: A OR B
Arithmetic Operators
Arithmetic Operators
• To add two values:
SELECT 5+ 5 total_value
• To concatenate two values as strings:
SELECT ‘5’ + ‘5’ total_value
• Data type may affect precision and scale
of result of arithmetic operation
Comparison Operators
Comparison Operators
• Can be used:
– In SELECT statement’s WHERE clause
– With decision statements; for example:
• If A>B, then perform action
– By themselves or together with logical
operators
Logical Operators
Logical Operators
• Used to evaluate set of conditions
• Return results of TRUE, FALSE, or
“unknown”
• Can be used:
– In SELECT statement WHERE clause
– With decision statements; for example:
• If A AND B are true, then perform action
Example: Comparison and Logical Operators
Example: Comparison and Logical Operators
• To list customer numbers, customer names, and
headquarter cities of customers that are
headquartered in New York or that satisfy two
conditions: having customer number higher than
1500 and being headquartered in Atlanta
SELECT CUSTNUM, CUSTNAME, HQCITY FROM
CUSTOMER WHERE HQCITY=’New York’ OR
(CUSTNUM>1500 AND HQCITY=’Atlanta’)
• Note that:
– AND has higher precedence than OR
– Clauses in parentheses evaluated first
The Like Operator
The Like Operator
• Used when criteria in WHERE clause of
SELECT query are only partially known
– For example, to find records for customers
whose names begin with letter A
SELECT * FROM CUSTOMER WHERE
CUSTNAME LIKE ‘A%’
Standard SQL Functions
• Functions supported by various DBMS providers
vary widely from ANSI standard function list and
from each other
• Deterministic functions:
– Always return same result if you pass in same
arguments
– E.g. ABS: Returns absolute value of number
• Nondeterministic functions:
– May return different results when called with same
arguments
– E.g. GETDATE( ): Accepts no arguments and returns
only current date and time
General Function Categories
• Numeric
– Functions that operate with numbers
– Statistical functions (e.g. mean and standard
deviations)
– Random number generator
• Mathematical
– Perform specific mathematic calculations
– For example, trigonometric functions for SIN,
COS, and so forth
General Function Categories
• Date/Time
– Performing calculations on dates and times, for
example:
• Current date/time information
• Formatting date and time strings
• Performing calculations based on date and time
• Aggregate
– Used to generate aggregate values based on
sets of numeric values
– For example, generating total, count, or
average
General Function Categories
• String
– Perform string manipulations such as:
•
•
•
•
•
•
Modifying strings
Locating patterns within string
Inserting characters
Concatenating strings
Finding string length
Changing character case
• Conversion
– Used to convert values between data types
– Allow explicit conversions between otherwise
incompatible types
Sample SQL Functions
• Standard SQL-99 functions include:
–
–
–
–
–
BIT_LENGTH
CAST
CURRENT_DATE
SUBSTRING
UPPER
• SQL Server built-in aggregate functions include:
–
–
–
–
AVG
COUNT
MAX
SUM
DML Commands
• Three basic DML statements (ANSI SQL):
– INSERT:
• To add rows to table
– UPDATE:
• To modify values in existing columns and rows
– DELETE:
• To remove rows from tables
• Statements may be subject to constraints
or other limits placed on table
– E.g. Foreign key constraint may disallow
deletion of row referenced in another table
DDL Commands
• DDL commands are used to create and
manage server and database objects
– Server objects: Objects implemented at server
level
– Database objects: Database-specific objects,
such as tables
• DDL commands vary widely in how they
are implemented by various DBMSs
DDL Commands
• Three basic object management
commands:
– CREATE
• To create server and database objects, such as:
– CREATE TABLE and CREATE INDEX
– ALTER:
• To modify server and database objects, such as:
– ALTER TABLE and ALTER INDEX
– DROP:
• To delete server and database objects, such as:
– DROP TABLE and DROP INDEX
Summary
• SQL: Standard relational DBMS language developed
by ANSI that incorporates data definition language
(DDL) and DML (data manipulation language (DML)
features
• SQL commands follow specified syntax structure,
using command name, command keywords, and
parameters
• SQL commands feature arithmetical, comparison, and
logical operators to modify queries and results
• Different SQL vendors may provide different functions,
in categories such as mathematical, numeric,
date/time, aggregate, string, conversion
• DML commands include INSERT, UPDATE, and
DELETE
• DDL commands include CREATE, ALTER, and DROP
Key Terms
•
•
•
•
•
•
•
•
•
Access path
Aggregate function
Batch
Binary Operator
Built-in functions
Clause
Command operators
Command syntax
Data definition language
(DDL)
• Data manipulation
language (DML)
• Data query language
(DQL)
• Declarative statement
• Default database
• Deterministic function
• Domain
• Dynamic SQL
• Embedded SQL
• Explicit conversion
• Function
• Implicit conversion
• Interactive SQL
Key Terms
•
•
•
•
•
•
•
•
•
•
•
Keyword
Minimally logged operation
Non-logged operation
Nondeterministic function
Operator precedence
Parameters
Parsing
Procedure
Qualifying conditions
Query mode
Relational result
•
•
•
•
•
•
•
•
•
•
Result set
Script
Search argument
Sqlcmd
Subquery
Temporary table
Transaction control
User-defined data type
Unary operator
Working database
Copyright Notice
Copyright 2008 John Wiley & Sons, Inc.
All rights reserved. Reproduction or translation of this
work beyond that permitted in section 117 of the 1976
United States Copyright Act without express
permission of the copyright owner is unlawful.
Requests for further information should be addressed
to the Permissions Department, John Wiley & Sons,
Inc. The purchaser may make back-up copies for
his/her own use only and not for distribution or resale.
The Publisher assumes no responsibility for errors,
omissions, or damages caused by the use of these
programs or from the use of the information herein.