Sql practise for beginners
Upcoming SlideShare
Loading in...5
×
 

Sql practise for beginners

on

  • 235 views

 

Statistics

Views

Total Views
235
Views on SlideShare
174
Embed Views
61

Actions

Likes
0
Downloads
3
Comments
0

1 Embed 61

http://practices.issoft.by 61

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Sql practise for beginners Sql practise for beginners Presentation Transcript

    • 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
    • Спасибо за внимание!