SlideShare ist ein Scribd-Unternehmen logo
1 von 90
SQLSQL
Piotr Mariat
School complex no. 26
in Warsaw
Introduction to MySQLIntroduction to MySQL
The MySQL server is the meager of your database

It creates new database

It knows where the database are stored

It stores and retrieves information, guided by the request, or
queries, that it receives
To make a request that MySQL can understand, you need to build an
SQL query and send it to the server
MS SQL ServerMS SQL Server
Microsoft SQL Server is a relational database management system
developed by Microsoft. As a database server, it is a software
product whose primary function is to store and retrieve data as
requested by other software applications, be it those on the same
computer or those running on another computer across a network
(including the Internet). There are at least a dozen different editions
of Microsoft SQL Server aimed at different audiences and for
workloads ranging from small single-machine applications to large
Internet-facing applications with many concurrent users.
Introduction to SQLIntroduction to SQL

SQL stands for Structured Query Language.

It is the most commonly used relational database language today.

SQL works with a variety of different fourth-generation (4GL)
programming languages, such as Visual Basic.
SQL is used forSQL is used for

Data Definition Language (DDL)
Create/alter/delete tables and their attributes

Data Manipulation Language (DML)
Query one or more tables
Insert/delete/modify tuples in tables

Data Control Language(DCL)
Authorizes users to access and manipulate data

Data Query Language(DQL)

Transaction Control Language(TCL)
DMLDML
The Data Manipulation Language (DML) is the subset of SQL used
to add, update and delete data:

INSERT adds rows (formally tuples) to an existing table

UPDATE modifies a set of existing table rows

DELETE removes existing rows from a table

MERGE is used to combine the data of multiple tables. It combines
the INSERT and UPDATE elements
DDLDDL
The Data Definition Language (DDL) manages table and index
structure. The most basic items of DDL are:

CREATE creates an object (a table, for example) in the database

ALTER modifies the structure of an existing object in various
ways, for example, adding a column to an existing table or a
constraint

TRUNCATE deletes all data from a table in a very fast way,
deleting the data inside the table and not the table itself. It usually
implies a subsequent COMMIT operation, i.e., it cannot be rolled
back (data is not written to the logs for rollback later, unlike
DELETE).

DROP deletes an object in the database, usually irretrievably, i.e., it
cannot be rolled back
SQL StandardsSQL Standards

SQL86 – first formalized standard

SQL89 - was just minor revision, adopted as FIPS 127-1

SQL92 - Major revision (ISO 9075), adopted as FIPS 127-2

SQL1999 - Added regular expression matching, recursive queries
(e.g. transitive closure), triggers, support for procedural and
control-of-flow statements, non-scalar types, and some object-
oriented features (e.g. structured types). Support for embedding
SQL in Java (SQL/OLB) and vice versa (SQL/JRT).

SQL2003 - Introduced XML-related features (SQL/XML), window
functions, standardized sequences, and columns with auto-
generated values (including identity-columns).
SQL StandardsSQL Standards

SQL2006 - 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 enables 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

SQL2009 - Legalizes ORDER BY outside cursor definitions. Adds
INSTEAD OF triggers. Adds the TRUNCATE statement

SQL2011 - One of the main new features is improved support for
temporal databases. Language enhancements for temporal data
definition and manipulation
SQL Basic commandsSQL Basic commands

SELECT

DISTINCT

WHERE

AND

OR

IN

BETWEEN

WILDCARD

LIKE

ORDER BY

GROUP BY

HAVING

ALIAS

AS

SELECT UNIQUE

INSERT INTO

INSERT INTO SELECTED

UPDATE

DELETE FROM
SQL RequirementsSQL Requirements

SQL Must be embedded in a programming language, or used with a
4GL like VB

SQL is a free form language so there is no limit to the the number
of words per line or fixed line break.

The case of the SQL words doesn't matter, select is same as
SELECT .On the other hand case of the table names, column
names, and other variable information does matter if you use Linux
or Unix, so they need to be exact match. Windows however isn't so
picky so case doesn't matter for it
SQL RequirementsSQL Requirements
Row is named LastName and table is named Member
Linux and Unix example
SELECT LastName FROM Member – Correct
SELECT lastname FROM member - Incorrect
Windows example
SELECT LastName FROM Member
SELECT lastname FROM member
Both are Correct
*Commands are bold and in uppercase for your comfort
SQL is a Relational DatabaseSQL is a Relational Database
A Fully Relational Database Management System must:

Represent all info in database as tablesRepresent all info in database as tables

Keep logical representation of data independent from its physical storageKeep logical representation of data independent from its physical storage
characteristicscharacteristics

Use one high-level language for structuring, querying, and changing info inUse one high-level language for structuring, querying, and changing info in
the databasethe database

Support the main relational operationsSupport the main relational operations

Support alternate ways of looking at data in tablesSupport alternate ways of looking at data in tables

Provide a method for differentiating between unknown values and nulls (zeroProvide a method for differentiating between unknown values and nulls (zero
or blank)or blank)

Support Mechanisms for integrity, authorization, transactions, and recoverySupport Mechanisms for integrity, authorization, transactions, and recovery
Data TypeData Type

CHARACTER(n) - Character string. Fixed-length n

VARCHAR(n) or CHARACTER VARYING(n) -
Character string. Variable length. Maximum length n

BINARY(n) - Binary string. Fixed-length n

BOOLEAN - Stores TRUE or FALSE values

VARBINARY(n) or BINARY VARYING(n) -
Binary string. Variable length. Maximum length n

INTEGER(p) - Integer numerical (no decimal). Precision p

SMALLINT - Integer numerical (no decimal). Precision 5

INTEGER - Integer numerical (no decimal). Precision 10

BIGINT - Integer numerical (no decimal). Precision 19

DECIMAL(p,s) - Exact numerical, precision p, scale s. Example:
decimal(5,2) is a number that has 3 digits before the decimal and 2
digits after the decimal
Data TypeData Type

NUMERIC(p,s) - Exact numerical, precision p, scale s. (Same as
DECIMAL)

FLOAT(p) - Approximate numerical, mantissa precision p. A
floating number in base 10 exponential notation. The size argument
for this type consists of a single number specifying the minimum
precision

REAL - Approximate numerical, mantissa precision 7

FLOAT - Approximate numerical, mantissa precision 16

DOUBLE PRECISION - Approximate numerical, mantissa
precision 16

DATE - Stores year, month, and day values

TIME - Stores hour, minute, and second values

TIMESTAMP - Stores year, month, day, hour, minute, and second
values
Data TypeData Type

INTERVAL - Composed of a number of integer fields, representing
a period of time, depending on the type of interval

ARRAY - A set-length and ordered collection of elements

MULTISET - A variable-length and underscored collection of
elements

XML - Stores XML data
Data Types in shortData Types in short
In short:

Characters: CHAR(20), VARCHAR(50)

Numbers: INT, BIGINT, SMALLINT, FLOAT

Others: MONEY, DATETIME, …
Every attribute must have an atomic type, hence tables are flat
Data HierarchyData Hierarchy
1) user-defined data
types (highest)
2) sql_variant
3) Xml
4) Datetimeoffset
5) Datetime2
6) Datetime
7) Smalldatetime
8) Date
9) Time
10)Float
11)Real
12)Decimal
13)Money
1) Smallmoney
2) Bigini
3) Ini
4) Smallini
5) Tinyini
6) Bit
7) Ntext
8) Text
9) Image
10)Timestamp
11)Uniqueidentifier
25)nvarchar (including
nvarchar(max) )
26)Nchar
27)varchar (including
varchar(max) )
28)Char
29)varbinary (including
varbinary(max) )
30)binary (lowest)
SQL Server uses the following precedence order
for data types:
DesignDesign

SQL represents all information in the form of tables

Supports three relational operations:
SELECTION means which rows are to be returned.
PROJECTION means choosing which columns (or expressions) the
query shall return.
Example
SELECT a, b, c FROM foobar WHERE x=3
“a,b,c” is PROJECTION part, “x=3” is SELECTION part
DesignDesign
JOIN clause is used to COMBINE rows from two or more tables,
based on a common field between them. There is 4 different types
of JOIN command

INNER JOIN: Returns all rows when there is at least one match in
BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched
rows from the right table

RIGHT JOIN: Return all rows from the right table, and the
matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the
tables
Creating and deleting a database and tables in itCreating and deleting a database and tables in it
Database

CREATE DATABASE database_name - command for creation

DROP DATABASE database_name – delete command
Table

CREATE TABLE table_name (column_name1
data_type(size),column_name2 data_type(size),....); - universal
command for table creation

DROP INDEX index_name ON table_name – delete command for
MS Access

DROP INDEX table_name.index_name – delete command for
MySQL server

Etc.
Altering tablesAltering tables
With ALTER TABLE command you can:

ALTER TABLE table_name ADD column_name datatype – add a
column

ALTER TABLE table_name DROP COLUMN column_name -
deleate them

ALTER TABLE table_name ALTER COLUMN column_name
datatype – alter there data type (command for SQL server and MS
Access)

ALTER TABLE table_name MODIFY COLUMN column_name
datatype - alter there data type (command for MySQL and Oracle
before version 10G, versions after dont need COLUMN)
SchemaSchema

A schema is a collection of database objects (as far as this hour is
concerned—tables) associated with one particular database
username. This username is called the schema owner, or the owner
of the related group of objects. You may have one or multiple
schemas in a database. Basically, any user who creates an object has
just created his or her own schema. So, based on a user's privileges
within the database, the user has control over objects that are
created, manipulated, and deleted. A schema can consist of a single
table and has no limits to the number of objects that it may contain,
unless restricted by a specific database implementation.
Schema creationSchema creation
CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n
] ]
<schema_name_clause> ::=
{schema_name | AUTHORIZATION owner_name
| schema_name AUTHORIZATION owner_name }
<schema_element> ::=
{ table_definition | view_definition | grant_statement |
revoke_statement | deny_statement }
Arguments

schema_name - Is the name by which the schema is identified
within the database.

AUTHORIZATION owner_name - Specifies the name of the
database-level principal that will own the schema. This principal
may own other schemas, and may not use the current schema as its
default schema
Schema creationSchema creation

table_definition - Specifies a CREATE TABLE statement that
creates a table within the schema. The principal executing this
statement must have CREATE TABLE permission on the current
database.

view_definition - Specifies a CREATE VIEW statement that
creates a view within the schema. The principal executing this
statement must have CREATE VIEW permission on the current
database.

grant_statement - Specifies a GRANT statement that grants
permissions on any securable except the new schema.

revoke_statement - Specifies a REVOKE statement that revokes
permissions on any securable except the new schema.

deny_statement - Specifies a DENY statement that denies
permissions on any securable except the new schema.
SQL TablesSQL Tables
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Tuples or rows
Attribute names
Product
Table name
Tables ExplainedTables Explained

The schema of a table is the table name and its attributes:
Product(PName, Price, Category, Manfacturer)

A key is an attribute whose values are unique, I underlined a
key
Product(PName, Price, Category, Manfacturer)

A tuple = a record
Restriction: all attributes are of atomic type

A table = a set of tuples
Adding data to tableAdding data to table
It is possible to write the INSERT INTO statement in two forms.

The first form does not specify the column names where the data
will be inserted, only their values:
INSERT INTO table_name VALUES (value1,value2,value3,...);

The second form specifies both the column names and the values to
be inserted:
INSERT INTO table_name (column1,column2,column3,...) VALUES
(value1,value2,value3,...);
Updating recordsUpdating records
The UPDATE statement is used to update existing records in a table.
UPDATE table_name SET column1=value1,column2=value2,...
WHERE some_column=some_value;
Coping data from one table to anotherCoping data from one table to another
The INSERT INTO SELECT statement selects data from one table
and inserts it into an existing table. Any existing rows in the target
table are unaffected.

We can copy all columns from one table to another, existing table
INSERT INTO table2 SELECT * FROM table1;

Or we can copy only the columns we want to into another, existing
table:
INSERT INTO table2 (column_name(s)) SELECT column_name(s)
FROM table1;
Deleting recordsDeleting records
The DELETE statement is used to delete rows in a table.
DELETE FROM table_name WHERE some_column=some_value;
Grouping data
The GROUP BY statement is used in conjunction with the aggregate
functions to group the result-set by one or more columns.
SELECT column_name, aggregate_function(column_name) FROM
table_name WHERE column_name operator value GROUP BY
column_name;
Grouping dataGrouping data
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering is ascending, unless you specify the DESC keyword.
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname
VariableVariable
In SQL Server (Transact-SQL), a variable allows a programmer to
store data temporarily during the execution of code.
The syntax to declare variables in SQL Server using the DECLARE
statement is:
DECLARE @variable_name datatype [ = initial_value ],
@variable_name datatype [ = initial_value ],
...;
Parameters or Arguments
variable_name -The name to assign to the variable.
Datatype - The datatype to assign to the variable.
initial_value - Optional. It is the value initially assigned to the
variable when it is declared.
ConditionsConditions
Imposes conditions on the execution of a Transact-SQL statement. The
Transact-SQL statement that follows an IF keyword and its condition is
executed if the condition is satisfied: the Boolean expression returns TRUE.
The optional ELSE keyword introduces another Transact-SQL statement
that is executed when the IF condition is not satisfied: the Boolean
expression returns FALSE.
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
An IF...ELSE construct can be used in batches, in stored procedures, and in ad
hoc queries. When this construct is used in a stored procedure, it is
frequently used to test for the existence of some parameter. IF tests can be
nested after another IF or following an ELSE. The limit to the number of
nested levels depends on available memory.
SQL QuerySQL Query

Most Basic form:
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
Simple SQL Query ExampleSimple SQL Query Example
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT *
FROM Product
WHERE category=‘Gadgets’
SELECT *
FROM Product
WHERE category=‘Gadgets’
Product
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks“selection”
Simple SQL Query ExampleSimple SQL Query Example
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Product
PName Price Manufacturer
SingleTouch $149.99 Canon
MultiTouch $203.99 Hitachi
“selection” and
“projection”
Combining QueriesCombining Queries
The UNION operator is used to combine the result-set of two or more
SELECT statements.
Notice that each SELECT statement within the UNION must have
the same number of columns. The columns must also have similar
data types. Also, the columns in each SELECT statement must be
in the same order.
The column names in the result-set of a UNION are usually equal to
the column names in the first SELECT statement in the UNION.
Combining QueriesCombining Queries
SELECT column_name(s)
FROM table1
UNION
SELECT column_name(s)
FROM table2;
SELECT column_name(s)
FROM table1
UNION ALL
SELECT column_name(s)
FROM table2;
The UNION operator selects only distinct values by default. To allow
duplicate values, use the ALL keyword with UNION.
NotationNotation
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Case sensitivityCase sensitivity

Case insensitive:
Same: SELECT Select select
Same: Product product
Different: ‘Seattle’ ‘seattle’

Constants:
‘abc’ - yes
“abc” - no
Eliminating DuplicatesEliminating Duplicates
SELECT DISTINCT category
FROM Product
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
JoinsJoins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
JoinsJoins
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch $149.99
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
SELECT PName, Price
FROM Product, Company
WHERE Manufacturer=CName AND Country=‘Japan’
AND Price <= 200
Cross joinCross join
PlayerName DepartmentId Scores
Jason 1 3000
Irene 1 1500
Jane 2 1000
David 2 2500
Paul 3 2000
James 3 2000
DepartmentId DepartmentName
1 IT
2 Marketing
3 HR
SELECT *
FROM GameScores
CROSS JOIN Departments
SELECT *
FROM GameScores
CROSS JOIN Departments
Playername Departamentid Scores Departamenti
d
Departamentname
Jason 1 3000 1 IT
Irene 1 1500 1 IT
Jane 2 1000 2 IT
David 2 2500 2 IT
Paul 3 2000 3 IT
James 3 2000 3 IT
Jason 1 3000 2 Marketing
... ... ... ... ...
Departments
Gamescores
Multiple joinsMultiple joins
Although each join specification joins only two tables, FROM clauses
can contain multiple join specifications. This allows many tables to
be joined for a single query.
SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
JOIN TableB
ON TableB.aID = TableA.aID
JOIN TableC
ON TableC.cID = TableB.cID
JOIN TableD
ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now())
ConstraintsConstraints
SQL constraints are used to specify rules for the data in a table. If
there is any violation between the constraint and the data action, the
action is aborted by the constraint.
Constraints can be specified when the table is created (inside the
CREATE TABLE statement) or after the table is created (inside
the ALTER TABLE statement).
ConstraintsConstraints
In SQL, we have the following constraints:

NOT NULL - Indicates that a column cannot store NULL value

UNIQUE - Ensures that each row for a column must have a unique
value

PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Ensures that a column (or combination of two or more columns)
have an unique identity which helps to find a particular record in a
table more easily and quickly

FOREIGN KEY - Ensure the referential integrity of the data in
one table to match values in another table

CHECK - Ensures that the value in a column meets a specific
condition

DEFAULT - Specifies a default value when specified none for this
column
Constraints – NOT NULLConstraints – NOT NULL
The NOT NULL constraint enforces a column to NOT accept NULL
values.
The NOT NULL constraint enforces a field to always contain a value.
This means that you cannot insert a new record, or update a record
without adding a value to this field.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Constraints - UNIQUEConstraints - UNIQUE
The UNIQUE constraint uniquely identifies each record in a database
table. The UNIQUE and PRIMARY KEY constraints both provide
a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE
constraint defined on it. Note that you can have many UNIQUE
constraints per table, but only one PRIMARY KEY constraint per
table.
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) )
Constraints - PRIMARY KEYConstraints - PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a
database table. Primary keys must contain UNIQUE values. A
primary key column cannot contain NULL values. Most tables
should have a primary key, and each table can have only ONE
primary key.
Constraints - PRIMARY KEYConstraints - PRIMARY KEY

MySQL
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT
NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

SQL Server / Oracle / MS Access
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY
KEY,
LastName varchar(255) NOT
NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Constraints - FOREIGN KEYConstraints - FOREIGN KEY

MySQL
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

SQL Server / Oracle / MS
Access
CREATE TABLE Orders
(
O_Id int NOT NULL
PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY
REFERENCES Persons(P_Id)
)
A FOREIGN KEY in one table points to a PRIMARY KEY in
another table.
Constraints - PRIMARY KEY and FOREIGN KEYConstraints - PRIMARY KEY and FOREIGN KEY
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
CName StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
Primary Key
Foreign
key
Constraints - CHECKConstraints - CHECK
The CHECK constraint is used to limit the value range that can be
placed in a column. If you define a CHECK constraint on a single
column it allows only certain values for this column. If you define a
CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
).
Constraints - DEFAULTConstraints - DEFAULT
The DEFAULT constraint is used to insert a default value into a
column.
The default value will be added to all new records, if no other value is
specified.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT “name or data type”
)
Meaning (Semantics) of SQL QueriesMeaning (Semantics) of SQL Queries
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
SELECT a1, a2, …, ak
FROM R1 AS x1, R2 AS x2, …, Rn AS xn
WHERE Conditions
Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions
then Answer = Answer ∪ {(a1,…,ak)}
return Answer
Answer = {}
for x1 in R1 do
for x2 in R2 do
…..
for xn in Rn do
if Conditions
then Answer = Answer ∪ {(a1,…,ak)}
return Answer
Subqueries Returning RelationsSubqueries Returning Relations
Company(name, city)
Product(pname, maker)
Purchase(id, product, buyer)
Return cities where one can find companies that manufacture products
bought by Joe Blow
SELECT Company.city
FROM Company
WHERE Company.name IN
SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
SELECT Company.city
FROM Company
WHERE Company.name IN
SELECT Product.maker
FROM Purchase , Product
WHERE Product.pname=Purchase.product
AND Purchase .buyer = ‘Joe Blow‘);
IndexIndex
An index can be created in a table to find data more quickly and
efficiently.
The users cannot see the indexes, they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than updating a
table without (because the indexes also need an update). So you
should only create indexes on columns (and tables) that will be
frequently searched against.
Index - commandsIndex - commands

Creates an index on a table.
Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)

Creates a unique index on a
table. Duplicate values are not
allowed:
CREATE UNIQUE INDEX
index_name
ON table_name (column_name)
TransactionsTransactions
A transaction is a unit of work that is performed against a database.
Transactions are units or sequences of work accomplished in a
logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the
database. For example, if you are creating a record or updating a
record or deleting a record from the table, then you are performing
transaction on the table. It is important to control transactions to
ensure data integrity and to handle database errors.
Transactions – proprietiesTransactions – proprieties
Transactions have the following four standard properties, usually
referred to by the acronym ACID:

Atomicity: ensures that all operations within the work unit are
completed successfully; otherwise, the transaction is aborted at the
point of failure, and previous operations are rolled back to their
former state.

Consistency: ensures that the database properly changes states
upon a successfully committed transaction.

Isolation: enables transactions to operate independently of and
transparent to each other.

Durability: ensures that the result or effect of a committed
transaction persists in case of a system failure.
Transactions - commandsTransactions - commands
There are following commands used to control transactions:

COMMIT: to save the changes.

ROLLBACK: to rollback the changes.

SAVEPOINT: creates points within groups of transactions in which
to ROLLBACK, is deleted by RELEASE SAVEPOINT

SET TRANSACTION: Places a name on a transaction.
Transactional control commands are only used with the DML
commands INSERT, UPDATE and DELETE only. They can not
be used while creating tables or dropping them because these
operations are automatically commited in the database.
Transactions – commands - COMMITTransactions – commands - COMMIT
The COMMIT command is the transactional command used to save
changes invoked by a transaction to the database.
The COMMIT command saves all transactions to the database since
the last COMMIT or ROLLBACK command.
The syntax for COMMIT command is as follows:
COMMIT;
Transactions – commands - ROLLBACKTransactions – commands - ROLLBACK
The ROLLBACK command is the transactional command used to
undo transactions that have not already been saved to the database.
The ROLLBACK command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
The syntax for ROLLBACK command is as follows:
ROLLBACK;
Transactions – commands - SAVEPOINTTransactions – commands - SAVEPOINT
A SAVEPOINT is a point in a transaction when you can roll the
transaction back to a certain point without rolling back the entire
transaction.
The syntax for SAVEPOINT command is as follows:
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among
transactional statements. The ROLLBACK command is used to
undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as follows:
ROLLBACK TO SAVEPOINT_NAME;
Transactions – commands – RELEASE SAVEPOINTTransactions – commands – RELEASE SAVEPOINT
The RELEASE SAVEPOINT command is used to remove a
SAVEPOINT that you have created.
The syntax for RELEASE SAVEPOINT is as follows:
RELEASE SAVEPOINT SAVEPOINT_NAME;
Once a SAVEPOINT has been released, you can no longer use the
ROLLBACK command to undo transactions performed since the
SAVEPOINT.
Transactions – commands – SET TRANSACTIONTransactions – commands – SET TRANSACTION
The SET TRANSACTION command can be used to initiate a
database transaction. This command is used to specify
characteristics for the transaction that follows.
For example, you can specify a transaction to be read only, or read
write.
The syntax for SET TRANSACTION is as follows:
SET TRANSACTION [ READ WRITE | READ ONLY ];
Optimistic and Pessimistic ConcurrencyOptimistic and Pessimistic Concurrency
Optimistic Concurrency
Optimistic concurrency control works on the assumption that resource
conflicts between multiple users are unlikely (but not impossible),
and allows transactions to execute without locking any resources.
Only when attempting to change data are resources checked to
determine if any conflicts have occurred. If a conflict occurs, the
application must read the data and attempt the change again.
Pessimistic Concurrency
Pessimistic concurrency control locks resources as they are required,
for the duration of a transaction. Unless deadlocks occur, a
transaction is assured of successful completion.
ViewView
In database theory, a view is the result set of a stored query on the
data, which the database users can query just as they would in a
persistent database collection object. This pre-established query
command is kept in the database dictionary. Unlike ordinary base
tables in a relational database, a view does not form part of the
physical schema: as a result set, it is a virtual table computed or
collated dynamically from data in the database when access to that
view is requested. Changes applied to the data in a relevant
underlying table are reflected in the data shown in subsequent
invocations of the view. In some NoSQL databases, views are the
only way to query data.
View - advantagesView - advantages
Views can provide advantages over tables:

Views can represent a subset of the data contained in a table. Consequently,
a view can limit the degree of exposure of the underlying tables to the outer
world: a given user may have permission to query the view, while denied
access to the rest of the base table.

Views can join and simplify multiple tables into a single virtual table.

Views can act as aggregated tables, where the database engine aggregates
data (sum, average, etc.) and presents the calculated results as part of the
data.

Views can hide the complexity of data. For example, a view could appear as
Sales2000 or Sales2001, transparently partitioning the actual underlying
table.

Views take very little space to store; the database contains only the
definition of a view, not a copy of all the data that it presents.

Depending on the SQL engine used, views can provide extra security.
View - commandsView - commands

Creation command
CREATE VIEW
view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

To update
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Now we want to add the "Category" column to the
"Current Product List" view. We will update the
view with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
CTECTE
A common table expression (CTE) can be thought of as a temporary
result set that is defined within the execution scope of a single
SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW
statement. A CTE is similar to a derived table in that it is not stored
as an object and lasts only for the duration of the query. Unlike a
derived table, a CTE can be self-referencing and can be referenced
multiple times in the same query.
Using a CTE offers the advantages of improved readability and ease in
maintenance of complex queries. The query can be divided into
separate, simple, logical building blocks. These simple blocks can
then be used to build more complex, interim CTEs until the final
result set is generated.
CTEs can be defined in user-defined routines, such as functions,
stored procedures, triggers, or views.
CTECTE
A CTE is made up of an expression name representing the CTE, an optional
column list, and a query defining the CTE. After a CTE is defined, it can
be referenced like a table or view can in a SELECT, INSERT, UPDATE,
or DELETE statement. A CTE can also be used in a CREATE VIEW
statement as part of its defining SELECT statement.
The basic syntax structure for a CTE is:
WITH expression_name [ ( column_name [,...n] ) ]
AS
( CTE_query_definition )
The list of column names is optional only if distinct names for all resulting
columns are supplied in the query definition.
The statement to run the CTE is:
SELECT <column_list>
FROM expression_name;
TriggersTriggers
A trigger is a special kind of a store procedure that executes in
response to certain action on the table like insertion, deletion or
update of data. It is a database object which is bound to a table and
is executed automatically. You can’t explicitly invoke triggers. The
only way to do this is by performing the required action no the table
that they are assigned to.
There are three action query types that you use in SQL which are
INSERT, UPDATE and DELETE. So, there are three types of
triggers and hybrids that come from mixing and matching the
events and timings that fire them. Basically, triggers are classified
into two main types:

AFTER Triggers

INSTEAD OF Triggers
AFTER triggersAFTER triggers
These triggers run after an insert, update or delete on a table. They are
not supported for views.
AFTER Triggers can be classified further into three types as:

AFTER INSERT Trigger.

AFTER UPDATE Trigger.

AFTER DELETE Trigger.
AFTER triggers - exampleAFTER triggers - example
AFTER INSERT
CREATE TRIGGER
TRG_InsertSyncEmp
ON dbo.EMPLOYEE
AFTER INSERT AS
BEGIN
INSERT INTO
EMPLOYEE_BACKUP
SELECT * FROM INSERTED
END
GO
AFTER UPDATE
CREATE TRIGGER
Departments_Update
AFTER UPDATE OF budget
ON Departments
WHEN (CURRENT_TIME >
'17:00:00')
SELECT MAX(budget) / 0
FROM Departments;
INSTEAD OF TriggersINSTEAD OF Triggers
These can be used as an interceptor for anything that anyone tried to
do on our table or view. If you define an Instead Of trigger on a
table for the DELETE operation, they try to delete rows, and they
will not actually get deleted (unless you issue another delete
instruction from within the trigger)
INSTEAD OF TRIGGERS can be classified further into three types
as:

INSTEAD OF INSERT Trigger.

INSTEAD OF UPDATE Trigger.

INSTEAD OF DELETE Trigger.
INSTEAD OF Triggers - exampleINSTEAD OF Triggers - example
INSTEAD OF INSERT
CREATE TRIGGER
InsteadTrigger on InsteadView
INSTEAD OF INSERT
AS
BEGIN
--Build an INSERT statement
ignoring inserted.ID and
--inserted.ComputedCol.
INSERT INTO BaseTable
SELECT Color, Material
FROM inserted
END;
GO
INSTEAD OF DELETE
CREATE TRIGGER
audit_Table_Deletes ON
dbo.mytesting
INSTEAD OF DELETE
AS
IF @@rowcount = 0 return;
INSERT INTO dbo.myaudit
(test_id, sometext)
SELECT d.test_id, t.sometext
FROM deleted d
JOIN dbo.mytesting t ON t.test_id
= d.test_id
Importing dataImporting data
The SQL Server Import and Export Wizard offers the simplest method
to create a Integration Services package that copies data from a
source to a destination.
The SQL Server Import and Export Wizard can copy data to and from
any data source for which a managed .NET Framework data
provider or a native OLE DB provider is available. The list of
available providers includes the following data sources:

SQL Server

Flat files

Microsoft Office Access

Microsoft Office Excel
BackupBackup
The SQL Server backup and restore component provides an essential
safeguard for protecting critical data stored in your SQL Server
databases. To minimize the risk of catastrophic data loss, you need
to back up your databases to preserve modifications to your data on
a regular basis. A well-planned backup and restore strategy helps
protect databases against data loss caused by a variety of failures.
Backup – Types of backupBackup – Types of backup

Copy-only backup - A special-use backup that is independent of the
regular sequence of SQL Server backups.

Data backup - A backup of data in a complete database (a database
backup), a partial database (a partial backup), or a set of data files
or file groups (a file backup).

Database backup - A backup of a database. Full database backups
represent the whole database at the time the backup finished.
Differential database backups contain only changes made to the
database since its most recent full database backup.

Full backup - A data backup that contains all the data in a specific
database or set of file groups or files, and also enough log to allow
for recovering that data.

Log backup - A backup of transaction logs that includes all log
records that were not backed up in a previous log backup. (full
recovery model)
Backup – Types of backupBackup – Types of backup

Differential backup - A data backup that is based on the latest full
backup of a complete or partial database or a set of data files or file
groups (the differential base) and that contains only the data extents
that have changed since the differential base.
A differential partial backup records only the data extents that have
changed in the file groups since the previous partial backup, known
as the base for the differential.

File backup - A backup of one or more database files or file groups

Partial backup - Contains data from only some of the file groups in
a database, including the data in the primary file group, every
read/write file group, and any optionally-specified read-only files.
Backup – Types of backup – Copy-only backupBackup – Types of backup – Copy-only backup
A copy-only backup is a SQL Server backup that is independent of the sequence
of conventional SQL Server backups. Usually, taking a backup changes the
database and affects how later backups are restored. However, occasionally, it
is useful to take a backup for a special purpose without affecting the overall
backup and restore procedures for the database.
Copy-only backups serve this purpose.
The types of copy-only backups are as follows:

Copy-only full backups (all recovery models) - A copy-only backup cannot
serve as a differential base or differential backup and does not affect the
differential base. Restoring a copy-only full backup is the same as restoring
any other full backup.

Copy-only log backups (full recovery model and bulk-logged recovery model
only) - A copy-only log backup preserves the existing log archive point and,
therefore, does not affect the sequencing of regular log backups. Copy-only
log backups are typically unnecessary.
Backup – Types of backup – Copy-only backupBackup – Types of backup – Copy-only backup

For a copy-only full backup:
BACKUP DATABASE
database_name TO
<backup_device> … WITH
COPY_ONLY …

For a copy-only log backup:
BACKUP LOG database_name
TO <backup_device> …
WITH COPY_ONLY …
The essential Transact-SQL syntax is as follows:
Backup – Types of backup – Full BackupBackup – Types of backup – Full Backup
You can re-create a whole database in one step by restoring the
database from a full database backup to any location. Enough of the
transaction log is included in the backup to let you recover the
database to the time when the backup finished. The restored
database matches the state of the original database when the
database backup finished, minus any uncommitted transactions.
Under the full recovery model, you should then restore all
subsequent transaction log backups. When the database is
recovered, uncommitted transactions are rolled back.
Backup – Types of backup – Full Backup - exampleBackup – Types of backup – Full Backup - example
USE master;
ALTER DATABASE AdventureWorks2012 SET RECOVERY
FULL;
GO
-- Back up the AdventureWorks2012 database to new media set
(backup set 1).
BACKUP DATABASE AdventureWorks2012
TO DISK =
'Z:SQLServerBackupsAdventureWorks2012FullRM.bak'
WITH FORMAT;
GO
--Create a routine log backup (backup set 2).
BACKUP LOG AdventureWorks2012 TO DISK =
'Z:SQLServerBackupsAdventureWorks2012FullRM.bak';
GO
Backup – Types of backup – Partial BackupBackup – Types of backup – Partial Backup
Partial backups are useful whenever you want to exclude read-only
file groups A partial backup resembles a full database backup, but a
partial backup does not contain all the file groups Instead, for a
read-write database, a partial backup contains the data in the
primary file group, every read-write file group, and, optionally, one
or more read-only files. A partial backup of a read-only database
contains only the primary file group
To create a partial backup
BACKUP(READ_WRITE_FILEGROUPS; FILEGROUP option, if
needed)
Information SourcesInformation Sources

http://www.w3schools.com/sql/

http://en.wikipedia.org/wiki/

http://stronymalowane.pl/sql/

http://www.tutorialspoint.com/sql/sql-transactions.htm

https://technet.microsoft.com/en-us/library/

http://www.techonthenet.com/sql_server/

http://courses.cs.washington.edu/courses/cse544/06sp/lectures/lecture-sql
-for most of tables in presentation

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Sql basics
Sql basicsSql basics
Sql basics
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
Introduction to (sql)
Introduction to (sql)Introduction to (sql)
Introduction to (sql)
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Sql
SqlSql
Sql
 
Create table
Create tableCreate table
Create table
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Ankit
AnkitAnkit
Ankit
 
Sql commands
Sql commandsSql commands
Sql commands
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Sql - Structured Query Language
Sql - Structured Query LanguageSql - Structured Query Language
Sql - Structured Query Language
 

Ähnlich wie PO WER - Piotr Mariat - Sql

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
Axmed Mo.
 

Ähnlich wie PO WER - Piotr Mariat - Sql (20)

Module02
Module02Module02
Module02
 
lovely
lovelylovely
lovely
 
12 SQL
12 SQL12 SQL
12 SQL
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
unit 1 ppt.pptx
unit 1 ppt.pptxunit 1 ppt.pptx
unit 1 ppt.pptx
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
SQL2.pptx
SQL2.pptxSQL2.pptx
SQL2.pptx
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Database Management Lab -SQL Queries
Database Management Lab -SQL Queries Database Management Lab -SQL Queries
Database Management Lab -SQL Queries
 
Introduction to SQL..pdf
Introduction to SQL..pdfIntroduction to SQL..pdf
Introduction to SQL..pdf
 
Adbms
AdbmsAdbms
Adbms
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome Measures
 
DBMS Part-3.pptx
DBMS Part-3.pptxDBMS Part-3.pptx
DBMS Part-3.pptx
 

Mehr von Zespół Szkół nr 26

Mehr von Zespół Szkół nr 26 (20)

Jak ugryźć ecvet
Jak ugryźć ecvetJak ugryźć ecvet
Jak ugryźć ecvet
 
Podsumowanie projektu po wer 2014
Podsumowanie projektu po wer 2014Podsumowanie projektu po wer 2014
Podsumowanie projektu po wer 2014
 
PO WER - Włodzimierz Sobociński - Prezentacja z praktyk 2015
PO WER - Włodzimierz Sobociński - Prezentacja z praktyk 2015PO WER - Włodzimierz Sobociński - Prezentacja z praktyk 2015
PO WER - Włodzimierz Sobociński - Prezentacja z praktyk 2015
 
PO WER Damian Kedzierski.Praktyki plymouth 2015
PO WER Damian Kedzierski.Praktyki plymouth 2015PO WER Damian Kedzierski.Praktyki plymouth 2015
PO WER Damian Kedzierski.Praktyki plymouth 2015
 
PO WER - Kamil Cichowski
PO WER - Kamil CichowskiPO WER - Kamil Cichowski
PO WER - Kamil Cichowski
 
PO WER - Jakub Ciupiński
PO WER  - Jakub CiupińskiPO WER  - Jakub Ciupiński
PO WER - Jakub Ciupiński
 
PO WER - Adrian Izbicki -praktyki plymouth
PO WER - Adrian Izbicki -praktyki plymouthPO WER - Adrian Izbicki -praktyki plymouth
PO WER - Adrian Izbicki -praktyki plymouth
 
PO WER Karolina Kaczmarska - praktyki w plymouth
PO WER Karolina Kaczmarska - praktyki w plymouthPO WER Karolina Kaczmarska - praktyki w plymouth
PO WER Karolina Kaczmarska - praktyki w plymouth
 
Akcja zakrętka - 2015 r
Akcja zakrętka - 2015 rAkcja zakrętka - 2015 r
Akcja zakrętka - 2015 r
 
Prezentacja na konferencję 6.06.2014
Prezentacja na konferencję 6.06.2014Prezentacja na konferencję 6.06.2014
Prezentacja na konferencję 6.06.2014
 
Zbigniew Matysiak
Zbigniew MatysiakZbigniew Matysiak
Zbigniew Matysiak
 
Patryk Zientara
Patryk ZientaraPatryk Zientara
Patryk Zientara
 
Kamil Reszka
Kamil ReszkaKamil Reszka
Kamil Reszka
 
Daniel Pikalski
Daniel PikalskiDaniel Pikalski
Daniel Pikalski
 
Cezary Słupek
Cezary SłupekCezary Słupek
Cezary Słupek
 
Paweł Krzepis
Paweł KrzepisPaweł Krzepis
Paweł Krzepis
 
Anna Wińska
Anna WińskaAnna Wińska
Anna Wińska
 
69 rocznica wyzwolenia obozów koncentracyjnych Mauthausen Gusen
69 rocznica wyzwolenia obozów koncentracyjnych Mauthausen Gusen69 rocznica wyzwolenia obozów koncentracyjnych Mauthausen Gusen
69 rocznica wyzwolenia obozów koncentracyjnych Mauthausen Gusen
 
Dulag 121
Dulag 121Dulag 121
Dulag 121
 
Nowy podławek nr 2
Nowy podławek nr 2Nowy podławek nr 2
Nowy podławek nr 2
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

PO WER - Piotr Mariat - Sql

  • 2. Introduction to MySQLIntroduction to MySQL The MySQL server is the meager of your database  It creates new database  It knows where the database are stored  It stores and retrieves information, guided by the request, or queries, that it receives To make a request that MySQL can understand, you need to build an SQL query and send it to the server
  • 3. MS SQL ServerMS SQL Server Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product whose primary function is to store and retrieve data as requested by other software applications, be it those on the same computer or those running on another computer across a network (including the Internet). There are at least a dozen different editions of Microsoft SQL Server aimed at different audiences and for workloads ranging from small single-machine applications to large Internet-facing applications with many concurrent users.
  • 4. Introduction to SQLIntroduction to SQL  SQL stands for Structured Query Language.  It is the most commonly used relational database language today.  SQL works with a variety of different fourth-generation (4GL) programming languages, such as Visual Basic.
  • 5. SQL is used forSQL is used for  Data Definition Language (DDL) Create/alter/delete tables and their attributes  Data Manipulation Language (DML) Query one or more tables Insert/delete/modify tuples in tables  Data Control Language(DCL) Authorizes users to access and manipulate data  Data Query Language(DQL)  Transaction Control Language(TCL)
  • 6. DMLDML The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete data:  INSERT adds rows (formally tuples) to an existing table  UPDATE modifies a set of existing table rows  DELETE removes existing rows from a table  MERGE is used to combine the data of multiple tables. It combines the INSERT and UPDATE elements
  • 7. DDLDDL The Data Definition Language (DDL) manages table and index structure. The most basic items of DDL are:  CREATE creates an object (a table, for example) in the database  ALTER modifies the structure of an existing object in various ways, for example, adding a column to an existing table or a constraint  TRUNCATE deletes all data from a table in a very fast way, deleting the data inside the table and not the table itself. It usually implies a subsequent COMMIT operation, i.e., it cannot be rolled back (data is not written to the logs for rollback later, unlike DELETE).  DROP deletes an object in the database, usually irretrievably, i.e., it cannot be rolled back
  • 8. SQL StandardsSQL Standards  SQL86 – first formalized standard  SQL89 - was just minor revision, adopted as FIPS 127-1  SQL92 - Major revision (ISO 9075), adopted as FIPS 127-2  SQL1999 - Added regular expression matching, recursive queries (e.g. transitive closure), triggers, support for procedural and control-of-flow statements, non-scalar types, and some object- oriented features (e.g. structured types). Support for embedding SQL in Java (SQL/OLB) and vice versa (SQL/JRT).  SQL2003 - Introduced XML-related features (SQL/XML), window functions, standardized sequences, and columns with auto- generated values (including identity-columns).
  • 9. SQL StandardsSQL Standards  SQL2006 - 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 enables 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  SQL2009 - Legalizes ORDER BY outside cursor definitions. Adds INSTEAD OF triggers. Adds the TRUNCATE statement  SQL2011 - One of the main new features is improved support for temporal databases. Language enhancements for temporal data definition and manipulation
  • 10. SQL Basic commandsSQL Basic commands  SELECT  DISTINCT  WHERE  AND  OR  IN  BETWEEN  WILDCARD  LIKE  ORDER BY  GROUP BY  HAVING  ALIAS  AS  SELECT UNIQUE  INSERT INTO  INSERT INTO SELECTED  UPDATE  DELETE FROM
  • 11. SQL RequirementsSQL Requirements  SQL Must be embedded in a programming language, or used with a 4GL like VB  SQL is a free form language so there is no limit to the the number of words per line or fixed line break.  The case of the SQL words doesn't matter, select is same as SELECT .On the other hand case of the table names, column names, and other variable information does matter if you use Linux or Unix, so they need to be exact match. Windows however isn't so picky so case doesn't matter for it
  • 12. SQL RequirementsSQL Requirements Row is named LastName and table is named Member Linux and Unix example SELECT LastName FROM Member – Correct SELECT lastname FROM member - Incorrect Windows example SELECT LastName FROM Member SELECT lastname FROM member Both are Correct *Commands are bold and in uppercase for your comfort
  • 13. SQL is a Relational DatabaseSQL is a Relational Database A Fully Relational Database Management System must:  Represent all info in database as tablesRepresent all info in database as tables  Keep logical representation of data independent from its physical storageKeep logical representation of data independent from its physical storage characteristicscharacteristics  Use one high-level language for structuring, querying, and changing info inUse one high-level language for structuring, querying, and changing info in the databasethe database  Support the main relational operationsSupport the main relational operations  Support alternate ways of looking at data in tablesSupport alternate ways of looking at data in tables  Provide a method for differentiating between unknown values and nulls (zeroProvide a method for differentiating between unknown values and nulls (zero or blank)or blank)  Support Mechanisms for integrity, authorization, transactions, and recoverySupport Mechanisms for integrity, authorization, transactions, and recovery
  • 14. Data TypeData Type  CHARACTER(n) - Character string. Fixed-length n  VARCHAR(n) or CHARACTER VARYING(n) - Character string. Variable length. Maximum length n  BINARY(n) - Binary string. Fixed-length n  BOOLEAN - Stores TRUE or FALSE values  VARBINARY(n) or BINARY VARYING(n) - Binary string. Variable length. Maximum length n  INTEGER(p) - Integer numerical (no decimal). Precision p  SMALLINT - Integer numerical (no decimal). Precision 5  INTEGER - Integer numerical (no decimal). Precision 10  BIGINT - Integer numerical (no decimal). Precision 19  DECIMAL(p,s) - Exact numerical, precision p, scale s. Example: decimal(5,2) is a number that has 3 digits before the decimal and 2 digits after the decimal
  • 15. Data TypeData Type  NUMERIC(p,s) - Exact numerical, precision p, scale s. (Same as DECIMAL)  FLOAT(p) - Approximate numerical, mantissa precision p. A floating number in base 10 exponential notation. The size argument for this type consists of a single number specifying the minimum precision  REAL - Approximate numerical, mantissa precision 7  FLOAT - Approximate numerical, mantissa precision 16  DOUBLE PRECISION - Approximate numerical, mantissa precision 16  DATE - Stores year, month, and day values  TIME - Stores hour, minute, and second values  TIMESTAMP - Stores year, month, day, hour, minute, and second values
  • 16. Data TypeData Type  INTERVAL - Composed of a number of integer fields, representing a period of time, depending on the type of interval  ARRAY - A set-length and ordered collection of elements  MULTISET - A variable-length and underscored collection of elements  XML - Stores XML data
  • 17. Data Types in shortData Types in short In short:  Characters: CHAR(20), VARCHAR(50)  Numbers: INT, BIGINT, SMALLINT, FLOAT  Others: MONEY, DATETIME, … Every attribute must have an atomic type, hence tables are flat
  • 18. Data HierarchyData Hierarchy 1) user-defined data types (highest) 2) sql_variant 3) Xml 4) Datetimeoffset 5) Datetime2 6) Datetime 7) Smalldatetime 8) Date 9) Time 10)Float 11)Real 12)Decimal 13)Money 1) Smallmoney 2) Bigini 3) Ini 4) Smallini 5) Tinyini 6) Bit 7) Ntext 8) Text 9) Image 10)Timestamp 11)Uniqueidentifier 25)nvarchar (including nvarchar(max) ) 26)Nchar 27)varchar (including varchar(max) ) 28)Char 29)varbinary (including varbinary(max) ) 30)binary (lowest) SQL Server uses the following precedence order for data types:
  • 19. DesignDesign  SQL represents all information in the form of tables  Supports three relational operations: SELECTION means which rows are to be returned. PROJECTION means choosing which columns (or expressions) the query shall return. Example SELECT a, b, c FROM foobar WHERE x=3 “a,b,c” is PROJECTION part, “x=3” is SELECTION part
  • 20. DesignDesign JOIN clause is used to COMBINE rows from two or more tables, based on a common field between them. There is 4 different types of JOIN command  INNER JOIN: Returns all rows when there is at least one match in BOTH tables  LEFT JOIN: Return all rows from the left table, and the matched rows from the right table  RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table  FULL JOIN: Return all rows when there is a match in ONE of the tables
  • 21. Creating and deleting a database and tables in itCreating and deleting a database and tables in it Database  CREATE DATABASE database_name - command for creation  DROP DATABASE database_name – delete command Table  CREATE TABLE table_name (column_name1 data_type(size),column_name2 data_type(size),....); - universal command for table creation  DROP INDEX index_name ON table_name – delete command for MS Access  DROP INDEX table_name.index_name – delete command for MySQL server  Etc.
  • 22. Altering tablesAltering tables With ALTER TABLE command you can:  ALTER TABLE table_name ADD column_name datatype – add a column  ALTER TABLE table_name DROP COLUMN column_name - deleate them  ALTER TABLE table_name ALTER COLUMN column_name datatype – alter there data type (command for SQL server and MS Access)  ALTER TABLE table_name MODIFY COLUMN column_name datatype - alter there data type (command for MySQL and Oracle before version 10G, versions after dont need COLUMN)
  • 23. SchemaSchema  A schema is a collection of database objects (as far as this hour is concerned—tables) associated with one particular database username. This username is called the schema owner, or the owner of the related group of objects. You may have one or multiple schemas in a database. Basically, any user who creates an object has just created his or her own schema. So, based on a user's privileges within the database, the user has control over objects that are created, manipulated, and deleted. A schema can consist of a single table and has no limits to the number of objects that it may contain, unless restricted by a specific database implementation.
  • 24. Schema creationSchema creation CREATE SCHEMA schema_name_clause [ <schema_element> [ ...n ] ] <schema_name_clause> ::= {schema_name | AUTHORIZATION owner_name | schema_name AUTHORIZATION owner_name } <schema_element> ::= { table_definition | view_definition | grant_statement | revoke_statement | deny_statement } Arguments  schema_name - Is the name by which the schema is identified within the database.  AUTHORIZATION owner_name - Specifies the name of the database-level principal that will own the schema. This principal may own other schemas, and may not use the current schema as its default schema
  • 25. Schema creationSchema creation  table_definition - Specifies a CREATE TABLE statement that creates a table within the schema. The principal executing this statement must have CREATE TABLE permission on the current database.  view_definition - Specifies a CREATE VIEW statement that creates a view within the schema. The principal executing this statement must have CREATE VIEW permission on the current database.  grant_statement - Specifies a GRANT statement that grants permissions on any securable except the new schema.  revoke_statement - Specifies a REVOKE statement that revokes permissions on any securable except the new schema.  deny_statement - Specifies a DENY statement that denies permissions on any securable except the new schema.
  • 26. SQL TablesSQL Tables PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Tuples or rows Attribute names Product Table name
  • 27. Tables ExplainedTables Explained  The schema of a table is the table name and its attributes: Product(PName, Price, Category, Manfacturer)  A key is an attribute whose values are unique, I underlined a key Product(PName, Price, Category, Manfacturer)  A tuple = a record Restriction: all attributes are of atomic type  A table = a set of tuples
  • 28. Adding data to tableAdding data to table It is possible to write the INSERT INTO statement in two forms.  The first form does not specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1,value2,value3,...);  The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
  • 29. Updating recordsUpdating records The UPDATE statement is used to update existing records in a table. UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value;
  • 30. Coping data from one table to anotherCoping data from one table to another The INSERT INTO SELECT statement selects data from one table and inserts it into an existing table. Any existing rows in the target table are unaffected.  We can copy all columns from one table to another, existing table INSERT INTO table2 SELECT * FROM table1;  Or we can copy only the columns we want to into another, existing table: INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
  • 31. Deleting recordsDeleting records The DELETE statement is used to delete rows in a table. DELETE FROM table_name WHERE some_column=some_value;
  • 32. Grouping data The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name;
  • 33. Grouping dataGrouping data Ties are broken by the second attribute on the ORDER BY list, etc. Ordering is ascending, unless you specify the DESC keyword. SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname SELECT pname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname
  • 34. VariableVariable In SQL Server (Transact-SQL), a variable allows a programmer to store data temporarily during the execution of code. The syntax to declare variables in SQL Server using the DECLARE statement is: DECLARE @variable_name datatype [ = initial_value ], @variable_name datatype [ = initial_value ], ...; Parameters or Arguments variable_name -The name to assign to the variable. Datatype - The datatype to assign to the variable. initial_value - Optional. It is the value initially assigned to the variable when it is declared.
  • 35. ConditionsConditions Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces another Transact-SQL statement that is executed when the IF condition is not satisfied: the Boolean expression returns FALSE. IF Boolean_expression { sql_statement | statement_block } [ ELSE { sql_statement | statement_block } ] An IF...ELSE construct can be used in batches, in stored procedures, and in ad hoc queries. When this construct is used in a stored procedure, it is frequently used to test for the existence of some parameter. IF tests can be nested after another IF or following an ELSE. The limit to the number of nested levels depends on available memory.
  • 36. SQL QuerySQL Query  Most Basic form: SELECT <attributes> FROM <one or more relations> WHERE <conditions>
  • 37. Simple SQL Query ExampleSimple SQL Query Example PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ SELECT * FROM Product WHERE category=‘Gadgets’ Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks“selection”
  • 38. Simple SQL Query ExampleSimple SQL Query Example PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Product PName Price Manufacturer SingleTouch $149.99 Canon MultiTouch $203.99 Hitachi “selection” and “projection”
  • 39. Combining QueriesCombining Queries The UNION operator is used to combine the result-set of two or more SELECT statements. Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. The column names in the result-set of a UNION are usually equal to the column names in the first SELECT statement in the UNION.
  • 40. Combining QueriesCombining Queries SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; The UNION operator selects only distinct values by default. To allow duplicate values, use the ALL keyword with UNION.
  • 41. NotationNotation Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100
  • 42. Case sensitivityCase sensitivity  Case insensitive: Same: SELECT Select select Same: Product product Different: ‘Seattle’ ‘seattle’  Constants: ‘abc’ - yes “abc” - no
  • 43. Eliminating DuplicatesEliminating Duplicates SELECT DISTINCT category FROM Product SELECT DISTINCT category FROM Product Compare to: SELECT category FROM Product SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 44. JoinsJoins Product (pname, price, category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
  • 45. JoinsJoins PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan PName Price SingleTouch $149.99 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200 SELECT PName, Price FROM Product, Company WHERE Manufacturer=CName AND Country=‘Japan’ AND Price <= 200
  • 46. Cross joinCross join PlayerName DepartmentId Scores Jason 1 3000 Irene 1 1500 Jane 2 1000 David 2 2500 Paul 3 2000 James 3 2000 DepartmentId DepartmentName 1 IT 2 Marketing 3 HR SELECT * FROM GameScores CROSS JOIN Departments SELECT * FROM GameScores CROSS JOIN Departments Playername Departamentid Scores Departamenti d Departamentname Jason 1 3000 1 IT Irene 1 1500 1 IT Jane 2 1000 2 IT David 2 2500 2 IT Paul 3 2000 3 IT James 3 2000 3 IT Jason 1 3000 2 Marketing ... ... ... ... ... Departments Gamescores
  • 47. Multiple joinsMultiple joins Although each join specification joins only two tables, FROM clauses can contain multiple join specifications. This allows many tables to be joined for a single query. SELECT TableA.*, TableB.*, TableC.*, TableD.* FROM TableA JOIN TableB ON TableB.aID = TableA.aID JOIN TableC ON TableC.cID = TableB.cID JOIN TableD ON TableD.dID = TableA.dID WHERE DATE(TableC.date)=date(now())
  • 48. ConstraintsConstraints SQL constraints are used to specify rules for the data in a table. If there is any violation between the constraint and the data action, the action is aborted by the constraint. Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement).
  • 49. ConstraintsConstraints In SQL, we have the following constraints:  NOT NULL - Indicates that a column cannot store NULL value  UNIQUE - Ensures that each row for a column must have a unique value  PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly  FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table  CHECK - Ensures that the value in a column meets a specific condition  DEFAULT - Specifies a default value when specified none for this column
  • 50. Constraints – NOT NULLConstraints – NOT NULL The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
  • 51. Constraints - UNIQUEConstraints - UNIQUE The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
  • 52. Constraints - PRIMARY KEYConstraints - PRIMARY KEY The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain UNIQUE values. A primary key column cannot contain NULL values. Most tables should have a primary key, and each table can have only ONE primary key.
  • 53. Constraints - PRIMARY KEYConstraints - PRIMARY KEY  MySQL CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) )  SQL Server / Oracle / MS Access CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
  • 54. Constraints - FOREIGN KEYConstraints - FOREIGN KEY  MySQL CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )  SQL Server / Oracle / MS Access CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) ) A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
  • 55. Constraints - PRIMARY KEY and FOREIGN KEYConstraints - PRIMARY KEY and FOREIGN KEY PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company CName StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan Primary Key Foreign key
  • 56. Constraints - CHECKConstraints - CHECK The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ).
  • 57. Constraints - DEFAULTConstraints - DEFAULT The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT “name or data type” )
  • 58. Meaning (Semantics) of SQL QueriesMeaning (Semantics) of SQL Queries SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions SELECT a1, a2, …, ak FROM R1 AS x1, R2 AS x2, …, Rn AS xn WHERE Conditions Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer ∪ {(a1,…,ak)} return Answer Answer = {} for x1 in R1 do for x2 in R2 do ….. for xn in Rn do if Conditions then Answer = Answer ∪ {(a1,…,ak)} return Answer
  • 59. Subqueries Returning RelationsSubqueries Returning Relations Company(name, city) Product(pname, maker) Purchase(id, product, buyer) Return cities where one can find companies that manufacture products bought by Joe Blow SELECT Company.city FROM Company WHERE Company.name IN SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘); SELECT Company.city FROM Company WHERE Company.name IN SELECT Product.maker FROM Purchase , Product WHERE Product.pname=Purchase.product AND Purchase .buyer = ‘Joe Blow‘);
  • 60. IndexIndex An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
  • 61. Index - commandsIndex - commands  Creates an index on a table. Duplicate values are allowed: CREATE INDEX index_name ON table_name (column_name)  Creates a unique index on a table. Duplicate values are not allowed: CREATE UNIQUE INDEX index_name ON table_name (column_name)
  • 62. TransactionsTransactions A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.
  • 63. Transactions – proprietiesTransactions – proprieties Transactions have the following four standard properties, usually referred to by the acronym ACID:  Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.  Consistency: ensures that the database properly changes states upon a successfully committed transaction.  Isolation: enables transactions to operate independently of and transparent to each other.  Durability: ensures that the result or effect of a committed transaction persists in case of a system failure.
  • 64. Transactions - commandsTransactions - commands There are following commands used to control transactions:  COMMIT: to save the changes.  ROLLBACK: to rollback the changes.  SAVEPOINT: creates points within groups of transactions in which to ROLLBACK, is deleted by RELEASE SAVEPOINT  SET TRANSACTION: Places a name on a transaction. Transactional control commands are only used with the DML commands INSERT, UPDATE and DELETE only. They can not be used while creating tables or dropping them because these operations are automatically commited in the database.
  • 65. Transactions – commands - COMMITTransactions – commands - COMMIT The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command. The syntax for COMMIT command is as follows: COMMIT;
  • 66. Transactions – commands - ROLLBACKTransactions – commands - ROLLBACK The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. The ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. The syntax for ROLLBACK command is as follows: ROLLBACK;
  • 67. Transactions – commands - SAVEPOINTTransactions – commands - SAVEPOINT A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction. The syntax for SAVEPOINT command is as follows: SAVEPOINT SAVEPOINT_NAME; This command serves only in the creation of a SAVEPOINT among transactional statements. The ROLLBACK command is used to undo a group of transactions. The syntax for rolling back to a SAVEPOINT is as follows: ROLLBACK TO SAVEPOINT_NAME;
  • 68. Transactions – commands – RELEASE SAVEPOINTTransactions – commands – RELEASE SAVEPOINT The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created. The syntax for RELEASE SAVEPOINT is as follows: RELEASE SAVEPOINT SAVEPOINT_NAME; Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the SAVEPOINT.
  • 69. Transactions – commands – SET TRANSACTIONTransactions – commands – SET TRANSACTION The SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows. For example, you can specify a transaction to be read only, or read write. The syntax for SET TRANSACTION is as follows: SET TRANSACTION [ READ WRITE | READ ONLY ];
  • 70. Optimistic and Pessimistic ConcurrencyOptimistic and Pessimistic Concurrency Optimistic Concurrency Optimistic concurrency control works on the assumption that resource conflicts between multiple users are unlikely (but not impossible), and allows transactions to execute without locking any resources. Only when attempting to change data are resources checked to determine if any conflicts have occurred. If a conflict occurs, the application must read the data and attempt the change again. Pessimistic Concurrency Pessimistic concurrency control locks resources as they are required, for the duration of a transaction. Unless deadlocks occur, a transaction is assured of successful completion.
  • 71. ViewView In database theory, a view is the result set of a stored query on the data, which the database users can query just as they would in a persistent database collection object. This pre-established query command is kept in the database dictionary. Unlike ordinary base tables in a relational database, a view does not form part of the physical schema: as a result set, it is a virtual table computed or collated dynamically from data in the database when access to that view is requested. Changes applied to the data in a relevant underlying table are reflected in the data shown in subsequent invocations of the view. In some NoSQL databases, views are the only way to query data.
  • 72. View - advantagesView - advantages Views can provide advantages over tables:  Views can represent a subset of the data contained in a table. Consequently, a view can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table.  Views can join and simplify multiple tables into a single virtual table.  Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents the calculated results as part of the data.  Views can hide the complexity of data. For example, a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table.  Views take very little space to store; the database contains only the definition of a view, not a copy of all the data that it presents.  Depending on the SQL engine used, views can provide extra security.
  • 73. View - commandsView - commands  Creation command CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition  To update CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No
  • 74. CTECTE A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query. Using a CTE offers the advantages of improved readability and ease in maintenance of complex queries. The query can be divided into separate, simple, logical building blocks. These simple blocks can then be used to build more complex, interim CTEs until the final result set is generated. CTEs can be defined in user-defined routines, such as functions, stored procedures, triggers, or views.
  • 75. CTECTE A CTE is made up of an expression name representing the CTE, an optional column list, and a query defining the CTE. After a CTE is defined, it can be referenced like a table or view can in a SELECT, INSERT, UPDATE, or DELETE statement. A CTE can also be used in a CREATE VIEW statement as part of its defining SELECT statement. The basic syntax structure for a CTE is: WITH expression_name [ ( column_name [,...n] ) ] AS ( CTE_query_definition ) The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition. The statement to run the CTE is: SELECT <column_list> FROM expression_name;
  • 76. TriggersTriggers A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or update of data. It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action no the table that they are assigned to. There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them. Basically, triggers are classified into two main types:  AFTER Triggers  INSTEAD OF Triggers
  • 77. AFTER triggersAFTER triggers These triggers run after an insert, update or delete on a table. They are not supported for views. AFTER Triggers can be classified further into three types as:  AFTER INSERT Trigger.  AFTER UPDATE Trigger.  AFTER DELETE Trigger.
  • 78. AFTER triggers - exampleAFTER triggers - example AFTER INSERT CREATE TRIGGER TRG_InsertSyncEmp ON dbo.EMPLOYEE AFTER INSERT AS BEGIN INSERT INTO EMPLOYEE_BACKUP SELECT * FROM INSERTED END GO AFTER UPDATE CREATE TRIGGER Departments_Update AFTER UPDATE OF budget ON Departments WHEN (CURRENT_TIME > '17:00:00') SELECT MAX(budget) / 0 FROM Departments;
  • 79. INSTEAD OF TriggersINSTEAD OF Triggers These can be used as an interceptor for anything that anyone tried to do on our table or view. If you define an Instead Of trigger on a table for the DELETE operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the trigger) INSTEAD OF TRIGGERS can be classified further into three types as:  INSTEAD OF INSERT Trigger.  INSTEAD OF UPDATE Trigger.  INSTEAD OF DELETE Trigger.
  • 80. INSTEAD OF Triggers - exampleINSTEAD OF Triggers - example INSTEAD OF INSERT CREATE TRIGGER InsteadTrigger on InsteadView INSTEAD OF INSERT AS BEGIN --Build an INSERT statement ignoring inserted.ID and --inserted.ComputedCol. INSERT INTO BaseTable SELECT Color, Material FROM inserted END; GO INSTEAD OF DELETE CREATE TRIGGER audit_Table_Deletes ON dbo.mytesting INSTEAD OF DELETE AS IF @@rowcount = 0 return; INSERT INTO dbo.myaudit (test_id, sometext) SELECT d.test_id, t.sometext FROM deleted d JOIN dbo.mytesting t ON t.test_id = d.test_id
  • 81. Importing dataImporting data The SQL Server Import and Export Wizard offers the simplest method to create a Integration Services package that copies data from a source to a destination. The SQL Server Import and Export Wizard can copy data to and from any data source for which a managed .NET Framework data provider or a native OLE DB provider is available. The list of available providers includes the following data sources:  SQL Server  Flat files  Microsoft Office Access  Microsoft Office Excel
  • 82. BackupBackup The SQL Server backup and restore component provides an essential safeguard for protecting critical data stored in your SQL Server databases. To minimize the risk of catastrophic data loss, you need to back up your databases to preserve modifications to your data on a regular basis. A well-planned backup and restore strategy helps protect databases against data loss caused by a variety of failures.
  • 83. Backup – Types of backupBackup – Types of backup  Copy-only backup - A special-use backup that is independent of the regular sequence of SQL Server backups.  Data backup - A backup of data in a complete database (a database backup), a partial database (a partial backup), or a set of data files or file groups (a file backup).  Database backup - A backup of a database. Full database backups represent the whole database at the time the backup finished. Differential database backups contain only changes made to the database since its most recent full database backup.  Full backup - A data backup that contains all the data in a specific database or set of file groups or files, and also enough log to allow for recovering that data.  Log backup - A backup of transaction logs that includes all log records that were not backed up in a previous log backup. (full recovery model)
  • 84. Backup – Types of backupBackup – Types of backup  Differential backup - A data backup that is based on the latest full backup of a complete or partial database or a set of data files or file groups (the differential base) and that contains only the data extents that have changed since the differential base. A differential partial backup records only the data extents that have changed in the file groups since the previous partial backup, known as the base for the differential.  File backup - A backup of one or more database files or file groups  Partial backup - Contains data from only some of the file groups in a database, including the data in the primary file group, every read/write file group, and any optionally-specified read-only files.
  • 85. Backup – Types of backup – Copy-only backupBackup – Types of backup – Copy-only backup A copy-only backup is a SQL Server backup that is independent of the sequence of conventional SQL Server backups. Usually, taking a backup changes the database and affects how later backups are restored. However, occasionally, it is useful to take a backup for a special purpose without affecting the overall backup and restore procedures for the database. Copy-only backups serve this purpose. The types of copy-only backups are as follows:  Copy-only full backups (all recovery models) - A copy-only backup cannot serve as a differential base or differential backup and does not affect the differential base. Restoring a copy-only full backup is the same as restoring any other full backup.  Copy-only log backups (full recovery model and bulk-logged recovery model only) - A copy-only log backup preserves the existing log archive point and, therefore, does not affect the sequencing of regular log backups. Copy-only log backups are typically unnecessary.
  • 86. Backup – Types of backup – Copy-only backupBackup – Types of backup – Copy-only backup  For a copy-only full backup: BACKUP DATABASE database_name TO <backup_device> … WITH COPY_ONLY …  For a copy-only log backup: BACKUP LOG database_name TO <backup_device> … WITH COPY_ONLY … The essential Transact-SQL syntax is as follows:
  • 87. Backup – Types of backup – Full BackupBackup – Types of backup – Full Backup You can re-create a whole database in one step by restoring the database from a full database backup to any location. Enough of the transaction log is included in the backup to let you recover the database to the time when the backup finished. The restored database matches the state of the original database when the database backup finished, minus any uncommitted transactions. Under the full recovery model, you should then restore all subsequent transaction log backups. When the database is recovered, uncommitted transactions are rolled back.
  • 88. Backup – Types of backup – Full Backup - exampleBackup – Types of backup – Full Backup - example USE master; ALTER DATABASE AdventureWorks2012 SET RECOVERY FULL; GO -- Back up the AdventureWorks2012 database to new media set (backup set 1). BACKUP DATABASE AdventureWorks2012 TO DISK = 'Z:SQLServerBackupsAdventureWorks2012FullRM.bak' WITH FORMAT; GO --Create a routine log backup (backup set 2). BACKUP LOG AdventureWorks2012 TO DISK = 'Z:SQLServerBackupsAdventureWorks2012FullRM.bak'; GO
  • 89. Backup – Types of backup – Partial BackupBackup – Types of backup – Partial Backup Partial backups are useful whenever you want to exclude read-only file groups A partial backup resembles a full database backup, but a partial backup does not contain all the file groups Instead, for a read-write database, a partial backup contains the data in the primary file group, every read-write file group, and, optionally, one or more read-only files. A partial backup of a read-only database contains only the primary file group To create a partial backup BACKUP(READ_WRITE_FILEGROUPS; FILEGROUP option, if needed)