Top Banner
Databases and SQL – Structured Query Language
50

Sql practise for beginners

Oct 21, 2014

Download

Education

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Sql practise for beginners

DatabasesandSQL – Structured Query Language

Page 2: Sql practise for beginners

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

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

Page 3: Sql practise for beginners

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

NoSQL БД

Page 4: Sql practise for beginners

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

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

Page 5: Sql practise for beginners

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

Ключ

Page 6: Sql practise for beginners

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

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

Page 7: Sql practise for beginners

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

1-я НФ (1НФ)

Page 8: Sql practise for beginners

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

ключей

2НФ

Page 9: Sql practise for beginners

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

3НФ

Page 10: Sql practise for beginners

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

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

Команды SQL

Page 11: Sql practise for beginners

SELECT CustomerName, CityFROM Customers;orSELECT * FROM Customers;

SELECT Statement

Page 12: Sql practise for beginners

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

Page 13: Sql practise for beginners

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

SELECT * FROM CustomersWHERE Country='Mexico';

SQL WHERE Clause

Page 14: Sql practise for beginners

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

Page 15: Sql practise for beginners

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

Page 16: Sql practise for beginners

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

Page 17: Sql practise for beginners

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

Page 18: Sql practise for beginners

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

Page 19: Sql practise for beginners

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

Page 20: Sql practise for beginners

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

Page 21: Sql practise for beginners

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

SELECT * FROM CustomersWHERE City LIKE 'ber%';

SQL Wildacard

Page 22: Sql practise for beginners

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

SELECT * FROM CustomersWHERE City LIKE '_erlin';

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

SQL Wildcard

Page 23: Sql practise for beginners

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

Page 24: Sql practise for beginners

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

Page 25: Sql practise for beginners

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

Page 26: Sql practise for beginners

SQL JOIN

Page 27: Sql practise for beginners

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

SQL JOIN

Page 28: Sql practise for beginners

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

Page 29: Sql practise for beginners

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

Page 30: Sql practise for beginners

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

Type of JOINs

Page 31: Sql practise for beginners

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

Page 32: Sql practise for beginners

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

Page 33: Sql practise for beginners

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

Page 34: Sql practise for beginners

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

Page 35: Sql practise for beginners

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

Page 36: Sql practise for beginners

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

Page 37: Sql practise for beginners

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

Page 38: Sql practise for beginners

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

Page 39: Sql practise for beginners

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

Page 40: Sql practise for beginners

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

Page 41: Sql practise for beginners

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

Page 42: Sql practise for beginners

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

Page 43: Sql practise for beginners

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

Page 44: Sql practise for beginners

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

Page 45: Sql practise for beginners

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

Page 46: Sql practise for beginners

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

Page 47: Sql practise for beginners

NULL values represent missing unknown data

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

SQL NULL Values

Page 48: Sql practise for beginners

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

Page 49: Sql practise for beginners

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

Page 50: Sql practise for beginners

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