Download SQL Commands

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

Relational algebra wikipedia , lookup

DBase wikipedia , lookup

Oracle Database wikipedia , lookup

Microsoft Access wikipedia , lookup

Tandem Computers wikipedia , lookup

Database wikipedia , lookup

Functional Database Model wikipedia , lookup

Ingres (database) wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Clusterpoint wikipedia , lookup

Null (SQL) wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Database model wikipedia , lookup

Relational model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
SQL IMPLEMENTATION & ADMINISTRATION
Querying the Database
LET’S TALK BASIC SQL COMMANDS
The basic SQL commands fall into 2 categories: data manipulation language commands (DML)
and data definition language commands (DDL). As the names suggest, DML is used to
manipulate the data in the database - i.e. to retrieve (query), modify, remove and add data.
DDL is used to define database objects.
The verbs for the basic SQL commands are:
• SELECT - to retrieve (query) data
• UPDATE - to modify existing data
• DELETE - to modify existing data
• INSERT - to add new data
We further break down SQL commands into the following categories:
• Data Creation
• Data Manipulation
• Data Retrival
• Advanced SQL with JOINS, Subqueries and UNIONS
SQL COMMANDS
SQL Commands
Data Creation
SQL Create Database
Use this to create a database.
-- CREATE DATABASE database_name
Once you create the database, you have to move to it, or select it by using the
following command: -- USE database_name
SQL Create Table
This SQL Create Table will be used very often throughout the tutorial. It is used to
create a table, in our case, mainly to create sample tables.
CREATE TABLE table_name
(
field1 data_type [primary key],
field2 data_type [NOT NULL],
field3 data_type [NULL],
....
)
SQL COMMANDS
SQL Commands
Data Creation
SQL Alter Table
Used less often, but it is very handy to know this command. With this you can
basically edit a table structure.
To add a column:
ALTER TABLE table_name
ADD new_field data_type [NULL]
To delete a column:
ALTER TABLE table_name
DROP COLUMN field_name
SQL Drop Table
Used to delete a table, not just the content. This command is also used very often
during the tutorial. So, you need to master this too.
--DROP TABLE table_name
SQL COMMANDS
SQL Commands
Data Retrieval
Amongst all SQL Commands, SQL Select can be regarded as the heart and soul of
SQL. The main reason for having a database is to retrieve the information.
The simplest form of SQL commands is just a SELECT FROM statement. Then if you
need to limit the result you introduce the WHERE clause. In the WHERE clause you
can use operators such as Like, And, Or, Between, and In.
SQL Select
Use this to select data from a table or tables. You are able to select all columns in a
table or only some columns. You can also select calculated fields or results of
another SQL commands.
SELECT column_list
FROM Table_name(s)
If you need to select all columns from a table, you can use "*" to replace column_list.
SELECT * FROM Table_name(s)
SQL COMMANDS
SQL Commands
Data Retrieval
SQL Distinct
Use this to select unique data from a table or tables.
SELECT DISTINCT column_list
FROM Table_name(s)
The "column_list" after the DISTINCT keyword determine the uniqueness of the
rows. If you select only one column, the SQL will select unique entries of that
column. If you select two columns, the SQL will select unique combination of those
two columns.
SQL Where
Use this to filter selected results.
SELECT column_list
FROM Table_name(s)
WHERE conditions
SQL COMMANDS
SQL Commands
Data Retrieval
SQL Distinct
Use this to select unique data from a table or tables.
SELECT DISTINCT column_list
FROM Table_name(s)
The "column_list" after the DISTINCT keyword determine the uniqueness of the
rows. If you select only one column, the SQL will select unique entries of that
column. If you select two columns, the SQL will select unique combination of those
two columns.
SQL Where
Use this to filter selected results.
SELECT column_list
FROM Table_name(s)
WHERE conditions
SQL COMMANDS
SQL Commands
Data Retrieval
SQL Where
What you need to know about SQL where are:
• Enclosed with quotes if the field in where condition is a text field (check with your
system, sometimes it allows either single or double quote).
• If you use numeric field in the condition, use the value only. No quotes around.
• The equality operators that are allowed for the conditions are: = , > , < , >= , <= or
<> (unequal).
SQL Like
SQL Like is used along with the where clause, as a smart way to search on a pattern.
A pattern can include regular characters and wildcard characters.
SELECT *
FROM table_name
WHERE column_name [NOT] LIKE pattern
SQL COMMANDS
SQL Commands
Data Retrieval
SQL Like
SQL Like is used along with the where clause, as a smart way to search on a pattern.
A pattern can include regular characters and wildcard characters.
Wildcards:
Wildcard character
Description
%
Match any string, zero or more
_ (underscore)
Any single character
[ ]
Any single character within the specified range ([a-f]) or set
([abcdef]).
[^]
Any single character not within the specified range ([^a-f])
or set ([^abcdef]).
SQL COMMANDS
SQL Commands
Data Retrieval
SQL Count
Counting number of rows.
-- SELECT count(*) FROM table_name WHERE last_name like ‘%Smith%’
SQL SUM
Getting the sum of a field
-- SELECT sum(total_cost) from orders
SQL MAX
This function will return the highest value.
-- SELECT max(order_date) from orders
SQL MIN
This function will return the lowest value.
-- SELECT min(order_date) from order
SQL AVG
This function will return the average value.
--SELECT avg(qty) from orders
SQL COMMANDS
SQL Commands
Data Retrieval
SQL ORDER By
Sorting the output
-- SELECT * FROM table_name(s) ORDER BY COLUMN_NAME
SQL AND OR
Connecting two or more conditions in the Where or Having clause.
--SELECT * from table_name(s) where lastname = ‘Smith’ AND firstname = ‘Frank’
--SELECT * from table_name(s) where (lastname = ‘Smith’ OR lastname = ‘Smyth’)
SQL Group By
Grouping rows into sets.
--SELECT * from table_names GROUP by lastname
SQL Having
To filter the result of aggregation
--SELECT count(*) from orders where lastname = ‘Smith’ Having count(*) > 1
SQL Between
Added to conditions to show results between two values.
-- SELECT * from Customers where lastname between ‘Smith’ and ‘Turner’
SQL COMMANDS
SQL Commands
Data Manipulation
SQL Update statement is a group of SQL commands to modify data. There are three
in this category.
1. SQL Insert command inserts data into a table.
2. SQL Update command updates data in a table.
3. SQL Delete command deletes rows in a table.
SQL INSERT
To add rows to a table, you use SQL Insert command. There are two methods, one is
with the VALUES keyword and second is with a SELECT statement.
The syntax to insert a row into a table with values:
INSERT INTO table_name[(column_list)]
VALUES (value_list)
The syntax to insert a row into a table from a select statement:
The syntax is:
INSERT INTO table_name[(column_list)]
SELECT column_list FROM table_name WHERE conditions
SQL COMMANDS
SQL Commands
Data Manipulation
SQL UPDATE
To change existing rows, you use SQL Update command. You can use it to change
values in a single row, groups of rows or all rows. You can also update a table based
on values in other tables.
UPDATE table_name
SET column_name=expression,column_name=expression, . . .
WHERE conditions
SQL DELETE
To remove rows, you use SQL Delete command. You can delete one rows, group of
rows or all rows. You can also delete rows based on values in other tables.
DELETE FROM table_name
WHERE conditions
SQL COMMANDS
SQL Commands
LET’S TALK INDEXING
One of the most important routes to high performance in a SQL Server database is the index.
Indexes speed up the querying process by providing swift access to rows in the data tables,
similarly to the way a book’s index helps you find information quickly within that book.
The primary reason indexes are built is to provide faster data access to the specific data your
query is trying to retrieve. This could be either a clustered or non-clustered index. Without
having an index SQL Server would need to read through all of the data in order to find the rows
that satisfy the query. If you have ever looked at a query plan the difference would be an Index
Seek vs a Table Scan as well as some other operations depending on the data selected.
Indexes directly affect the performance of database applications. This article uses analogies to
describe how indexes work. The estimated execution plan feature of the Query Window is
utilized to compare the performance of two queries in a batch.
“An index makes the query fast” is the most basic explanation of an index.
An index is a distinct structure in the database that is built using the create index statement. It
requires its own disk space and holds a copy of the indexed table data. That means that an
index is pure redundancy. Creating an index does not change the table data; it just creates a
new data structure that refers to the table. A database index is, after all, is very much like the
index at the end of a book: it occupies its own space, it is highly redundant, and it refers to the
actual information stored in a different place.
INDEXING
SQL Server 2012: Indexing
Searching in a database index is like searching in a printed telephone directory. The
key concept is that all entries are arranged in a well-defined order. Finding data in
an ordered data set is fast and easy because the sort order determines each entries
position.
A database index is, however, more complex than a printed directory because it
undergoes constant change. Updating a printed directory for every change is
impossible for the simple reason that there is no space between existing entries to
add new ones. A printed directory bypasses this problem by only handling the
accumulated updates with the next printing. An SQL database cannot wait that long.
It must process insert, delete and update statements immediately, keeping the
index order without moving large amounts of data.
Indexes are created on columns in tables or views. The index provides a fast way to
look up data based on the values within those columns. For example, if you create
an index on the primary key and then search for a row of data based on one of the
primary key values, SQL Server first finds that value in the index, and then uses the
index to quickly locate the entire row of data. Without the index, a table scan would
have to be performed in order to locate the row, which can have a significant effect
on performance.
INDEXING
SQL Server 2012: Indexing
In addition to an index being clustered or non-clustered, it can be configured in other ways:
Composite index: An index that contains more than one column. In both SQL Server 2005 and
2008, you can include up to 16 columns in an index, as long as the index doesn’t exceed the
900-byte limit. Both clustered and non-clustered indexes can be composite indexes.
Unique Index: An index that ensures the uniqueness of each value in the indexed column. If the
index is a composite, the uniqueness is enforced across the columns as a whole, not on the
individual columns. For example, if you were to create an index on the FirstName and
LastName columns in a table, the names together must be unique, but the individual names
can be duplicated.
A unique index is automatically created when you define a primary key or unique constraint:
Primary key: When you define a primary key constraint on one or more columns, SQL
Server automatically creates a unique, clustered index if a clustered index does not
already exist on the table or view. However, you can override the default behavior
and define a unique, non-clustered index on the primary key.
Unique: When you define a unique constraint, SQL Server automatically creates a unique,
non-clustered index. You can specify that a unique clustered index be created if a
clustered index does not already exist on the table.
Covering index: A type of index that includes all the columns that are needed to process a
particular query. For example, your query might retrieve the FirstName and LastName columns
from a table, based on a value in the ContactID column. You can create a covering index that
includes all three columns.
INDEXING
SQL Server 2012: Indexing
LET’S TALK INDEXING ON VIEWS
Creating Indexed Views
An indexed view is different from other views because it is materialized and stored on disk in
the same way as a table. An interesting point about an indexed view is that the query optimizer
may reference a view to improve performance even if it is not referenced in the query.
Before you can create an indexed view, you need to make sure that all the referenced tables
meet a few requirements. First, all referenced tables must be contained within the same
database. If any computed columns in the base tables are not deterministic, they must be
removed. Deterministic is defined as always returning the same value or result set. Since a
requirement of an indexed view is that it be deterministic, all the columns in the base table
must also be deterministic. You can use the following code, which leverages the
COLUMNPROPERTY scalar function to determine if the column is deterministic.
A clustered index cannot be created on a view if the view references any nondeterministic
functions.
VIEWS
Views – Additional Information
As beneficial as indexes can be, they must be designed carefully. Because they can
take up significant disk space, you don’t want to implement more indexes than
necessary. In addition, indexes are automatically updated when the data rows
themselves are updated, which can lead to additional overhead and can affect
performance. As a result, index design should take into account a number of
considerations.
SUMMARY
Summary