SlideShare une entreprise Scribd logo
1  sur  50
Databases
and
SQL – Structured Query
Language
Совокупность данных из набора
двумерных таблиц:
- Огромные объемы данных
- Огромное число пользователей
- Гибкая, не ограниченная схемой
структура БД.
- NoSQL используют: Facebook, eBay
Помогает избавиться от избыточности в
отношениях и оптимизировать работу БД
Ключ – это набор столбцов таблицы,
которые уникально определяют
строку.
Суррогатный ключ – уникальный ключ
искусственного происхождения
(Например ID или просто порядковый
номер)
Нормализация – подразумевает приведение
БД к одной из НФ
Всего их 6
Обычно используются первых 3
Каждая строка должна хранить одно-
единственное значение и не являться
списком. Атрибут должен быть атомарным.
- Устранение избыточности данных
- Использование атомарных(не составных)
ключей
Факты, хранимые в таблицах должны
зависеть только от ключа
Команды состоят из:
 - имен операций и функций
 - имен таблиц и их стобцов
 - зарезервированных ключевых слов и
спец.символов
 - логических и арифметических выражений.
SELECT CustomerName, City
FROM Customers;
or
SELECT * FROM Customers;
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;
The WHERE clause is used to extract only those
records that fulfill a specified criterion
SELECT *
FROM Customers
WHERE Country='Mexico';
 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 Customers
WHERE Country='Germany'
AND City='Berlin';
SELECT * FROM Customers
WHERE City='Berlin'
OR City='München';
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
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 Customers
ORDER BY Country DESC;
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');
The UPDATE statement is used to update
existing records in a table
UPDATE Customers
SET 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!
The DELETE statement is used to delete rows in a
table:
DELETE FROM Customers
WHERE CustomerName='Alfreds Fkiste';
Or
DELETE FROM Customers;
All rows will be deleted!
The LIKE operator is used to search for a
specified pattern in a column:
SELECT * FROM Customers
WHERE City LIKE 's%';
Or
SELECT * FROM Customers
WHERE Country(NOT) LIKE '%land%';
All customers with a Country containing the
pattern "land"
SQL wildcard characters are used with the SQL LIKE
operator:
%-Заменяет любое кол-во симоволов
_ - Заменяет один символ
[abc] – Диапазон символов
[!abc] – Исключает диапазон символов
SELECT * FROM Customers
WHERE City LIKE 'ber%';
SELECT * FROM Customers
WHERE City LIKE '%es%';
SELECT * FROM Customers
WHERE City LIKE '_erlin';
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The BETWEEN operator selects values within a
range. The values can be numbers, text, or dates.
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Or
SELECT * FROM Products
WHERE ProductName(NOT) BETWEEN 'C'
AND 'M';
SQL aliases are used to give a database table, or a
column in a table, a temporary name.
SELECT CustomerName AS Cust,
ContactName AS Somebody
FROM Customers;
SELECT CustomerName, Address+',
'+City+', '+PostalCode+', '+Country AS
Address
FROM Customers; - combine four columns
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
SELECT Orders.OrderID,
Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
 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.
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).
The FULL OUTER JOIN keyword returns
all rows from the left table (table1) and
from the right table (table2).
The SQL UNION operator combines the result of
two or more SELECT statements.
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
The SELECT INTO statement selects data from
one table and inserts it into a new table.
SELECT *
INTO CustomersBackup2013
FROM Customers;
WHERE Country='Germany';
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;
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 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));
 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));
 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));
 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));
 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'));
 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');
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;
The ALTER TABLE statement is used to add,
delete, or modify columns in an existing table.
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year(data
type);
ALTER TABLE Persons
DROP COLUMN DateOfBirth;
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));
In SQL, a view is a virtual table based on the
result-set of an SQL statement.
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
DROP VIEW view_name;
 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
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
NULL values represent missing unknown data
SELECT LastName,FirstName,Address
FROM Persons
WHERE Address IS(NOT) NULL;
Data type Access SQLServer Oracle MySQL PostgreSQL
boolean Yes/No Bit Byte N/A Boolean
integer
Number
(integer)
Int Number
Int
Integer
Int
Integer
float
Number
(single)
Float
Real
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+)
Varchar
Varchar
Varchar2
Varchar Varchar
binary object
OLE Object
Memo
Binary (fixed up to
8K)
Varbinary (<8K)
Image (<2GB)
Long
Raw
Blob
Text
Binary
Varbinary
 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
Спасибо за внимание!

Contenu connexe

Tendances

Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querriesIbrahim Jutt
 
06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinctBishal Ghimire
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command StatementsShaun Wilson
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLPrashant Kumar
 
Ppt INFORMATIVE PRACTICES for class 11th chapter 14
Ppt INFORMATIVE PRACTICES for class 11th chapter 14Ppt INFORMATIVE PRACTICES for class 11th chapter 14
Ppt INFORMATIVE PRACTICES for class 11th chapter 14prashant0000
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)Nalina Kumari
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQLMahir Haque
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating databaseMukesh Tekwani
 
vFabric SQLFire Introduction
vFabric SQLFire IntroductionvFabric SQLFire Introduction
vFabric SQLFire IntroductionJags Ramnarayan
 
Intro to tsql unit 7
Intro to tsql   unit 7Intro to tsql   unit 7
Intro to tsql unit 7Syed Asrarali
 
Data Definition Language (DDL)
Data Definition Language (DDL) Data Definition Language (DDL)
Data Definition Language (DDL) Mohd Tousif
 

Tendances (19)

Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querries
 
Sql
SqlSql
Sql
 
06.01 sql select distinct
06.01 sql select distinct06.01 sql select distinct
06.01 sql select distinct
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command Statements
 
SQL
SQLSQL
SQL
 
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQLSql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
Sql notes, sql server,sql queries,introduction of SQL, Beginner in SQL
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Sql slid
Sql slidSql slid
Sql slid
 
Ppt INFORMATIVE PRACTICES for class 11th chapter 14
Ppt INFORMATIVE PRACTICES for class 11th chapter 14Ppt INFORMATIVE PRACTICES for class 11th chapter 14
Ppt INFORMATIVE PRACTICES for class 11th chapter 14
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
BIS05 Introduction to SQL
BIS05 Introduction to SQLBIS05 Introduction to SQL
BIS05 Introduction to SQL
 
Sql basics v2
Sql basics v2Sql basics v2
Sql basics v2
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
vFabric SQLFire Introduction
vFabric SQLFire IntroductionvFabric SQLFire Introduction
vFabric SQLFire Introduction
 
Intro to tsql unit 7
Intro to tsql   unit 7Intro to tsql   unit 7
Intro to tsql unit 7
 
Varraysandnestedtables
VarraysandnestedtablesVarraysandnestedtables
Varraysandnestedtables
 
Sql commands
Sql commandsSql commands
Sql commands
 
Data Definition Language (DDL)
Data Definition Language (DDL) Data Definition Language (DDL)
Data Definition Language (DDL)
 

Similaire à Sql practise for beginners

Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01sagaroceanic11
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsAshwin Dinoriya
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfAnishurRehman1
 
ADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxArjayBalberan1
 
MQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptxMQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptxlemonchoos
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1Swapnali Pawar
 
Relational database management system
Relational database management systemRelational database management system
Relational database management systemPraveen Soni
 
MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.sudhasuryasnata06
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1sagaroceanic11
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxjainendraKUMAR55
 

Similaire à Sql practise for beginners (20)

Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01Mysql 120831075600-phpapp01
Mysql 120831075600-phpapp01
 
SQL report
SQL reportSQL report
SQL report
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Sql basics
Sql basicsSql basics
Sql basics
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdf
 
ADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptx
 
MQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptxMQSL JOINING OF TABLES.pptx
MQSL JOINING OF TABLES.pptx
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Relational database management system
Relational database management systemRelational database management system
Relational database management system
 
Unit_9.pptx
Unit_9.pptxUnit_9.pptx
Unit_9.pptx
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.MySQL.pptx comuterscience from kvsbbsrs.
MySQL.pptx comuterscience from kvsbbsrs.
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 

Plus de ISsoft

Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестированииISsoft
 
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...ISsoft
 
Testing of mobile apps
Testing of mobile appsTesting of mobile apps
Testing of mobile appsISsoft
 
Testing, qa, qc. what the difference
Testing, qa, qc. what the differenceTesting, qa, qc. what the difference
Testing, qa, qc. what the differenceISsoft
 
Ranorex presentation
Ranorex presentationRanorex presentation
Ranorex presentationISsoft
 
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...ISsoft
 
Bdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеBdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеISsoft
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требованийISsoft
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требованийISsoft
 
Отдел юзабилити
Отдел юзабилитиОтдел юзабилити
Отдел юзабилитиISsoft
 
ToDoList
ToDoListToDoList
ToDoListISsoft
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentationISsoft
 
решение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baрешение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baISsoft
 
решение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистоврешение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистовISsoft
 
Development of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesDevelopment of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesISsoft
 
Bdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеBdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеISsoft
 
инфотекс автоматизация тестирования
инфотекс   автоматизация тестированияинфотекс   автоматизация тестирования
инфотекс автоматизация тестированияISsoft
 
Sikuli script
Sikuli scriptSikuli script
Sikuli scriptISsoft
 

Plus de ISsoft (20)

Sql инъекции в тестировании
Sql инъекции в тестированииSql инъекции в тестировании
Sql инъекции в тестировании
 
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
введение в практическую разработку по в Is soft 4-1 and 4-2 clients and commu...
 
Testing of mobile apps
Testing of mobile appsTesting of mobile apps
Testing of mobile apps
 
Testing, qa, qc. what the difference
Testing, qa, qc. what the differenceTesting, qa, qc. what the difference
Testing, qa, qc. what the difference
 
Ranorex presentation
Ranorex presentationRanorex presentation
Ranorex presentation
 
Bugs
BugsBugs
Bugs
 
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
Bdd j behave or cucumber jvm plus appium for efficient cross platform mobile ...
 
Bdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проектеBdd and dsl как способ построения коммуникации на проекте
Bdd and dsl как способ построения коммуникации на проекте
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требований
 
Тестирование требований
Тестирование требованийТестирование требований
Тестирование требований
 
Отдел юзабилити
Отдел юзабилитиОтдел юзабилити
Отдел юзабилити
 
ToDoList
ToDoListToDoList
ToDoList
 
ISTQB
ISTQBISTQB
ISTQB
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentation
 
решение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте baрешение основной проблемы Agile (scrum) проектов в контексте ba
решение основной проблемы Agile (scrum) проектов в контексте ba
 
решение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистоврешение одной из ключевых проблем компетенции Ba специалистов
решение одной из ключевых проблем компетенции Ba специалистов
 
Development of automated tests for ext js based web sites
Development of automated tests for ext js based web sitesDevelopment of automated tests for ext js based web sites
Development of automated tests for ext js based web sites
 
Bdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проектеBdd or dsl как способ построения коммуникации на проекте
Bdd or dsl как способ построения коммуникации на проекте
 
инфотекс автоматизация тестирования
инфотекс   автоматизация тестированияинфотекс   автоматизация тестирования
инфотекс автоматизация тестирования
 
Sikuli script
Sikuli scriptSikuli script
Sikuli script
 

Dernier

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...liera silvan
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 

Dernier (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 

Sql practise for beginners

  • 2. Совокупность данных из набора двумерных таблиц:
  • 3. - Огромные объемы данных - Огромное число пользователей - Гибкая, не ограниченная схемой структура БД. - NoSQL используют: Facebook, eBay
  • 4. Помогает избавиться от избыточности в отношениях и оптимизировать работу БД
  • 5. Ключ – это набор столбцов таблицы, которые уникально определяют строку. Суррогатный ключ – уникальный ключ искусственного происхождения (Например ID или просто порядковый номер)
  • 6. Нормализация – подразумевает приведение БД к одной из НФ Всего их 6 Обычно используются первых 3
  • 7. Каждая строка должна хранить одно- единственное значение и не являться списком. Атрибут должен быть атомарным.
  • 8. - Устранение избыточности данных - Использование атомарных(не составных) ключей
  • 9. Факты, хранимые в таблицах должны зависеть только от ключа
  • 10. Команды состоят из:  - имен операций и функций  - имен таблиц и их стобцов  - зарезервированных ключевых слов и спец.символов  - логических и арифметических выражений.
  • 11. SELECT CustomerName, City FROM Customers; or SELECT * FROM Customers;
  • 12. 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;
  • 13. The WHERE clause is used to extract only those records that fulfill a specified criterion SELECT * FROM Customers WHERE Country='Mexico';
  • 14.  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 Customers WHERE Country='Germany' AND City='Berlin';
  • 15. SELECT * FROM Customers WHERE City='Berlin' OR City='München'; SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
  • 16. 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 Customers ORDER BY Country DESC;
  • 17. 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');
  • 18. The UPDATE statement is used to update existing records in a table UPDATE Customers SET 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!
  • 19. The DELETE statement is used to delete rows in a table: DELETE FROM Customers WHERE CustomerName='Alfreds Fkiste'; Or DELETE FROM Customers; All rows will be deleted!
  • 20. The LIKE operator is used to search for a specified pattern in a column: SELECT * FROM Customers WHERE City LIKE 's%'; Or SELECT * FROM Customers WHERE Country(NOT) LIKE '%land%'; All customers with a Country containing the pattern "land"
  • 21. SQL wildcard characters are used with the SQL LIKE operator: %-Заменяет любое кол-во симоволов _ - Заменяет один символ [abc] – Диапазон символов [!abc] – Исключает диапазон символов SELECT * FROM Customers WHERE City LIKE 'ber%';
  • 22. SELECT * FROM Customers WHERE City LIKE '%es%'; SELECT * FROM Customers WHERE City LIKE '_erlin'; SELECT * FROM Customers WHERE City LIKE '[bsp]%';
  • 23. The BETWEEN operator selects values within a range. The values can be numbers, text, or dates. SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; Or SELECT * FROM Products WHERE ProductName(NOT) BETWEEN 'C' AND 'M';
  • 24. SQL aliases are used to give a database table, or a column in a table, a temporary name. SELECT CustomerName AS Cust, ContactName AS Somebody FROM Customers; SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address FROM Customers; - combine four columns
  • 25. 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
  • 26.
  • 27. SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
  • 28.  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.
  • 29. 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).
  • 30. The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).
  • 31. The SQL UNION operator combines the result of two or more SELECT statements. SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;
  • 32. The SELECT INTO statement selects data from one table and inserts it into a new table. SELECT * INTO CustomersBackup2013 FROM Customers; WHERE Country='Germany';
  • 33. 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;
  • 34. 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) );
  • 35. 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));
  • 36.  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));
  • 37.  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));
  • 38.  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));
  • 39.  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'));
  • 40.  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');
  • 41. 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;
  • 42. The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. ALTER TABLE Persons ALTER COLUMN DateOfBirth year(data type); ALTER TABLE Persons DROP COLUMN DateOfBirth;
  • 43. 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));
  • 44. In SQL, a view is a virtual table based on the result-set of an SQL statement. CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition; DROP VIEW view_name;
  • 45.  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
  • 46. 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
  • 47. NULL values represent missing unknown data SELECT LastName,FirstName,Address FROM Persons WHERE Address IS(NOT) NULL;
  • 48. Data type Access SQLServer Oracle MySQL PostgreSQL boolean Yes/No Bit Byte N/A Boolean integer Number (integer) Int Number Int Integer Int Integer float Number (single) Float Real 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+) Varchar Varchar Varchar2 Varchar Varchar binary object OLE Object Memo Binary (fixed up to 8K) Varbinary (<8K) Image (<2GB) Long Raw Blob Text Binary Varbinary
  • 49.  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