SlideShare uma empresa Scribd logo
1 de 36
Baixar para ler offline
MODULE 4
SQL QUERIES
ALEXANDER BABICH
ALEXANDER.TAURUS@GMAIL.COM
MODULE OVERVIEW
• SQL expressions. Basic language constructs
• SELECT statement. Build simple queries with
selection conditions
• COUNT, FIRST, LAST statistical functions
• Statistical functions MIN, MAX,AVG. SUM
function
• Queries to add, update, delete, create a table
LESSON 1:WHAT IS SQL?
• SQL expressions. Basic language constructs
• SELECT statement. Build simple queries with selection
conditions
• COUNT, FIRST, LAST statistical functions
• Statistical functions MIN, MAX,AVG. SUM function
WHAT IS SQL?
WHAT IS SQL?
Structured Query Language
• universal language for creating, modifying
and managing data in relational databases
• 70s - end user tool
• not a programming language!
• But there is the possibility of procedural
extensions
WHY WE USE SQL?
WHAT IS SQL?
DDL
DML
SQL
DDL
DML
MICROSOFT ACCESS И SQL
• Support for two SQL standards:
• ANSI
• MS Jet SQL
• Differences:
• different sets of reserved words and data types
• different rules for the operator Between ... And ...
• different wildcards of the operator Like (? and _, * and %)
• Jet SQL - grouping and sorting by expressions is allowed
• Jet SQL - more complex expressions and additional
instructions
"GENERAL" STATEMENTS
ADD COMMIT* FETCH* MAX ROLLBACK*
ALL CONSTRAINT FROM MIN SELECT
ALTER COUNT FOREIGN NOT SET
ANY CREATE GRANT* NULL SOME
ALIAS CREATEVIEW* HAVING ON TRANSACTION*
AS CURRENT* IN OR UNION
ASC CURSOR* INDEX ORDER UNIQUE
AUTHORIZATION* DECLARE* INNER OUTER UPDATE
AVG DELETE INSERT PARAMETERS VALUE
BEGIN* DESC INTO PRIMARY VALUES
BETWEEN DISALLOW IS PRIVILEGES* WHERE
BY DISTINCT JOIN PROCEDURE WORK*
CHECK* DROP KEY REFERENCES
CLOSE* DROPVIEW* LEFT REVOKE*
COLUMN EXISTS LIKE RIGHT
OPERATORS
• Most comparison operators match: =, <, <=, >, =>
• The exception is the inequality operator
• != in ANSI SQL
• <> in Jet SQL
FUNCTIONS AND OPERATORS
Access ANSI SQL
And AND
Avg( ) AVG()
Between BETWEEN
Count ( ) COUNT
Is IS
Like LIKE
Мах( ) MAX()
Min( ) MIN()
Not NOT
Null NULL
Or OR
Sum( ) SUM
NEW IN JET SQL
Access Function Meaning
StdDev()
The offset of the standard deviation for
the sample
StdDevP ( )
The unbiased value of the standard
deviation for the sample
Var () Offset variance value for the sample
VarP ( )
The unbiased variance value for the
sample
DATA TYPES
Data types of ANSI SQL Data types of Jet SQL Alias Note
BIT, BIT VARYING BINARY
VARBINARY, BINARY
VARYING BIT VARYING
Not a standard Access data type
UNSUPPORTED BIT
BOOLEAN, LOGICAL,
LOGICAL1, YESNO
Yes/No
UNSUPPORTED TINYINT INTEGER 1, BYTE Byte
UNSUPPORTED COUNTER AUTOINCREMENT
UNSUPPORTED MONEY CURRENCY Currency
DATE, TIME, TIMESTAMP DATETIME DATE, TIME Date/Time
UNSUPPORTED UNIQUEIDEN TIFIER QUID
DECIMAL DECIMAL NUMERIC, DEC
REAL REAL
SINGLE, FLOAT4,
IEEESINGLE
Number (Single)
DOUBLE PRECISION,
FLOAT
FLOAT
DOUBLE, FLOATS,
IEEEDOUBLE, NUMBER
Number (Double)
SMALLINT SMALLINT SHORT, INTEGER2 Number (Integer)
INTEGER INTEGER LONG, INT, INTEGER4 Number (Long Integer)
INTERVAL UNSUPPORTED
UNSUPPORTED IMAGE
LONGBINARY, GENERAL,
OLEOBJECT
OLE field
UNSUPPORTED TEXT
LONGTEXT, LONGCHAR,
MEMO, NOTE, NTEXT
(MEMO) Long Text field
CHARACTER, CHARACTER
VARYING, NATIONAL
CHARACTER, NATIONAL
CHARACTER VARYING
CHAR
TEXT(n), ALPHANUMERIC,
CHARACTER, STRING,
VARCHAR, CHARACTER
VARYING, NCHAR,
NATIONAL CHARACTER,
NATIONAL CHAR,
NATIONAL CHARACTER
VARYING, NATIONAL
CHAR VARYING
Short Text field
WILDCARD CHARACTERS
Jet SQL ANSI SQL Note
? _ (underscore) Any single character
* %
Arbitrary number of
characters
# No equivalent Any digit from 0 to 9
[character_list] No equivalent
Any single character
from the character list
[!character_list] No equivalent
Any single character
not included in the
character list
SEPARATORS AND CHARACTERS
Commas are used to separate list members
• First Name, Last Name, Middle Name,Year of Birth,Address, City, Index
Square brackets are used to specify field names that contain spaces
• [Date of placement]
If the query includes fields from several tables, then the full field name is
included
• the name of the table and the name of the field, between which the point is
used
• Orders.Order_code
Characters are enclosed in both single (') and double quotation marks (")
• when using SQL statements inVBA procedures, it is recommended
to put single quotes
At the end of the Jet SQL statement, a semicolon (;) is mandatory
CREATING SQL QUERIES
Create a query using the DesignView
Close the Show Table dialog box without adding tables
ChooseView > SQLView on the ribbon
Delete all text in SQL window
• usually the default is SELECT DISTINCTROW;
Enter SQL statement
• CTRL+ENTER for a new line
Click the Run (!) button on the ribbon
SELECT STATEMENT
SELECT [predicate] { * | table.* | [table.]field_1
[AS alias_1] [, [table.]field_2 [AS alias_2] [,...]]}
FROM expression [, ...] [IN externalDataBase]
[WHERE...]
[GROUP BY...]
[HAVING...]
[ORDER BY...]
[WITH OWNERACCESS OPTION]
EXAMPLES
• SELECTTOP 25 * FROM Orders IN "С:DocumentsNorthWind.mdb";
• SELECT Ordered.*, Orders.CustomerID, Orders.OrderDate,
Orders.OrderID FROM Orders, Ordered
WHERE (((Orders.OrderDate)>=#1/1/2018#) AND
((Orders.OrderID)=[Ordered].[OrderID])) OR
(((Orders.OrderDate) Is Null) AND
((Orders.OrderID)=[Ordered].[OrderID]));
• SELECT Customers.Title, Customers.City, Customers.Address
FROM Customers
WHERE (((Customers.Country)
IN (‘Ukraine’,’Poland’,’Georgia')));
ELIMINATION OF REPETITIONS
• DISTINCTROW and DISTINCT in the SELECT
statement allow you to exclude duplicate lines
from the result set
• DISTINCTROW - all fields of the source table are
used to compare records.
• no matter which fields are included in the query
• DISTINCT - only those fields that are included in
the query are used to compare records.
AGGREGATE FUNCTIONS
• AVG () - average
• COUNT () - the number of rows
• FIRST () - first value
• LAST () - the last value
• MAX () - the highest value
• MIN () - the lowest value
• SUM () - amount
SCALAR FUNCTIONS
• UCASE () - upper case
• LCASE () - lower case
• MID () - extract characters from text
• LEN () - text length
• ROUND () - rounding value
• NOW () - current date-time
• FORMAT () - formatting values
EXAMPLES
• SELECT Count(*) AS [Number of Invoices]
FROM tblInvoices
• SELECT Avg(Amount) AS [Average Invoice
Amount] FROM tblInvoices
• SELECT Last(Amount) AS [Last Invoice Amount]
FROM tblInvoices
LESSON 2: SQL QUERIES
• Queries to add, update,
delete, create a table
QUERIESTO ADD
INSERT INTO destination [(field_1[, field_2[, ...]])] [IN externalDataBase]
SELECT [source.]field_1[, field_2[, ...]
FROM expression [, ...] [IN externalDataBase]
[WHERE...]
[GROUP BY...]
[HAVING...]
[ORDER BY...]
[WITH OWNERACCESS OPTION]
Examples:
• INSERT INTO Delivery (Title, PhoneNumber)
VALUES (“DHL",“+3(095)211-9988");
• INSERT INTOTempTable ( CustomerID, [OrderAmount] )
SELECT Orders.CustomerID,sum([Price]*[Quantity])
FROM Ordered, Orders IN "С:DocumentsDataBasel.mdb"
WHERE (Ordered.OrderID)=[Orders].[OrderID]))
GROUP BY Orders.CustomerID
ORDER BY Sum([Price]*[Quantity])
DESC;
QUERIESTO UPDATE
• UPDATE table SET field=newValue WHERE criteria
• Examples:
• UPDATE [Products] SET [Products].Discontinued = False
WHERE ((([Products].Discontinued)=Тruе));
• UPDATE Orders INNER JOIN Ordered ON
Orders.OrderID= Ordered.OrderID SET
Ordered.Discount = 0 WHERE (((Orders.OrderDate) Is
Null));
QUERIESTO DELETE
• DELETE [table.]*, field_1 [,...] FROM table
WHERE criteria
• Example:
• DELETE [Products].Discontinued FROM [Products]
WHERE ((([Products].Discontinued)=Тruе));
• DROP {TABLE table | INDEX index ON table |
PROCEDURE procedure |VIEW view}
QUERIESTO CREATE A TABLE
CREATE [TEMPORARY] TABLE table (field_1 type [(size)]
[NOT NULL] [WITH COMPRESSION |WITH COMP]
[index_1] [, field_2 тип [(size)] [NOT NULL]
[index_2] [, ...]] [, CONSTRAINT complexIndex [, ...]])
EXERCISE
1. Try to recreate the same
queries for your database
using SQL
BOTTOM LINE
• SQL expressions. Basic language constructs
• SELECT statement. Build simple queries with
selection conditions
• COUNT, FIRST, LAST statistical functions
• Statistical functions MIN, MAX,AVG. SUM
function
• Queries to add, update, delete, create a table
QUESTIONS?
SELF-TEST
• What SQL standards are supported by Microsoft
Access?What are the differences between them?
• How to create a SQL query in Access?
• List Access SQL QueryTypes
WANT TO KNOW MORE?
W3Schools SQL Tutorial
https://www.w3schools.com/sql/default.asp
WANT TO KNOW MORE?
Sololearn SQL Fundamentals
https://www.sololearn.com/Course/SQL/
WANT TO KNOW MORE?
SQL Course - QA
https://www.slideshare.net/pingkapil/sql-course-qa

Mais conteúdo relacionado

Mais procurados

1 data types
1 data types1 data types
1 data typesRam Kedem
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queriesPRAKHAR JHA
 
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101IDERA Software
 
Episode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceEpisode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceJitendra Zaa
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schoolsfarhan516
 
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
 
Nested Types in Impala
Nested Types in ImpalaNested Types in Impala
Nested Types in ImpalaMyung Ho Yun
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsZohar Elkayam
 

Mais procurados (18)

Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
3 indexes
3 indexes3 indexes
3 indexes
 
1 data types
1 data types1 data types
1 data types
 
Oracle basic queries
Oracle basic queriesOracle basic queries
Oracle basic queries
 
Db1 lecture4
Db1 lecture4Db1 lecture4
Db1 lecture4
 
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101
 
Episode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceEpisode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in Salesforce
 
DML using oracle
 DML using oracle DML using oracle
DML using oracle
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Sql
SqlSql
Sql
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
dbms lab manual
dbms lab manualdbms lab manual
dbms lab manual
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
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
 
Nested Types in Impala
Nested Types in ImpalaNested Types in Impala
Nested Types in Impala
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
 

Semelhante a Access 04

ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxYashaswiniSrinivasan1
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAndrey Gershun
 
Using ddl statements to create and manage tables
Using ddl statements to create and manage tablesUsing ddl statements to create and manage tables
Using ddl statements to create and manage tablesSyed Zaid Irshad
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sqlŁukasz Grala
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql MengChun Lam
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republicKaing Menglieng
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1MariaDB plc
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle Abrar ali
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentationMichael Keane
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
 

Semelhante a Access 04 (20)

ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptx
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User Manual
 
Using ddl statements to create and manage tables
Using ddl statements to create and manage tablesUsing ddl statements to create and manage tables
Using ddl statements to create and manage tables
 
Les09
Les09Les09
Les09
 
Database
Database Database
Database
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
SQL(database)
SQL(database)SQL(database)
SQL(database)
 
Ch6(mysql front)
Ch6(mysql front)Ch6(mysql front)
Ch6(mysql front)
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republic
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Physical Design and Development
Physical Design and DevelopmentPhysical Design and Development
Physical Design and Development
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
Master tuning
Master   tuningMaster   tuning
Master tuning
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentation
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 

Mais de Alexander Babich

Актуальні курси з мого арсеналу (Бабич О.В.)
Актуальні курси з мого арсеналу (Бабич О.В.)Актуальні курси з мого арсеналу (Бабич О.В.)
Актуальні курси з мого арсеналу (Бабич О.В.)Alexander Babich
 
M365: Word, Excel, PowerPoint...
M365: Word, Excel, PowerPoint...M365: Word, Excel, PowerPoint...
M365: Word, Excel, PowerPoint...Alexander Babich
 
M365: Інші сервіси та застосунки
M365: Інші сервіси та застосункиM365: Інші сервіси та застосунки
M365: Інші сервіси та застосункиAlexander Babich
 
M365: Завершення
M365: ЗавершенняM365: Завершення
M365: ЗавершенняAlexander Babich
 
M365: рекомендації
M365: рекомендаціїM365: рекомендації
M365: рекомендаціїAlexander Babich
 
M365: Огляд платформи Microsoft365
M365: Огляд платформи Microsoft365M365: Огляд платформи Microsoft365
M365: Огляд платформи Microsoft365Alexander Babich
 
M365: Роздаткові матеріали
M365: Роздаткові матеріалиM365: Роздаткові матеріали
M365: Роздаткові матеріалиAlexander Babich
 
Meet&Code - VR, метавсесвіт та криптовалюти (1).pptx
Meet&Code - VR, метавсесвіт та криптовалюти (1).pptxMeet&Code - VR, метавсесвіт та криптовалюти (1).pptx
Meet&Code - VR, метавсесвіт та криптовалюти (1).pptxAlexander Babich
 
Ви обрали професію програміста
Ви обрали професію програмістаВи обрали професію програміста
Ви обрали професію програмістаAlexander Babich
 
Змішане навчання в ППФК
Змішане навчання в ППФКЗмішане навчання в ППФК
Змішане навчання в ППФКAlexander Babich
 
Формування професійних інтересів студентів
Формування професійних інтересів студентівФормування професійних інтересів студентів
Формування професійних інтересів студентівAlexander Babich
 
День відкритих дверей' 2021
День відкритих дверей' 2021День відкритих дверей' 2021
День відкритих дверей' 2021Alexander Babich
 
06. Обучение и сертификация по Azure
06. Обучение и сертификация по Azure06. Обучение и сертификация по Azure
06. Обучение и сертификация по AzureAlexander Babich
 
05.Внедрение Azure
05.Внедрение Azure05.Внедрение Azure
05.Внедрение AzureAlexander Babich
 
04.Службы Azure - подробнее
04.Службы Azure - подробнее04.Службы Azure - подробнее
04.Службы Azure - подробнееAlexander Babich
 
03.Сколько стоит облако
03.Сколько стоит облако03.Сколько стоит облако
03.Сколько стоит облакоAlexander Babich
 

Mais de Alexander Babich (20)

Актуальні курси з мого арсеналу (Бабич О.В.)
Актуальні курси з мого арсеналу (Бабич О.В.)Актуальні курси з мого арсеналу (Бабич О.В.)
Актуальні курси з мого арсеналу (Бабич О.В.)
 
M365: Word, Excel, PowerPoint...
M365: Word, Excel, PowerPoint...M365: Word, Excel, PowerPoint...
M365: Word, Excel, PowerPoint...
 
M365: Інші сервіси та застосунки
M365: Інші сервіси та застосункиM365: Інші сервіси та застосунки
M365: Інші сервіси та застосунки
 
M365: OneDrive
M365: OneDriveM365: OneDrive
M365: OneDrive
 
M365: Завершення
M365: ЗавершенняM365: Завершення
M365: Завершення
 
M365: SharePoint
M365: SharePointM365: SharePoint
M365: SharePoint
 
M365: рекомендації
M365: рекомендаціїM365: рекомендації
M365: рекомендації
 
M365: Огляд платформи Microsoft365
M365: Огляд платформи Microsoft365M365: Огляд платформи Microsoft365
M365: Огляд платформи Microsoft365
 
M365: Вступ
M365: ВступM365: Вступ
M365: Вступ
 
M365: Роздаткові матеріали
M365: Роздаткові матеріалиM365: Роздаткові матеріали
M365: Роздаткові матеріали
 
Meet&Code - VR, метавсесвіт та криптовалюти (1).pptx
Meet&Code - VR, метавсесвіт та криптовалюти (1).pptxMeet&Code - VR, метавсесвіт та криптовалюти (1).pptx
Meet&Code - VR, метавсесвіт та криптовалюти (1).pptx
 
Ви обрали професію програміста
Ви обрали професію програмістаВи обрали професію програміста
Ви обрали професію програміста
 
Змішане навчання в ППФК
Змішане навчання в ППФКЗмішане навчання в ППФК
Змішане навчання в ППФК
 
Формування професійних інтересів студентів
Формування професійних інтересів студентівФормування професійних інтересів студентів
Формування професійних інтересів студентів
 
День відкритих дверей' 2021
День відкритих дверей' 2021День відкритих дверей' 2021
День відкритих дверей' 2021
 
Спробуйте Python
Спробуйте PythonСпробуйте Python
Спробуйте Python
 
06. Обучение и сертификация по Azure
06. Обучение и сертификация по Azure06. Обучение и сертификация по Azure
06. Обучение и сертификация по Azure
 
05.Внедрение Azure
05.Внедрение Azure05.Внедрение Azure
05.Внедрение Azure
 
04.Службы Azure - подробнее
04.Службы Azure - подробнее04.Службы Azure - подробнее
04.Службы Azure - подробнее
 
03.Сколько стоит облако
03.Сколько стоит облако03.Сколько стоит облако
03.Сколько стоит облако
 

Último

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 

Último (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Access 04

  • 1. MODULE 4 SQL QUERIES ALEXANDER BABICH ALEXANDER.TAURUS@GMAIL.COM
  • 2. MODULE OVERVIEW • SQL expressions. Basic language constructs • SELECT statement. Build simple queries with selection conditions • COUNT, FIRST, LAST statistical functions • Statistical functions MIN, MAX,AVG. SUM function • Queries to add, update, delete, create a table
  • 3. LESSON 1:WHAT IS SQL? • SQL expressions. Basic language constructs • SELECT statement. Build simple queries with selection conditions • COUNT, FIRST, LAST statistical functions • Statistical functions MIN, MAX,AVG. SUM function
  • 5. WHAT IS SQL? Structured Query Language • universal language for creating, modifying and managing data in relational databases • 70s - end user tool • not a programming language! • But there is the possibility of procedural extensions
  • 6. WHY WE USE SQL?
  • 8. DDL
  • 9. DML
  • 10. MICROSOFT ACCESS И SQL • Support for two SQL standards: • ANSI • MS Jet SQL • Differences: • different sets of reserved words and data types • different rules for the operator Between ... And ... • different wildcards of the operator Like (? and _, * and %) • Jet SQL - grouping and sorting by expressions is allowed • Jet SQL - more complex expressions and additional instructions
  • 11. "GENERAL" STATEMENTS ADD COMMIT* FETCH* MAX ROLLBACK* ALL CONSTRAINT FROM MIN SELECT ALTER COUNT FOREIGN NOT SET ANY CREATE GRANT* NULL SOME ALIAS CREATEVIEW* HAVING ON TRANSACTION* AS CURRENT* IN OR UNION ASC CURSOR* INDEX ORDER UNIQUE AUTHORIZATION* DECLARE* INNER OUTER UPDATE AVG DELETE INSERT PARAMETERS VALUE BEGIN* DESC INTO PRIMARY VALUES BETWEEN DISALLOW IS PRIVILEGES* WHERE BY DISTINCT JOIN PROCEDURE WORK* CHECK* DROP KEY REFERENCES CLOSE* DROPVIEW* LEFT REVOKE* COLUMN EXISTS LIKE RIGHT
  • 12. OPERATORS • Most comparison operators match: =, <, <=, >, => • The exception is the inequality operator • != in ANSI SQL • <> in Jet SQL
  • 13. FUNCTIONS AND OPERATORS Access ANSI SQL And AND Avg( ) AVG() Between BETWEEN Count ( ) COUNT Is IS Like LIKE Мах( ) MAX() Min( ) MIN() Not NOT Null NULL Or OR Sum( ) SUM
  • 14. NEW IN JET SQL Access Function Meaning StdDev() The offset of the standard deviation for the sample StdDevP ( ) The unbiased value of the standard deviation for the sample Var () Offset variance value for the sample VarP ( ) The unbiased variance value for the sample
  • 15. DATA TYPES Data types of ANSI SQL Data types of Jet SQL Alias Note BIT, BIT VARYING BINARY VARBINARY, BINARY VARYING BIT VARYING Not a standard Access data type UNSUPPORTED BIT BOOLEAN, LOGICAL, LOGICAL1, YESNO Yes/No UNSUPPORTED TINYINT INTEGER 1, BYTE Byte UNSUPPORTED COUNTER AUTOINCREMENT UNSUPPORTED MONEY CURRENCY Currency DATE, TIME, TIMESTAMP DATETIME DATE, TIME Date/Time UNSUPPORTED UNIQUEIDEN TIFIER QUID DECIMAL DECIMAL NUMERIC, DEC REAL REAL SINGLE, FLOAT4, IEEESINGLE Number (Single) DOUBLE PRECISION, FLOAT FLOAT DOUBLE, FLOATS, IEEEDOUBLE, NUMBER Number (Double) SMALLINT SMALLINT SHORT, INTEGER2 Number (Integer) INTEGER INTEGER LONG, INT, INTEGER4 Number (Long Integer) INTERVAL UNSUPPORTED UNSUPPORTED IMAGE LONGBINARY, GENERAL, OLEOBJECT OLE field UNSUPPORTED TEXT LONGTEXT, LONGCHAR, MEMO, NOTE, NTEXT (MEMO) Long Text field CHARACTER, CHARACTER VARYING, NATIONAL CHARACTER, NATIONAL CHARACTER VARYING CHAR TEXT(n), ALPHANUMERIC, CHARACTER, STRING, VARCHAR, CHARACTER VARYING, NCHAR, NATIONAL CHARACTER, NATIONAL CHAR, NATIONAL CHARACTER VARYING, NATIONAL CHAR VARYING Short Text field
  • 16. WILDCARD CHARACTERS Jet SQL ANSI SQL Note ? _ (underscore) Any single character * % Arbitrary number of characters # No equivalent Any digit from 0 to 9 [character_list] No equivalent Any single character from the character list [!character_list] No equivalent Any single character not included in the character list
  • 17. SEPARATORS AND CHARACTERS Commas are used to separate list members • First Name, Last Name, Middle Name,Year of Birth,Address, City, Index Square brackets are used to specify field names that contain spaces • [Date of placement] If the query includes fields from several tables, then the full field name is included • the name of the table and the name of the field, between which the point is used • Orders.Order_code Characters are enclosed in both single (') and double quotation marks (") • when using SQL statements inVBA procedures, it is recommended to put single quotes At the end of the Jet SQL statement, a semicolon (;) is mandatory
  • 18. CREATING SQL QUERIES Create a query using the DesignView Close the Show Table dialog box without adding tables ChooseView > SQLView on the ribbon Delete all text in SQL window • usually the default is SELECT DISTINCTROW; Enter SQL statement • CTRL+ENTER for a new line Click the Run (!) button on the ribbon
  • 19. SELECT STATEMENT SELECT [predicate] { * | table.* | [table.]field_1 [AS alias_1] [, [table.]field_2 [AS alias_2] [,...]]} FROM expression [, ...] [IN externalDataBase] [WHERE...] [GROUP BY...] [HAVING...] [ORDER BY...] [WITH OWNERACCESS OPTION]
  • 20. EXAMPLES • SELECTTOP 25 * FROM Orders IN "С:DocumentsNorthWind.mdb"; • SELECT Ordered.*, Orders.CustomerID, Orders.OrderDate, Orders.OrderID FROM Orders, Ordered WHERE (((Orders.OrderDate)>=#1/1/2018#) AND ((Orders.OrderID)=[Ordered].[OrderID])) OR (((Orders.OrderDate) Is Null) AND ((Orders.OrderID)=[Ordered].[OrderID])); • SELECT Customers.Title, Customers.City, Customers.Address FROM Customers WHERE (((Customers.Country) IN (‘Ukraine’,’Poland’,’Georgia')));
  • 21. ELIMINATION OF REPETITIONS • DISTINCTROW and DISTINCT in the SELECT statement allow you to exclude duplicate lines from the result set • DISTINCTROW - all fields of the source table are used to compare records. • no matter which fields are included in the query • DISTINCT - only those fields that are included in the query are used to compare records.
  • 22. AGGREGATE FUNCTIONS • AVG () - average • COUNT () - the number of rows • FIRST () - first value • LAST () - the last value • MAX () - the highest value • MIN () - the lowest value • SUM () - amount
  • 23. SCALAR FUNCTIONS • UCASE () - upper case • LCASE () - lower case • MID () - extract characters from text • LEN () - text length • ROUND () - rounding value • NOW () - current date-time • FORMAT () - formatting values
  • 24. EXAMPLES • SELECT Count(*) AS [Number of Invoices] FROM tblInvoices • SELECT Avg(Amount) AS [Average Invoice Amount] FROM tblInvoices • SELECT Last(Amount) AS [Last Invoice Amount] FROM tblInvoices
  • 25. LESSON 2: SQL QUERIES • Queries to add, update, delete, create a table
  • 26. QUERIESTO ADD INSERT INTO destination [(field_1[, field_2[, ...]])] [IN externalDataBase] SELECT [source.]field_1[, field_2[, ...] FROM expression [, ...] [IN externalDataBase] [WHERE...] [GROUP BY...] [HAVING...] [ORDER BY...] [WITH OWNERACCESS OPTION] Examples: • INSERT INTO Delivery (Title, PhoneNumber) VALUES (“DHL",“+3(095)211-9988"); • INSERT INTOTempTable ( CustomerID, [OrderAmount] ) SELECT Orders.CustomerID,sum([Price]*[Quantity]) FROM Ordered, Orders IN "С:DocumentsDataBasel.mdb" WHERE (Ordered.OrderID)=[Orders].[OrderID])) GROUP BY Orders.CustomerID ORDER BY Sum([Price]*[Quantity]) DESC;
  • 27. QUERIESTO UPDATE • UPDATE table SET field=newValue WHERE criteria • Examples: • UPDATE [Products] SET [Products].Discontinued = False WHERE ((([Products].Discontinued)=Тruе)); • UPDATE Orders INNER JOIN Ordered ON Orders.OrderID= Ordered.OrderID SET Ordered.Discount = 0 WHERE (((Orders.OrderDate) Is Null));
  • 28. QUERIESTO DELETE • DELETE [table.]*, field_1 [,...] FROM table WHERE criteria • Example: • DELETE [Products].Discontinued FROM [Products] WHERE ((([Products].Discontinued)=Тruе)); • DROP {TABLE table | INDEX index ON table | PROCEDURE procedure |VIEW view}
  • 29. QUERIESTO CREATE A TABLE CREATE [TEMPORARY] TABLE table (field_1 type [(size)] [NOT NULL] [WITH COMPRESSION |WITH COMP] [index_1] [, field_2 тип [(size)] [NOT NULL] [index_2] [, ...]] [, CONSTRAINT complexIndex [, ...]])
  • 30. EXERCISE 1. Try to recreate the same queries for your database using SQL
  • 31. BOTTOM LINE • SQL expressions. Basic language constructs • SELECT statement. Build simple queries with selection conditions • COUNT, FIRST, LAST statistical functions • Statistical functions MIN, MAX,AVG. SUM function • Queries to add, update, delete, create a table
  • 33. SELF-TEST • What SQL standards are supported by Microsoft Access?What are the differences between them? • How to create a SQL query in Access? • List Access SQL QueryTypes
  • 34. WANT TO KNOW MORE? W3Schools SQL Tutorial https://www.w3schools.com/sql/default.asp
  • 35. WANT TO KNOW MORE? Sololearn SQL Fundamentals https://www.sololearn.com/Course/SQL/
  • 36. WANT TO KNOW MORE? SQL Course - QA https://www.slideshare.net/pingkapil/sql-course-qa