sql practise for beginners

Post on 21-Oct-2014

303 Views

Category:

Education

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

DatabasesandSQL – Structured Query Language

Совокупность данных из набора двумерных таблиц:

Реляционная модель

- Огромные объемы данных- Огромное число пользователей- Гибкая, не ограниченная схемой структура БД.- NoSQL используют: Facebook, eBay

NoSQL БД

Помогает избавиться от избыточности в отношениях и оптимизировать работу БД

Нормализация

Ключ – это набор столбцов таблицы, которые уникально определяют строку.Суррогатный ключ – уникальный ключ искусственного происхождения (Например ID или просто порядковый номер)

Ключ

Нормализация – подразумевает приведение БД к одной из НФВсего их 6Обычно используются первых 3

Нормальные формы НФ

Каждая строка должна хранить одно-единственное значение и не являться списком. Атрибут должен быть атомарным.

1-я НФ (1НФ)

- Устранение избыточности данных- Использование атомарных(не составных)

ключей

2НФ

Факты, хранимые в таблицах должны зависеть только от ключа

3НФ

Команды состоят из: - имен операций и функций - имен таблиц и их стобцов - зарезервированных ключевых слов и

спец.символов - логических и арифметических выражений.

Команды SQL

SELECT CustomerName, CityFROM Customers;orSELECT * FROM Customers;

SELECT Statement

DISTINCT - In a table, a column may contain many duplicate values.The DISTINCT keyword can be used to return only distinct (different) values.

SELECT DISTINCT City FROM Customers;

SELECT DISTINCT

The WHERE clause is used to extract only those records that fulfill a specified criterion

SELECT * FROM CustomersWHERE Country='Mexico';

SQL WHERE Clause

The AND operator displays a record if both the first condition AND the second are true.

The OR operator displays a record if either the first condition OR the second condition is true.

SELECT * FROM CustomersWHERE Country='Germany'AND City='Berlin';

SQL AND & OR operators

SELECT * FROM CustomersWHERE City='Berlin'OR City='München';

SELECT * FROM CustomersWHERE Country='Germany'AND (City='Berlin' OR City='München');

SQL AND & OR operators

The ORDER BY keyword is used to sort the result-set by one or more columns, it’s ascending by default. If you want descending order use DESC keyword.

SELECT * FROM CustomersORDER BY Country DESC;

ORDERED BY Syntax

The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');

INSERT INTO Statement

The UPDATE statement is used to update existing records in a table

UPDATE CustomersSET ContactName='Alfred Schmidt', City='Hamburg'WHERE CustomerName='Alfreds Futterkiste';

Be careful when updating records. If we had omitted the WHERE clause all rows would be updated!

SQL UPDATE statement

The DELETE statement is used to delete rows in a table:DELETE FROM CustomersWHERE CustomerName='Alfreds Fkiste';Or

DELETE FROM Customers;

All rows will be deleted!

SQL DELETE statement

The LIKE operator is used to search for a specified pattern in a column:SELECT * FROM CustomersWHERE City LIKE 's%';OrSELECT * FROM CustomersWHERE Country(NOT) LIKE '%land%';All customers with a Country containing the pattern "land"

SQL LIKE operator

SQL wildcard characters are used with the SQL LIKE operator:%-Заменяет любое кол-во симоволов_ - Заменяет один символ[abc] – Диапазон символов[!abc] – Исключает диапазон символов

SELECT * FROM CustomersWHERE City LIKE 'ber%';

SQL Wildacard

SELECT * FROM CustomersWHERE City LIKE '%es%';

SELECT * FROM CustomersWHERE City LIKE '_erlin';

SELECT * FROM CustomersWHERE City LIKE '[bsp]%';

SQL Wildcard

The BETWEEN operator selects values within a range. The values can be numbers, text, or dates.

SELECT * FROM ProductsWHERE Price BETWEEN 10 AND 20; Or

SELECT * FROM ProductsWHERE ProductName(NOT) BETWEEN 'C' AND 'M';

SQL BETWEEN operator

SQL aliases are used to give a database table, or a column in a table, a temporary name.SELECT CustomerName AS Cust, ContactName AS SomebodyFROM Customers;

SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS AddressFROM Customers; - combine four columns

SQL Aliases

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where exists connection between them

SQL JOIN

SQL JOIN

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDateFROM OrdersINNER JOIN CustomersON Orders.CustomerID=Customers.CustomerID;

SQL JOIN

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

If there are rows in the "Customers" table that do not have matches in "Orders", these customers will NOT be listed.

Type of JOINs

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2).

The LEFT JOIN keyword returns all the rows from the left table (Customers), even if there are no matches in the right table (Orders).

Type of JOINs

The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).

Type of JOINs

The SQL UNION operator combines the result of two or more SELECT statements.

SELECT City FROM CustomersUNIONSELECT City FROM SuppliersORDER BY City;

SQL UNION operator

The SELECT INTO statement selects data from one table and inserts it into a new table.

SELECT *INTO CustomersBackup2013FROM Customers;WHERE Country='Germany';

SQL SELECT INTO

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.

INSERT INTO Customers (CustomerName, Country)SELECT SupplierName, Country FROM Suppliers;

SQL INSERT INTO

We want to create a table called "Persons" that contains five columns:

CREATE TABLE Persons(PersonID int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255) );

SQL CREATE TABLE

SQL constraints are used to specify rules for the data in a table. NOT NULL - Indicates that a column cannot

accept NULL values

CREATE TABLE PersonsNotNull(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255));

SQL Constraints

UNIQUE - Ensures that each row for a column must have a unique value:

CREATE TABLE Persons(P_Id int NOT NULL UNIQUE,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255));

SQL Constraints

PRIMARY KEY - Ensures that a column have an unique identity which helps to find a record in a table more easily and quickly.

CREATE TABLE Persons(P_Id int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),City varchar(255));

SQL Constraints

FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table

CREATE TABLE Orders(O_Id int NOT NULL PRIMARY KEY,OrderNo int NOT NULL,P_Id int FOREIGN KEY REFERENCES Persons(P_Id));

SQL Constraints

CHECK - Ensures that the value in a column meets a specific condition

CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes'));

SQL Constraints

DEFAULT - is used to insert a default value into a column.

CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255) DEFAULT 'Sandnes');

SQL Constraints

Tables and databases can easily be deleted/removed with the DROP statement.DROP TABLE table_name;DROP DATABASE database_name;

Only delete the data inside the table, and not the table itself:TRUNCATE TABLE table_name;

SQL DROP operator

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.ALTER TABLE PersonsALTER COLUMN DateOfBirth year(data type);

ALTER TABLE PersonsDROP COLUMN DateOfBirth;

ALTER TABLE Syntax

Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.

CREATE TABLE Persons(ID int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),PRIMARY KEY (ID));

AUTO INCREMENT

In SQL, a view is a virtual table based on the result-set of an SQL statement.CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition;

DROP VIEW view_name;

SQL CREATE VIEW

DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS SMALLDATETIME - format: YYYY-MM-DD

HH:MM:SS TIMESTAMP - format: a unique number

SQL Type of dates

GETDATE() Returns the current date and time

DATEPART() Returns a single part of a date/time

DATEADD() Adds or subtracts a specified time interval from a date

DATEDIFF() Returns the time between two dates

CONVERT() Displays date/time data in different formats

Date Function

NULL values represent missing unknown data

SELECT LastName,FirstName,Address FROM PersonsWHERE Address IS(NOT) NULL;

SQL NULL Values

Data type Access SQLServer Oracle MySQL PostgreSQL

boolean Yes/No Bit Byte N/A Boolean

integerNumber (integer)

Int NumberIntInteger

IntInteger

floatNumber (single)

FloatReal

Number Float Numeric

currency Currency Money N/A N/A Money

string (fixed) N/A Char Char Char Char

string (variable)

Text (<256)Memo (65k+)

VarcharVarcharVarchar2

Varchar Varchar

binary objectOLE Object Memo

Binary (fixed up to 8K)Varbinary (<8K)Image (<2GB)

LongRaw

BlobText

BinaryVarbinary

Data types

AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

SQL aggregate functions

Спасибо за внимание!

top related