Download - Sql practise for beginners
![Page 1: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/1.jpg)
DatabasesandSQL – Structured Query Language
![Page 2: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/2.jpg)
Совокупность данных из набора двумерных таблиц:
Реляционная модель
![Page 3: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/3.jpg)
- Огромные объемы данных- Огромное число пользователей- Гибкая, не ограниченная схемой структура БД.- NoSQL используют: Facebook, eBay
NoSQL БД
![Page 4: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/4.jpg)
Помогает избавиться от избыточности в отношениях и оптимизировать работу БД
Нормализация
![Page 5: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/5.jpg)
Ключ – это набор столбцов таблицы, которые уникально определяют строку.Суррогатный ключ – уникальный ключ искусственного происхождения (Например ID или просто порядковый номер)
Ключ
![Page 6: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/6.jpg)
Нормализация – подразумевает приведение БД к одной из НФВсего их 6Обычно используются первых 3
Нормальные формы НФ
![Page 7: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/7.jpg)
Каждая строка должна хранить одно-единственное значение и не являться списком. Атрибут должен быть атомарным.
1-я НФ (1НФ)
![Page 8: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/8.jpg)
- Устранение избыточности данных- Использование атомарных(не составных)
ключей
2НФ
![Page 9: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/9.jpg)
Факты, хранимые в таблицах должны зависеть только от ключа
3НФ
![Page 10: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/10.jpg)
Команды состоят из: - имен операций и функций - имен таблиц и их стобцов - зарезервированных ключевых слов и
спец.символов - логических и арифметических выражений.
Команды SQL
![Page 11: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/11.jpg)
SELECT CustomerName, CityFROM Customers;orSELECT * FROM Customers;
SELECT Statement
![Page 12: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/12.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/13.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/14.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/15.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/16.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/17.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/18.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/19.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/20.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/21.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/22.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/23.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/24.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/25.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/26.jpg)
SQL JOIN
![Page 27: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/27.jpg)
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDateFROM OrdersINNER JOIN CustomersON Orders.CustomerID=Customers.CustomerID;
SQL JOIN
![Page 28: Sql practise for beginners](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/28.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/29.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/30.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/31.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/32.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/33.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/34.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/35.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/36.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/37.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/38.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/39.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/40.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/41.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/42.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/43.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/44.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/45.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/46.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/47.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/48.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/49.jpg)
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](https://reader033.vdocument.in/reader033/viewer/2022061106/54473c86afaf9f51178b49a3/html5/thumbnails/50.jpg)
Спасибо за внимание!