ell
Notes for Professionals
100+ pages
of professional hints and tricks
, Prerincs
GoalKicker.com ae ae te cen et
Free Programming Books alPircdlemarksandresisered wademarkears
ree gia earsContents
About
hapter 1: Getting started with SQL
Section 11: Overview
Chapter 2: Identifier
Section 21: Unguoted identifiers
Chapter 3: Data Types
31: DECIMAL and NUMERIC
‘Section 32 FLOAT and REAL
Section 33: Integers
Section 3.4 MONEY and SMALLMONEY.
‘Section 351 BINARY and VARBINARY
Section 3.6: CHAR and VARCHAR
Section 37: NCHAR ond NVARCHAR
t JOU! iE
Chapter 4: NULL 7
tion 41 Filtering for NULL in quer
Sect ble:
Section 4: Updating fields to NULL
‘Section 4.4: Inserting rows with NULL fields ..
Chapter 5: Example Databases and Tables ..
Section 5.1 Auto Shop Datobase
Section 5.2: Librory Database
Section 53: Countries Table
Chapter 6: SELECT
jection 61 Using the wildcard character to select all columns in ¢ quer
42: Nullgble columns
SNADMAAUHHEARDRARRWYNN
Section 62: SFLECT Using Column Aliases 15
Section 63: Select Individuel COIUMNS nmin 18
lon 64: Select fled number of recor 19
Section 65: Selecting with Conaition .... 20
Section 66: Selecting with CAS: a se o a se 20
0 ned after reser fa o snsnnn 21
tion 6.8: Selecting with table alas 2
Section 6 Selecting with more than 1 condition 22
on 61 ting without Locking sininnnninnninnininininonninnnnnnnnnnnnne 23
Section 61%: Selecting with Aggregate fUNCHIONS -rinnnmminmnininenimenininnnnnannnnenmnenesennies 2B
Section 612: Select with condition of multiple values from column 24
Section 613: Get agareqated resull for row groups 24
Section 614: Selection with sorted Results .
Section 6.15: Selecting with null
Section 616: Select distinct (unique values onl 28
Section 617: Select rows from multiple tables snc sn 26
Chapter 7: GROUP BY ....sonnnninmniinninnninnininininnninininennnnsnnn seonsnnnsnnnnine OT
Section 71: Basic GROUP BY example 7
Section 7.2 Filter GROUP BY results using 6 HAVING clause 28
Section 75: USE GROUP BY to COUNT the number of rows for each ynique entry in a given columa
28
Section 7.4: ROLAP agaregotion (Data Mining) 29Chapter 8: ORDER BY
Section 81: Sorting bu column number (instead of name)
with TOP to retur rows based
Section 83 Customized sorting order
Section 84: Order by Alios
Chapter 9: AND & OR Operators
‘Section 9:1 AND OR Example
Chapter 10: CASE ..
Section 101
n 103: CASE
sion 10.4: Shorthan¢
tlon 107: CASE in
Chapter 11: LIKE operator
IRDER BY cla ort
tion 111 Motch open.
Section 112: Single character match
Section 113: ESCAPE statement in the LIKE-qven
Section 114: Search for @ range of characters
Section 115: Match by range or set
Section 116: Wildcard characters
Chapter 12: IN clause
on 121: Simpl
.¢ CASE to COUNT the num
Section 102: Seorched CASE in SELECT (Matches o boolean expression)
in clause ORDER BY
AS
Ein SELECT.
lowest valu
tern
Section 12.2: Using IN clause with @ SUBQUEEY warn
Chapter 13: Filter results using WHERE and HAVING
Sect
ti WHERE ch
Section 13.4: Equal
1 Use BETWEEN to Filter Results
Section 15.2: Use HAVING with Aggregate Functions
with NOT NULL ve
ch a cor
Section 135: The WHERE clause only returns rows that mateh its erterig
‘Section 136: AND and OR
Section 157: Use IN to rei
‘ows with @ value contained in ¢ list
Section 138 Use LIKE to find matching strings and substrings
0 Zh
Section 1510: Use HAVING
o check for multiple conditions in a
Chapter 14: SKIP TAKE (Pagination)
Section 14. Limiting amount of results
Section 142: Skipping then toking some results (Pagination)
section 143: Skipping some rows {rom result
Chapter 15: EXCEPT
Section 151i Select dataset exce
where values ore
Chapter 16: EXPLAIN and DESCRIBE ..
Section 16. EXPLAIN Select quer
Section 162: DESCRIBE toblenaMe ran
Chapter 17: EXISTS CLAUSE
on 171.6
Chapter 18: JOIN
3
a
31
32
32
33
3
35,
38
36
36
36
37
37
38
39
39
40
40
41
a
a
43
44
45,
45,
46
ss 6
46
a7
a7
AB.
43.
50
50
vs 50
51
52
52
on 53
53
53
54
55.Section 18.1: Self JOIN nmin stninnnininnnnninineniinininnnnnnnenninnenns 5S
Section 182: Differences between inner/outer joins 56
Section 183: JOIN Terminologur Inner, Outer. Semi, Anti 59
Section 18.4: Left Outer Join see 69
‘Section 185: Implicit Join . vn 70
Section 186: CROSS JOIN n
Section 187: CROSS APPLY & LATERAL JOIN. eon T2
on 18.8: ft son ' oe 7B
Section 189: Recursive JOINS a . sen se sens TA
Section 18,10; Basic explicit Inner IOI neu se sa scninnnnninnnnenne TA
lon 18.1" Joining on a 75,
Chapter 19: UPDATE se 76
ction 195% UPDATE with data from another tab! 76
Section 19,2: Modifying existing valves, 7
Section 193: Undating Specified Rows ..
‘Section 19.4: Updating All Rows .. . sen so 7 7
Section 19.5: Copturing Undated record's 7
Chapter 20: CREATE Database ........ ss se se se 78
Section 20.1 CREATE Database 78
Chapter 21: CREATE TABLE 79
Section 211: Create Table From Select suo 79
on 212: Cr we sn sen ee 7 79
Section 215: CREATE TABLE With FOREIGN KEY. .sironnnnnnn seni 73
lon 215: Create o Temporary or In-Memory TabIE snes smninsnsnninnninennsnennsnsnne 80
Chapter 22: CREATE FUNCTION ... se o ss 82
‘Saction 22:1 Create a new Function 82
Chapter 23: TRY/CATCH .csininninnnnnininininmininininnnnninnnnnininmninnnnnnnnnnnnnen 8B
Section 231: Transaction in a TRY/CATC 83
ster 24: UNION / UNION ALL
Section 241: Bosic UNION ALL quer 84
85
Chapter 25: ALTER TABLE
Section 251: Add Column(s)
Section 25.2: Drop Column
Section 25.3: Add Primary Ke
Section 254: Alter Colun
Chapter 26: INSERT .. sn vo
Section 261: INSERT data from another table using SELECT
Section 262 Insert New Row ..
Section 264: Insert multiple cows at once
Chapter 27: MERGE ....... o
Section 27.1 MERGE to make Target match Sour
Section 272: MySQL: counting users by name ...
jection 27°3 PostgreSOl: counting users by nam
Chapter 28: cross apply, outer apply
Section 28.1 CROSS APPLY and QUTER APPLY basics...Chapter 29: DELETE 22
291: DELETE all rows 92
9. iain rows with W sn 92
293 TRUNCATE clause 92
Section 294: DELETE certain rows bosed upon comparisons with other tables 92
Chapter 30: TRUNCATE 94
Section 30.1: Removing all rows from th: nnn vanes 94
Chapter 31: DROP Table 95,
section 311: Check for existence before dronpin: sen son smnennnnnne 95
‘Section 312 Simple drop 95,
Chapter 32: DROP or DELETE Database .......c0n o a o 96
Sect 96
hapter 33: a — a 7
Section 351: ON DELETE CASCADE 7
Chapter 34: GRANT and REVOKE 9
Section 341 Grant/revoke privileges 99
Chapter 35: XML 100
Section 35.1 Query from XML Dota Type -uinmnnnninmininininuiinninnnnnninnnmniennnnnnnnn 100
Chapter 36: Primary Keys 101
action 36%: Creating @ PAMAPY KEY nnsnnninmninmininenimnnnninminnninennnnnmnnnnnnnnnnns 101
Section 362: Using Auto Increment 101
Chapter 37: Indexes 102
Section 371 Sorted index 102
Section 3, 1102
jection 375. Creating dA INGEX nimmnmnmnmninmenininnnsnnannnanineninennmnnnnnnnanineneninenrnennne 102
Section 37.4: Dropping on Index or Disabling and Rebuilding it 103
Section 375: Clustered, Unique, and Sorted Indexes 103
‘Saction 32.6 Rebulld index smn ve se 104
Section 377: Inserting with 0 Unique Index 104
Chapter 38: Row number seven 105
Section 38.1 Delete All But Lost Record (1 to Many Table) 105
Section 382: Row numbers without partitions ssiinminminininineninimninnninnnnmnninennennnnsnnnnn 105
Section 38.3: Row numbers with partitions snes smn 105
Chapter 39: SOL Group By vs Distinct 106
Section 39.1 Difference between Gi 106
Chapter 40: Finding Duplicates on a Column Subset with Detail 107
Section 40 St with some name and dote of birth 107
Chapter 41: String Functions 108
Section 411: Concatenat 108
Section 412: Lenat! sinnnnninniinniiiinnninninnnnnininninnnnnnnnnennnnnns 108
Section 413: Trim empty spaces. svar . 109
Section 414: Upper & lower case 109
Section 415: Split rnin o oe sannnnnnenenenrneesee 109
Section 416 Replace 110
417. REGEXP 110
Section 418: Substri 110
SOCIO 419: SUE sasnmninmenninnninininmninnnenennsenn st — senninesnnen VIO
Section 410: LEFT - RIGHT 110REVERSE
REPLICATE
Section 4115: PARSENAME sso
Chapter 42: Functions (Aggregate)
422: Uist Concatenation
423. SUM
Section 42.4 AVGO
Section 425: Cour
Se
sclion 42.6 Min
Section 427: Max.
Chapter 43: Functions (Scalar/Single Row) ..
4511 Date And Time
43.2: Character
Section 433: Configuration and Conversion Function ..
Section 43.4: Logical and Mathmetical Funct
Chapter 44: Functions (Analutic)
Section 441: LAG and LEAD
Section 442: PERCENTILE DISC ond PERCENTILE CONT
Section 443: FIRST VALUE
Section 444 LAST VALUE
445: PERCENT RANK and CUME DIST
Sect
Chapter 45: Window Functions
fications
her rows have a commen py
vence" records using the LAGO function
Section 45.3: Getting o running total
Section 45.4: Adding the total rows selected to every row os
Section 4555: Getting the N most recent rows over multiple grouping
Chapter 46: Common Table Expressions
Section 46.1 generating values
Section 46.2 recursively enumerating a subtree
Section 463: Temporary quer
Section 46.4: recursively going up IN BOE . . vo
Section 46.5: Recursively generate dates. extended to include team rostering as example
Section 46.6: Oracle CONNECT BY functionality with recursive CTES
Chapter 47: Views
Section 4711 Simple views ..
Section 47.2: Complex views
hapter 48: Materialized View:
Section 48.1: PostoreSOL example
Chapter 49: Comments
Section 4911 Single-line comments
Chapter 50: Foreign Keys ..
Section 50.1 Foreign Keys explainec
Section 50,2: Creating a table with a foreign ke
Chapter 51: Sequence
m1
m1
1
2
2
114
114
14
116
116
116
M7
8
119
19
120
120
121
123
123
123,
vo 124
125
125
127
127
127
128
128
129
130
130
130
131
131
132
132
134
134
134
135
135
136
136
136
137
137
137
139Section 511: Create Sequence
Section 512: Using Sequences
Chapter 52: Subaveries . .
Section 521: Subquery in FROM clause
Section 52.2: Subquery in SELECT clause
section 5; very in WH
Section 52.6: Subqueries in FROM clause ..
Section 52.7: Subqueries in WHERE clause
hapter 53: Execution block:
Section 531: Using BEGIN. END
Chapter 54: Stored Procedures
in" for
Chapter 56: Transactions ....
jection 5611 Simple Transaction
Sectio
Chapter 57: Table Design
Section 57.1 Properties of a well designed table
Chapter 58: Synonyms
Section 58.1 Creote Synonym .
Chapter 59: Information Schema
Section 59.1 Basic Information Schema Seore!
Chapter 60: Order of Execution
section 601 Logical Order of Query Processing in SOL
Chapter 61: Clean Code in SQL sn
Section 61: Formatting and Spelling of Keywords and Names
Section 612: indenting
n 613: SELECT"
562: Rollback Transaction
Section 61,4: Join se
Chapter 62: SOL Injection ...
Section 621: SO injection sample
Section 62.2: simple injection somph
Credits
You may also like
139
139
140
140
140
140
140
140
141
1a
142
142
143
143
144
144
14a
145
145
145
146
146
147
147
148
148
149
149)
150
150
150
151
152
153
153
154
155
159About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/SQLBook
This SQL Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official SQL group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
‘The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to [email protected]
Goolkicker-com - SQL Notes for Professionals,Chapter 1: Getting started with SQL
Version Short Name Standard Release Date
1986 — SQL-86 ANSI X3.135-1986, ISO 9075:1987, 1986-01-01
1989 SQL-89 ANSI X3,135-1989, ISO/IEC 9075:1989 1989-01-01
1992 SQL-92 ISOMEC 9075:1992 1992-01-01
1999 $QL:1999— ISOMEC 9075:1999 1999-12-16
2003 $QL:2003_ISOMEC 9075:2003 2003-12-15
2005 SQL2006 ISO/IEC 9075:2006, 2006-06-01
(2008 = $QL:2008 ~— ISOMEC 9075:2008 2008-07-15,
2011 sQu2011_IsONEC 9075:2011 2011-12415
2016 SQL2016 ISO/EC 9075:2015, 2016«12-01
Section 1.1: Overview
Structured Query Language (SQL) is a special-purpose programming language designed for managing data held in a
Relational Database Management System (RDBMS). SQL-like languages can also be used in Relational Data Stream
Management Systems (RDSMS), or in "not-only SQL” (NoSQL) databases.
‘SQL comprises of 3 major sub-languages
1. Data Definition Language (DDL): to create and modify the structure of the database;
2. Data Manipulation Language (DML): to perform Read, Insert, Update and Delete operations on the data of
the database;
3. Data Control Language (DCL): to control the access of the data stored in the database.
SOL article on Wikipedia
‘The core DML operations are Create, Read, Update and Delete (CRUD for short) which are performed by the
statenents INSERT, SELECT, UPDATE and DELETE.
There is also a (recently added) MERGE statement which can perform all 3 write operations (INSERT, UPDATE,
DELETE),
CRUD article on Wikipedia
Many SQL databases are implemented as client/server systems; the term "SQL server" describes such a database.
‘At the same time, Microsoft makes a database that is named "SQL Server". While that database speaks a dialect of
SQL. information specific to that database is not on topic in this tag but belongs into the SQL Server documentation,
Goolkicker-com - SQL Notes for Professionals, 2Chapter 2: Identifier
‘This topic is about identifiers, ie. syntax rules for names of tables, columns, and other database objects.
Where appropriate, the examples should cover variations used by different SQL implementations, or identify the
‘SQL implementation of the example.
Section 2.1: Unquoted identifiers
Unquoted identifiers can use leters (a2), digits (28), and underscore (.), and must start with a letter
Depending on SQL implementation, and/or database settings, other characters may be allowed, some even as the
first character, e.g.
MS SQL: 8 §, #, and other Unicode letters (source
MySQL: $ (source)
Oracle: §, #, and other letters from database character set (source
PostgreSQL. §, and other Unicode letters (source)
Unquoted identifiers are case-insensitive. How this is handled depends greatly on SQL implementation:
+ MS SQL: Case-preserving, sensitivity defined by database character set, so can be case-sensitive
MySQL: Case-preserving, sensitivity depends on database setting and underlying file system.
Oracle: Converted to uppercase, then handled like quoted identifier.
PostgreSQL: Converted to lowercase, then handled like quoted identifier
SQLite: Case-preserving; case insensitivity only for ASCII characters.
Goolkicker-com - SQL Notes for Professionals,Chapter 3: Data Types
Section 3.1: DECIMAL and NUMERIC
Fixed precision and scale decimal numbers. DECIMAL. and NUNERIC are functionally equivalent.
Syntax:
DECIMAL ( precision | , scale
NUMERIC ( precision | | scale
Examples:
SELECT CAST(123. AS DECIMAL(S,2)) --returns 123.00
SELECT CAST(12345.12 AS NUMERIC(1®, 5)) --returns 12345.12000
Section 3.2: FLOAT and REAL
Approximate-number data types for use with floating point numeric data,
SELECT CAST( PI() AS FLOAT) --returns 3.14159265358079
SELECT CAST( PI() AS REAL) ~-returns 9.141893,
Section 3.3: Integers
Exact-number data types that use integer data.
Data type Range Storage
bigint —-2%63 (-9,223,372,036,854,775,808) to 2%63-1 (9,223,372,036,854,775,807) 8 Bytes
int 2931 (2,147 483,648) to 2931-1 (2,147,483,647) 4 Bytes
smallint -215 (-32,768) to 2415-1 (32,767) 2 Bytes
tinyint 0 t0 255, 1 Byte
Section 3.4: MONEY and SMALLMONEY
Data types that represent monetary or currency values,
Data type Range Storage
money _-922,337,203,685,477.5808 to 922,337,203,685,477.5807 & bytes
smallmoney -214,748,3648 to 214,748.3647 bytes
Section 3.5: BINARY and VARBINARY
Binary data types of either fixed length or variable length,
syntax:
BINARY [ ( nbytes )
VARBINARY [ ( nbytes | max ) ]
n_hytes can be any number from 1 to 8000 bytes, max indicates that the maximum storage space Is 2431-1
Goolkicker-com - SQL Notes for Professionals,Examples:
SELECT CAST(12345 AS BINARY(1@)) -- exoeaaee0e000008003039
SELECT CAST(12345 AS VARBINARY(16)) -- @x00803039
Section 3.6: CHAR and VARCHAR
String data types of either fixed length or variable length.
syntax:
CHAR [ ( nchars ) |
VARCHAR [ ( nchars ) |
Examples:
SELECT CAST(*ABC' AS CHAR(10)) -- ‘ABC (padded with spaces on the right)
SELECT CAST("ABC' AS VARCHAR(1@)) ~~ ‘ABC’ (no padding due to variable character)
SELECT CAST(*ABCOEFGHIJKLNNOPORSTUVWKYZ' AS CHAR(1)) -- ‘ABCDEFGHIJ' (truncated to 1@ characters)
Section 3.7: NCHAR and NVARCHAR
UNICODE string data types of either fixed length or variable length,
syntax:
NCHAR [ ( nchars )
NVARCHAR [ ( nchars | MAX )
Use WX for very long strings that may exceed 8000 characters.
Section 3.8: UNIQUEIDENTIFIER
A 16-byte GUID / UID.
DECLARE @GUID UNTQUEIDENTIFIER = NEWID()
SELECT @GUID -- "E28B3BD9-9174~41A9-B508-B99A78A39540"
DECLARE @bad_GUTD_string VARCHAR(100) = ‘£2889BD9-9174-41A9-8508-899A78A33540_foobarbaz
SELECT
@bad_GUID_string, ~~ '£2863BD9-9174-41A9-8508-899A78A33540_foobarbaz
CONVERT (UNIQUEIDENTIFIER, @bad_GUID_string) -~ 'E28B3BD9-9174-41A9-8508-899A7EAI9540
Goolkicker-com - SQL Notes for Professionals, 5Chapter 4: NULL
NULL in SQL, as well as programming in general, means literally "nothing". In SQL, itis easier to understand as “the
absence of any value"
Itis important to distinguish it from seemingly empty values, such as the empty string ** or the number 8, neither
‘of which are actually NULL.
Itis also important to be careful not to enclose NULL in quotes, like "NULL’, which is allowed in columns that accept
text, but is not NULL and can cause errors and incorrect data sets
Section 4.1: Filtering for NULL in queries
The syntax for filtering for NULL (ie. the absence of a value) in WHERE blocks is slightly different than filtering for
specific values.
SELECT * FROM Employees WHERE ManagerTd IS NULL
SELECT * FROM Employees WHERE ManagerId IS NOT NULL
Note that because NULL is not equal to anything, not even to itself, using equality operators = NULL or <> NULL (or
= NULL) will always yield the truth value of UNKNOWN which will be rejected by WHERE.
WHERE fters all rows that the condition is FALSE or UKNOWN and keeps only rows that the condition is TRUE.
Section 4.2: Nullable columns in tables
When creating tables itis possible to declare a column as nullable or non-nullable.
CREATE TABLE MyTable
- non=nullable
nullable
MyCol1 INT NOT NULL,
MyCol2 INT NULL
By default every column (except those in primary key constraint) is nullable unless we explicitly set NOT NULL
constraint,
Atternpting to assign NUL to a non-nullable column will result in an error.
INSERT INTO MyTable (MyCol1, MyCol2) VALUES (1, NULL) ; ~~ works fine
INSERT INTO MyTable (MyCol1, MyCol2) VALUES (NULL, 2)
cannot inse
the value NULL into column ‘MyCol1', table ‘MyTable
column does not allow nulls. INSERT fails.
Section 4.3: Updating fields to NULL
Setting afield to NULL works exactly lke with any other value:
UPDATE Employees
SET ManagerId = NULL
WHERE Td = 4
Goolkicker-com - SQL Notes for Professionals,Section 4.4: Inserting rows with NULL fields
For example inserting an employee with no phone number and no manager into the Employees example table:
INSERT INTO Employees
(Id, FName, Lame, PhoneNunber, MenagerId, DepartmentId, Salary, HireDate)
VALUES
(5, ‘Jane’, ‘Doe’, NULL, NULL, 2, 888, '2016-07-22")
Goolkicker-com - SQL Notes for Professionals,Chapter 5: Example Databases and Tables
Section 5.1: Auto Shop Database
In the following example - Database for an auto shop business, we have a list of departments, employees,
‘customers and customer cars, We are using foreign keys to create relationships between the various tables.
Live example: SOL fiddle
Relationships between tables
‘+ Each Department may have 0 or more Employees
‘+ Each Employee may have 0 or 1 Manager
* Each Customer may have 0 or more Cars
Departments
Id Name
1 HR
2 Sales
3 Tech
‘SQL statements to create the table:
CREATE TABLE Departments (
Td INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(25) NOT NULL.
PRIMARY KEV(Td)
INSERT INTO Departments
[14], [Name]
VALUES
1, CHR)
(2, ‘sales')
(3, ‘Tech’
Employees
IdFName LName PhoneNumber Managerld Departmentid Salary HireDate
1 James Smith 1234567890 NULL 1 1000 01-01-2002
2 John Johnson 24681012141 1 400. 23-03-2005,
3 Michael Williams 13579111311 2 600 12-05-2009
4 Johnathon Smith 12121212122 1 500 24-07-2016
‘SQL statements to create the table:
CREATE TABLE Employees (
Id INT NOT NULL AUTO_INCREMENT,
FName VARCHAR(35) NOT NULL,
LName VARCHAR(35) NOT NULL,
PhoneNunber VARCHAR(11)
Managertd INT
DepartmentId INT NOT NULL,
Goolkicker-com - SQL Notes for Professionals,Salary INT NOT NULL
HireDate DATETIME NOT NULL
PRIMARY KEY(Id)
FOREIGN KEY (NanagerId) REFERENCES Employees(Id)
FOREIGN KEY (DepartmentId) REFERENCES Departments (Id)
INSERT INTO Enployees
((1d), [FName), [LName), [PhoneNunber), [ManagerId), [Departmentid), (Salary
VALUES
(1, ‘James", ‘Smith’, 1234567890, NULL, 1, 1808, '@1-01-2002")
2, ‘John’, ‘Johnson’, 2468101214, '1', 1, 408, '23-03-2605')
(3, ‘Michael’, ‘Willians’, 1957911191, °1°, 2, 608, '12-@5-2009")
4, ‘Johnathon’, ‘Smith, 1212121212, '2', 1, 588, '24-07-2016")
Customers
Id FName LName Email PhoneNumber PreferredContact
1 William Jones william [email protected] 3347927472 PHONE
2 David Miller [email protected] 2137921892 EMAIL
3 Richard Davis [email protected] NULL EMAIL
‘SQL statements to create the table:
CREATE TABLE Customers (
Id INT NOT NULL AUTO_INCREMENT,
FName VARCHAR(35) NOT NULL.
UName VARCHAR(35) NOT NULL.
Email verchar(108) NOT NULL.
PhoneNunber VARCHAR(11)
PreferredContact VARCHAR(5) NOT NULL.
PRIMARY KEY(Id)
INSERT INTO Customers
((Td], [FName}, (LName), [Email], [PhoneNunber}, [PreferredContact])
VALUES
(1, ‘Willian’, "Jones", ‘william. [email protected]’, "3347927472", "PHONE
2. ‘David’, ‘Miller’, ‘dmillergexample.net', '2137921892', ' EMATL’
(3, ‘Richard’, ‘Davis’, ‘richard®1238exanple.com’, NULL, ‘EMAIL’
cars
Id Customerld Employeeld Model Status Total Cost
4 2 FordF-150 READY 230
21 2 FordF-150 READY 200
32 1 Ford Mustang WAITING 100
43 3 Toyota Prius WORKING 1254
‘SQL statements to create the table:
CREATE TABLE Cars (
Td INT NOT NULL AUTO_INCREMENT,
CustomerId INT NOT NULL
Enployeetd INT NOT NULL
Model verchar(5@) NOT NULL
Status varchar(25) NOT NULL
HireDate))
Goolkicker-com - SQL Notes for Professionals,TotalCost INT NOT NULL
PRIMARY KEY(Id)
FOREIGN KEY (CustomerId) REFERENCES Customers (Id
FOREIGN KEY (EmployeeId) REFERENCES Enployees(Id)
INSERT INTO Cars
[Id], [Customertd], [Employed], [Model], [Status], [TotalCost))
VALUES
15, (11, '2', "Ford F-158", 'READY', '238")
2° 1", 12) "Ford F-158", "READY’, '208"
3°, '2', ‘1, ‘Ford Mustang’, ‘WAITING’, '160")
(14", °3", 13") "Toyota Prius’, "WORKING, '1254")
Section 5.2: Library Database
In this example database fora library, we have Authors, Books and BooksAuthors tables.
Live example: SOL fiddle
Authors and Books are known as base tables, since they contain column definition and dats for the actual entities in
the relational model. BooksAuthors is known as the relationship table, since this table defines the relationship
between the Books and Authors table.
Relationships between tables
‘+ Each author can have 1 or more books
* Each book can have 1 or more aut!
Authors
(View table)
IdName Country
1 J.D.Salinger USA
2 F. Scott. Fitzgerald USA
3 Jane Austen UK
4 Scott Hanselman USA
5 Jason N. Gaylord USA
6 Pranav Rastogi India
7 Todd Miranda USA
8 Christian Wenz USA
SQL to create the table:
CREATE TABLE Authors
Id INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(7@) NOT NULL.
Country VARCHAR(1@@) NOT NULL.
PRIMARY KEY(Id)
INSERT INTO Authors
Goolkicker-com - SQL Notes for Professionals, 70(Name, Country)
VALUES
(J.D. Salinger’, “USA')
°F, Scott. Fitzgerald’, ‘USA
“Jane Austen’, "UK")
“Scott Hanselman’, 'USA’)
“Jason N. Gaylord’, “USA')
“Pranay Rastogi’, ‘India')
“Todd Miranda’, ‘USA’
“christian Wenz’, ‘USA')
Books
laTitle
The Catcher in the Rye
Nine Stories
Franny and Zooey
Tender id the Night
Pride and Prejudice
Professional ASP.NET 4.5 in C# and VB.
1
2
3
4 The Great Gatsby
5
6
7
SQL to create the table:
CREATE TABLE Books (
Id INT NOT NULL AUTO_INCREMENT.
Title VARCHAR(S®) NOT NULL
PRIMARY KEY (Id)
INSERT INTO Books
(Id, Title)
VALUES
qa
“The Catcher in the Rye")
2, ‘Nine Stories’)
(3, ‘Franny and Zooey’)
(4, ‘The Great Gatsby")
(S. ‘Tender id the Night")
(6, ‘Pride and Prejudice’),
(7, "Professional ASP.NET 4.5 in C# and VB")
BooksAuthors
(view table)
Bookld Authorid
1
ween
1
Goolkicker-com - SQL Notes for Professionals,evaune
SQL to create the table:
CREATE TABLE BooksAuthors (
‘Authorid INT NOT NULL
BookId INT NOT NULL.
FOREIGN KEY (AuthorId) REFERENCES Authors(Id)
FOREIGN KEY (BookId) REFERENCES Books( Id)
INSERT INTO BooksAuthors
(BookId, Authorid)
VALUES
(1)
(2.1)
3.1)
(4 2)
5, 2)
(6 3)
7.4)
78
7. 6)
@.
7
Examples
View all authors (view live example):
SELECT * FROM Authors:
View all book titles (view live example):
SELECT * FROM Books
View all books and their authors (view live example!
SELECT
ba. Authorid
@.Neme AuthorNane,
ba. BookId:
b.Title BookTitle
FROM BooksAuthors ba
INNER JOIN Authors @ ON a.id = ba.authorid
INNER JOIN Books b ON b.id = ba.bookid
Goolkicker-com - SQL Notes for Professionals,Section 5.3: Countries Table
In this example, we have a Countries table. A table for countries has many uses, especially in Financial applications
involving currencies and exchange rates.
Live example: SOL fiddle
‘Some Market data software applications like Bloomberg and Reuters require you to give their API either a 2 or 3
character country code along with the currency cade. Hence this example table has bath the 2-character 180 code
column and the 3 character 1803 code columns.
Countries
view table)
Id IS0 1SO3 ISONumeric CountryName Capital __ContinentCode CurrencyCode
1 AU AUS 36 Australia Canberra. OC AUD
2 DE DEU 276 Germany Berlin. EU EUR
2 IN IND 356 India New Delhi AS INR
3 LA LAO 418 Laos Vientiane AS LAK
4 US USA 840 United States Washington NA usp
5 ZW 2WE 716, Zimbabwe Harare. A Ze
SQL to create the table:
CREATE TABLE Countries (
Id INT NOT NULL AUTO_INCREMENT,
TSO VARCHAR(2) NOT NULL
1803 VARCHAR(3) NOT NULL
Ts0Numerie INT NOT NULL
CountryName VARCHAR(64) NOT NULL.
Capital VARCHAR(64) NOT NULL,
ContinentCode VARCHAR(2) NOT NULL
CurrencyCode VARCHAR(3) NOT NULL,
PRIMARY KEY(Td)
INSERT INTO Countries
(180, 1803, ISONumeric, CountryName, Capital, ContinentCode, CurrencyCode)
VALUES
(AU', "AUS", 96, “Australia’, ‘Canberra’, ‘Oc’, “AUD')
DE", "DEU', 276, ‘Germany’, ‘Berlin’, "EU', ‘EUR')
COIN", "IND", 956, "India", ‘New Delhi", “AS, "INR")
LA", "LAO", 418, ‘Laos’, ‘Vientiane’, 'AS', ‘LAK')
(US", "USA", 849, ‘United States’, ‘Washington’, ‘NA’, "USD"
ZW’, '7WE'| 716, ‘Zimbabwe’, ‘Harare’, "AF", ‘ZWL"
Goolkicker-com - SQL Notes for Professionals, 3Chapter 6: SELECT
‘The SELECT statement is at the heart
f most SQL queries. It defines what result set should be returned by the
query, and is almost always used in conjunction with the FROM clause, which defines what part(s) of the database
should be queried,
Section 6.1: Using the wildcard character to select all columns
in a query
Consider a database with the following two tables.
Employees tabl
Id FName LName Deptid
1 James smith 3
2 John Johnson 4
Departments table:
ld Name
1 Sales
2 Marketing
3 Finance
4a
‘Simple select statement
sisthe
{card character used to select all available columns in a table,
When used as a substitute for explicit column names, it returns all columns in all tables that a query is selecting,
FROM, This effect applies to all tables the query accesses through its JOIN clauses,
Consider the following query:
SELECT * FROM Employees
It will return all fields of all rows of the Employees table:
Id FName LName Deptid
1 James smith 3
2 John Johnson 4
Dot notation
To select all values from a specific table, the wildcard character can be applied to the table with dot notation,
Consider the following query:
SELECT
Employees.
Departments. Nane
FROM
Enployees
JOIN
Goolkicker-com - SQL Notes for Professionals,Departments
ON Departments. Id = Enployees.Deptid
This will return a data set with all fields on the Employee table, followed by just the Nane field in the Departments
table:
Id FName LName Deptid Name
1 James smith 3 Finance
2 John Johnson4 IT
Warnings Against Use
Itis generally advised that using + is avoided in production code where possible, as it can cause a number of
potential problems including:
1. Excess 10, network load, memory use, and so on, due to the database engine reading data that is not needed
and transmitting it to the front-end code. This is particularly a concern where there might be large fields such
as those used to stare long notes or attached files.
2. Further excess 10 load if the database needs to spool internal results to disk as part of the processing for a
query more complex than SELECT FROM