SlideShare a Scribd company logo
1 of 36
Download to read 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

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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)
 

More from 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
 

More from 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.Сколько стоит облако
 

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
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
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Recently uploaded (20)

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
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
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

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