Uso de SQL
Uso de SQL
IN A
DATABASE
Sumario
Introduction to SQL............................................................................................................................12
What is SQL?.................................................................................................................................12
What Can SQL do?........................................................................................................................12
SQL is a Standard - BUT...............................................................................................................12
Using SQL in Your Web Site.........................................................................................................12
RDBMS.........................................................................................................................................13
Example....................................................................................................................................13
SQL Syntax.........................................................................................................................................13
Database Tables.............................................................................................................................13
SQL Statements.............................................................................................................................14
Example....................................................................................................................................14
Keep in Mind That.........................................................................................................................14
Semicolon after SQL Statements?.................................................................................................14
Some of The Most Important SQL Commands.............................................................................14
SQL SELECT Statement....................................................................................................................15
The SQL SELECT Statement........................................................................................................15
SELECT Syntax........................................................................................................................15
Demo Database..............................................................................................................................15
SELECT Column Example............................................................................................................16
Example....................................................................................................................................16
SELECT * Example.......................................................................................................................16
Example....................................................................................................................................16
SQL WHERE Clause..........................................................................................................................16
The SQL WHERE Clause..............................................................................................................16
WHERE Syntax........................................................................................................................16
Demo Database..............................................................................................................................16
WHERE Clause Example..............................................................................................................17
Example....................................................................................................................................17
Text Fields vs. Numeric Fields......................................................................................................17
Example....................................................................................................................................17
Operators in The WHERE Clause.................................................................................................17
SQL AND, OR and NOT Operators...................................................................................................17
The SQL AND, OR and NOT Operators.......................................................................................18
AND Syntax..............................................................................................................................18
OR Syntax.................................................................................................................................18
NOT Syntax..............................................................................................................................18
Demo Database..............................................................................................................................18
AND Example................................................................................................................................20
Example....................................................................................................................................20
OR Example...................................................................................................................................20
Example....................................................................................................................................20
Example....................................................................................................................................21
NOT Example................................................................................................................................21
Example....................................................................................................................................21
Combining AND, OR and NOT....................................................................................................21
Example....................................................................................................................................21
Example....................................................................................................................................21
SQL ORDER BY Keyword................................................................................................................21
Página 1 de 132
The SQL ORDER BY Keyword....................................................................................................21
ORDER BY Syntax...................................................................................................................22
Demo Database..............................................................................................................................22
ORDER BY Example....................................................................................................................22
Example....................................................................................................................................22
ORDER BY DESC Example.........................................................................................................22
Example....................................................................................................................................22
ORDER BY Several Columns Example........................................................................................23
Example....................................................................................................................................23
ORDER BY Several Columns Example 2.....................................................................................23
Example....................................................................................................................................23
SQL INSERT INTO Statement...........................................................................................................23
The SQL INSERT INTO Statement...............................................................................................23
INSERT INTO Syntax..............................................................................................................23
Demo Database..............................................................................................................................23
INSERT INTO Example................................................................................................................24
Example....................................................................................................................................24
Insert Data Only in Specified Columns.........................................................................................24
Example....................................................................................................................................24
SQL NULL Values..............................................................................................................................25
What is a NULL Value?.................................................................................................................25
How to Test for NULL Values?.....................................................................................................25
IS NULL Syntax........................................................................................................................25
IS NOT NULL Syntax..............................................................................................................25
Demo Database..............................................................................................................................25
The IS NULL Operator..................................................................................................................26
Example....................................................................................................................................26
The IS NOT NULL Operator.........................................................................................................26
Example....................................................................................................................................26
SQL UPDATE Statement...................................................................................................................26
The SQL UPDATE Statement.......................................................................................................26
UPDATE Syntax.......................................................................................................................26
Demo Database..............................................................................................................................27
UPDATE Table..............................................................................................................................27
Example....................................................................................................................................27
UPDATE Multiple Records...........................................................................................................28
Example....................................................................................................................................28
Update Warning!............................................................................................................................28
Example....................................................................................................................................28
SQL DELETE Statement....................................................................................................................29
The SQL DELETE Statement........................................................................................................29
DELETE Syntax.......................................................................................................................29
Demo Database..............................................................................................................................29
SQL DELETE Example.................................................................................................................29
Example....................................................................................................................................29
Delete All Records.........................................................................................................................30
Example....................................................................................................................................30
SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause..................................................................30
The SQL SELECT TOP Clause.....................................................................................................30
Demo Database..............................................................................................................................31
Página 2 de 132
SQL TOP, LIMIT and FETCH FIRST Examples..........................................................................31
Example....................................................................................................................................31
Example....................................................................................................................................32
Example....................................................................................................................................32
SQL TOP PERCENT Example......................................................................................................32
Example....................................................................................................................................32
Example....................................................................................................................................32
ADD a WHERE CLAUSE............................................................................................................32
Example....................................................................................................................................32
Example....................................................................................................................................32
Example....................................................................................................................................33
SQL MIN() and MAX() Functions.....................................................................................................33
The SQL MIN() and MAX() Functions.........................................................................................33
MIN() Syntax............................................................................................................................33
MAX() Syntax...........................................................................................................................33
Demo Database..............................................................................................................................33
MIN() Example..............................................................................................................................33
Example....................................................................................................................................33
MAX() Example............................................................................................................................34
Example....................................................................................................................................34
SQL COUNT(), AVG() and SUM() Functions...................................................................................34
The SQL COUNT(), AVG() and SUM() Functions.......................................................................34
COUNT() Syntax......................................................................................................................34
AVG() Syntax............................................................................................................................34
SUM() Syntax...........................................................................................................................34
Demo Database..............................................................................................................................34
COUNT() Example........................................................................................................................35
Example....................................................................................................................................35
AVG() Example.............................................................................................................................35
Example....................................................................................................................................35
Demo Database..............................................................................................................................35
SUM() Example.............................................................................................................................35
Example....................................................................................................................................35
SQL LIKE Operator...........................................................................................................................36
The SQL LIKE Operator...............................................................................................................36
LIKE Syntax.............................................................................................................................36
Demo Database..............................................................................................................................37
SQL LIKE Examples.....................................................................................................................38
Example....................................................................................................................................38
Example....................................................................................................................................38
Example....................................................................................................................................39
Example....................................................................................................................................39
Example....................................................................................................................................39
Example....................................................................................................................................39
Example....................................................................................................................................39
SQL Wildcards....................................................................................................................................39
SQL Wildcard Characters..............................................................................................................39
Wildcard Characters in MS Access...........................................................................................40
Wildcard Characters in SQL Server..........................................................................................40
Demo Database..............................................................................................................................40
Página 3 de 132
Using the % Wildcard....................................................................................................................42
Example....................................................................................................................................42
Example....................................................................................................................................42
Using the _ Wildcard.....................................................................................................................42
Example....................................................................................................................................42
Example....................................................................................................................................43
Using the [charlist] Wildcard.........................................................................................................43
Example....................................................................................................................................43
Example....................................................................................................................................43
Using the [!charlist] Wildcard........................................................................................................43
Example....................................................................................................................................43
Example....................................................................................................................................43
SQL IN Operator................................................................................................................................43
The SQL IN Operator....................................................................................................................43
IN Syntax..................................................................................................................................44
Demo Database..............................................................................................................................44
IN Operator Examples...................................................................................................................46
Example....................................................................................................................................46
Example....................................................................................................................................46
Example....................................................................................................................................46
SQL BETWEEN Operator.................................................................................................................46
The SQL BETWEEN Operator.....................................................................................................46
BETWEEN Syntax...................................................................................................................46
Demo Database..............................................................................................................................46
BETWEEN Example.....................................................................................................................47
Example....................................................................................................................................47
NOT BETWEEN Example............................................................................................................47
Example....................................................................................................................................47
BETWEEN with IN Example........................................................................................................47
Example....................................................................................................................................47
BETWEEN Text Values Example..................................................................................................47
Example....................................................................................................................................47
Example....................................................................................................................................48
NOT BETWEEN Text Values Example........................................................................................48
Example....................................................................................................................................48
Sample Table..................................................................................................................................48
BETWEEN Dates Example...........................................................................................................48
Example....................................................................................................................................48
Example....................................................................................................................................48
SQL Aliases........................................................................................................................................49
SQL Aliases...................................................................................................................................49
Alias Column Syntax................................................................................................................49
Alias Table Syntax....................................................................................................................49
Demo Database..............................................................................................................................49
Alias for Columns Examples.........................................................................................................49
Example....................................................................................................................................50
Example....................................................................................................................................50
Example....................................................................................................................................50
Alias for Tables Example...............................................................................................................50
Example....................................................................................................................................50
Página 4 de 132
Example....................................................................................................................................50
SQL Joins............................................................................................................................................51
SQL JOIN......................................................................................................................................51
Example....................................................................................................................................51
Different Types of SQL JOINs......................................................................................................52
SQL INNER JOIN Keyword..............................................................................................................52
SQL INNER JOIN Keyword.........................................................................................................52
INNER JOIN Syntax.................................................................................................................52
Demo Database..............................................................................................................................53
SQL INNER JOIN Example..........................................................................................................53
Example....................................................................................................................................53
JOIN Three Tables.........................................................................................................................53
Example....................................................................................................................................53
SQL LEFT JOIN Keyword.................................................................................................................54
SQL LEFT JOIN Keyword............................................................................................................54
LEFT JOIN Syntax...................................................................................................................54
Demo Database..............................................................................................................................54
SQL LEFT JOIN Example.............................................................................................................55
Example....................................................................................................................................55
SQL RIGHT JOIN Keyword..............................................................................................................55
SQL RIGHT JOIN Keyword.........................................................................................................55
RIGHT JOIN Syntax.................................................................................................................55
Demo Database..............................................................................................................................55
SQL RIGHT JOIN Example..........................................................................................................56
Example....................................................................................................................................56
SQL FULL OUTER JOIN Keyword..................................................................................................56
SQL FULL OUTER JOIN Keyword.............................................................................................56
FULL OUTER JOIN Syntax.....................................................................................................56
Demo Database..............................................................................................................................57
SQL FULL OUTER JOIN Example..............................................................................................57
SQL Self Join......................................................................................................................................57
SQL Self Join.................................................................................................................................57
Self Join Syntax........................................................................................................................58
Demo Database..............................................................................................................................58
SQL Self Join Example..................................................................................................................58
Example....................................................................................................................................58
SQL UNION Operator........................................................................................................................58
The SQL UNION Operator............................................................................................................58
UNION Syntax..........................................................................................................................59
UNION ALL Syntax.................................................................................................................59
Demo Database..............................................................................................................................59
SQL UNION Example...................................................................................................................59
Example....................................................................................................................................60
SQL UNION ALL Example...........................................................................................................60
Example....................................................................................................................................60
SQL UNION With WHERE..........................................................................................................60
Example....................................................................................................................................60
SQL UNION ALL With WHERE..................................................................................................60
Example....................................................................................................................................60
Another UNION Example.............................................................................................................61
Página 5 de 132
Example....................................................................................................................................61
SQL GROUP BY Statement...............................................................................................................61
The SQL GROUP BY Statement...................................................................................................61
GROUP BY Syntax...................................................................................................................61
Demo Database..............................................................................................................................61
SQL GROUP BY Examples..........................................................................................................62
Example....................................................................................................................................62
Example....................................................................................................................................62
Demo Database..............................................................................................................................62
GROUP BY With JOIN Example..................................................................................................63
Example....................................................................................................................................63
SQL HAVING Clause.........................................................................................................................63
The SQL HAVING Clause.............................................................................................................63
HAVING Syntax.......................................................................................................................63
Demo Database..............................................................................................................................63
SQL HAVING Examples...............................................................................................................64
Example....................................................................................................................................64
Example....................................................................................................................................64
Demo Database..............................................................................................................................64
More HAVING Examples..............................................................................................................64
Example....................................................................................................................................64
Example....................................................................................................................................65
SQL EXISTS Operator.......................................................................................................................65
The SQL EXISTS Operator...........................................................................................................65
EXISTS Syntax.........................................................................................................................65
Demo Database..............................................................................................................................65
SQL EXISTS Examples.................................................................................................................66
Example....................................................................................................................................66
Example....................................................................................................................................66
SQL ANY and ALL Operators...........................................................................................................66
The SQL ANY and ALL Operators................................................................................................66
The SQL ANY Operator................................................................................................................66
ANY Syntax..............................................................................................................................67
The SQL ALL Operator.................................................................................................................67
ALL Syntax With SELECT.......................................................................................................67
ALL Syntax With WHERE or HAVING..................................................................................67
Demo Database..............................................................................................................................67
SQL ANY Examples......................................................................................................................68
Example....................................................................................................................................68
Example....................................................................................................................................68
Example....................................................................................................................................69
SQL ALL Examples.......................................................................................................................69
Example....................................................................................................................................69
Example....................................................................................................................................69
SQL SELECT INTO Statement..........................................................................................................70
The SQL SELECT INTO Statement..............................................................................................70
SELECT INTO Syntax..............................................................................................................70
SQL SELECT INTO Examples.....................................................................................................70
SQL INSERT INTO SELECT Statement...........................................................................................71
The SQL INSERT INTO SELECT Statement...............................................................................71
Página 6 de 132
INSERT INTO SELECT Syntax...............................................................................................71
Demo Database..............................................................................................................................72
SQL INSERT INTO SELECT Examples......................................................................................72
Example....................................................................................................................................72
Example....................................................................................................................................72
Example....................................................................................................................................72
SQL CASE Statement.........................................................................................................................73
The SQL CASE Statement.............................................................................................................73
CASE Syntax.................................................................................................................................73
Demo Database..............................................................................................................................73
SQL CASE Examples....................................................................................................................73
Example....................................................................................................................................73
Example....................................................................................................................................74
SQL NULL Functions........................................................................................................................74
SQL IFNULL(), ISNULL(), COALESCE(), and NVL() Functions.............................................74
Solutions........................................................................................................................................74
SQL Stored Procedures for SQL Server.............................................................................................75
What is a Stored Procedure?..........................................................................................................75
Stored Procedure Syntax...........................................................................................................75
Execute a Stored Procedure......................................................................................................75
Demo Database..............................................................................................................................76
Stored Procedure Example.............................................................................................................76
Example....................................................................................................................................76
Example....................................................................................................................................76
Stored Procedure With One Parameter..........................................................................................76
Example....................................................................................................................................76
Example....................................................................................................................................77
Stored Procedure With Multiple Parameters.................................................................................77
Example....................................................................................................................................77
Example....................................................................................................................................77
SQL Comments..................................................................................................................................77
SQL Comments..............................................................................................................................77
Single Line Comments...................................................................................................................77
Example....................................................................................................................................78
Example....................................................................................................................................78
Example....................................................................................................................................78
Multi-line Comments.....................................................................................................................78
Example....................................................................................................................................78
Example....................................................................................................................................78
Example....................................................................................................................................78
Example....................................................................................................................................79
SQL Operators....................................................................................................................................79
SQL Arithmetic Operators.............................................................................................................79
SQL Bitwise Operators..................................................................................................................79
SQL Comparison Operators...........................................................................................................79
SQL Compound Operators............................................................................................................79
SQL Logical Operators..................................................................................................................80
SQL CREATE DATABASE Statement..............................................................................................80
The SQL CREATE DATABASE Statement..................................................................................80
Syntax........................................................................................................................................80
Página 7 de 132
CREATE DATABASE Example....................................................................................................80
Example....................................................................................................................................80
SQL DROP DATABASE Statement...................................................................................................81
The SQL DROP DATABASE Statement.......................................................................................81
Syntax........................................................................................................................................81
DROP DATABASE Example........................................................................................................81
Example....................................................................................................................................81
SQL BACKUP DATABASE for SQL Server.....................................................................................81
The SQL BACKUP DATABASE Statement.................................................................................81
Syntax........................................................................................................................................81
The SQL BACKUP WITH DIFFERENTIAL Statement..............................................................81
Syntax........................................................................................................................................82
BACKUP DATABASE Example...................................................................................................82
Example....................................................................................................................................82
BACKUP WITH DIFFERENTIAL Example................................................................................82
Example....................................................................................................................................82
SQL CREATE TABLE Statement......................................................................................................82
The SQL CREATE TABLE Statement..........................................................................................82
Syntax........................................................................................................................................82
SQL CREATE TABLE Example...................................................................................................83
Example....................................................................................................................................83
Create Table Using Another Table.................................................................................................83
Syntax........................................................................................................................................83
Example....................................................................................................................................84
SQL DROP TABLE Statement...........................................................................................................84
The SQL DROP TABLE Statement...............................................................................................84
Syntax........................................................................................................................................84
SQL DROP TABLE Example........................................................................................................84
Example....................................................................................................................................84
SQL TRUNCATE TABLE.............................................................................................................84
Syntax........................................................................................................................................84
SQL ALTER TABLE Statement.........................................................................................................84
SQL ALTER TABLE Statement....................................................................................................84
ALTER TABLE - ADD Column....................................................................................................85
Example....................................................................................................................................85
ALTER TABLE - DROP COLUMN.............................................................................................85
Example....................................................................................................................................85
ALTER TABLE - ALTER/MODIFY COLUMN...........................................................................85
SQL ALTER TABLE Example......................................................................................................86
Change Data Type Example...........................................................................................................86
DROP COLUMN Example...........................................................................................................86
SQL Constraints..................................................................................................................................87
SQL Create Constraints.................................................................................................................87
Syntax........................................................................................................................................87
SQL Constraints.............................................................................................................................87
SQL NOT NULL Constraint..............................................................................................................88
SQL NOT NULL Constraint..........................................................................................................88
SQL NOT NULL on CREATE TABLE.........................................................................................88
Example....................................................................................................................................88
SQL NOT NULL on ALTER TABLE............................................................................................88
Página 8 de 132
SQL UNIQUE Constraint...................................................................................................................88
SQL UNIQUE Constraint..............................................................................................................88
SQL UNIQUE Constraint on CREATE TABLE...........................................................................89
SQL UNIQUE Constraint on ALTER TABLE..............................................................................90
DROP a UNIQUE Constraint........................................................................................................90
SQL PRIMARY KEY Constraint.......................................................................................................90
SQL PRIMARY KEY Constraint..................................................................................................90
SQL PRIMARY KEY on CREATE TABLE.................................................................................90
SQL PRIMARY KEY on ALTER TABLE....................................................................................91
DROP a PRIMARY KEY Constraint.............................................................................................92
SQL FOREIGN KEY Constraint........................................................................................................92
SQL FOREIGN KEY Constraint...................................................................................................92
Persons Table.............................................................................................................................92
Orders Table..............................................................................................................................92
SQL FOREIGN KEY on CREATE TABLE..................................................................................93
SQL FOREIGN KEY on ALTER TABLE.....................................................................................94
DROP a FOREIGN KEY Constraint.............................................................................................94
SQL CHECK Constraint.....................................................................................................................94
SQL CHECK Constraint................................................................................................................94
SQL CHECK on CREATE TABLE...............................................................................................95
SQL CHECK on ALTER TABLE..................................................................................................95
DROP a CHECK Constraint..........................................................................................................96
SQL DEFAULT Constraint.................................................................................................................96
SQL DEFAULT Constraint............................................................................................................96
SQL DEFAULT on CREATE TABLE...........................................................................................96
SQL DEFAULT on ALTER TABLE..............................................................................................97
DROP a DEFAULT Constraint......................................................................................................97
SQL CREATE INDEX Statement......................................................................................................98
SQL CREATE INDEX Statement.................................................................................................98
CREATE INDEX Syntax..........................................................................................................98
CREATE UNIQUE INDEX Syntax..........................................................................................98
CREATE INDEX Example............................................................................................................98
DROP INDEX Statement..............................................................................................................98
SQL AUTO INCREMENT Field.......................................................................................................99
AUTO INCREMENT Field...........................................................................................................99
Syntax for MySQL.........................................................................................................................99
Syntax for SQL Server.................................................................................................................100
Syntax for Access.........................................................................................................................101
Syntax for Oracle.........................................................................................................................101
SQL Working With Dates.................................................................................................................102
SQL Dates....................................................................................................................................102
SQL Date Data Types..................................................................................................................102
SQL Working with Dates.............................................................................................................102
Orders Table............................................................................................................................103
SQL Views........................................................................................................................................103
SQL CREATE VIEW Statement..................................................................................................103
CREATE VIEW Syntax..........................................................................................................104
SQL CREATE VIEW Examples..................................................................................................104
Example..................................................................................................................................104
Example..................................................................................................................................104
Página 9 de 132
Example..................................................................................................................................104
Example..................................................................................................................................104
SQL Updating a View..................................................................................................................104
SQL CREATE OR REPLACE VIEW Syntax........................................................................105
Example..................................................................................................................................105
SQL Dropping a View..................................................................................................................105
SQL DROP VIEW Syntax......................................................................................................105
Example..................................................................................................................................105
SQL Injection....................................................................................................................................105
SQL Injection...............................................................................................................................105
SQL in Web Pages.......................................................................................................................105
Example..................................................................................................................................106
SQL Injection Based on 1=1 is Always True...............................................................................106
SQL Injection Based on""="" is Always True.............................................................................106
Example..................................................................................................................................106
Result......................................................................................................................................106
Result......................................................................................................................................107
SQL Injection Based on Batched SQL Statements......................................................................107
Example..................................................................................................................................107
Example..................................................................................................................................107
Result......................................................................................................................................107
Use SQL Parameters for Protection.............................................................................................107
ASP.NET Razor Example.......................................................................................................108
Another Example....................................................................................................................108
Examples......................................................................................................................................108
SQL Hosting.....................................................................................................................................109
SQL Hosting................................................................................................................................109
MS SQL Server............................................................................................................................109
Oracle...........................................................................................................................................109
MySQL........................................................................................................................................109
MS Access....................................................................................................................................109
SQL Data Types for MySQL, SQL Server, and MS Access.............................................................110
SQL Data Types...........................................................................................................................110
MySQL Data Types (Version 8.0)................................................................................................110
String Data Types....................................................................................................................110
Numeric Data Types................................................................................................................111
Date and Time Data Types......................................................................................................112
SQL Server Data Types................................................................................................................112
String Data Types....................................................................................................................112
Numeric Data Types................................................................................................................112
Date and Time Data Types......................................................................................................113
Other Data Types.....................................................................................................................114
MS Access Data Types.................................................................................................................114
SQL Keywords Reference................................................................................................................114
SQL Keywords.............................................................................................................................115
MySQL Functions.............................................................................................................................117
MySQL String Functions.............................................................................................................117
MySQL Numeric Functions.........................................................................................................118
MySQL Date Functions...............................................................................................................119
MySQL Advanced Functions.......................................................................................................120
Página 10 de 132
SQL Server Functions.......................................................................................................................121
SQL Server String Functions.......................................................................................................121
SQL Server Math/Numeric Functions.........................................................................................122
SQL Server Date Functions.........................................................................................................123
SQL Server Advanced Functions.................................................................................................123
Página 11 de 132
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of
the International Organization for Standardization (ISO) in 1987
Note: Most of the SQL database programs also have their own proprietary extensions in addition to
the SQL standard!
Página 12 de 132
• An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
• To use a server-side scripting language, like PHP or ASP
• To use SQL to get the data you want
• To use HTML / CSS to style the page
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related data
entries and it consists of columns and rows.
Look at the "Customers" table:
Example
SELECT * FROM Customers;
Every table is broken up into smaller entities called fields. The fields in the Customers table consist
of CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. A field is a
column in a table that is designed to maintain specific information about every record in the table.
A record, also called a row, is each individual entry that exists in a table. For example, there are 91
records in the above Customers table. A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific field
in a table.
SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
In this tutorial we will use the well-known Northwind sample database (included in MS Access and
MS SQL Server).
Below is a selection from the "Customers" table:
Página 13 de 132
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
120 Hanover
4 Around the Horn Thomas Hardy London WA1 1DP UK
Sq.
Berglunds Christina Berguvsvägen
5 Luleå S-958 22 Sweden
snabbköp Berglund 8
The table above contains five records (one for each customer) and seven columns (CustomerID,
CustomerName, ContactName, Address, City, PostalCode, and Country).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
In this tutorial we will teach you all about the different SQL statements.
Página 14 de 132
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you
want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Página 15 de 132
SELECT Column Example
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName, City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE,
DELETE, etc.!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Página 16 de 132
Emparedados y Constitución
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
120 Hanover
4 Around the Horn Thomas Hardy London WA1 1DP UK
Sq.
Berglunds Christina Berguvsvägen
5 Luleå S-958 22 Sweden
snabbköp Berglund 8
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Página 17 de 132
LIKE Search for a pattern
IN To specify multiple possible values for a column
The AND and OR operators are used to filter records based on more than one condition:
• The AND operator displays a record if all the conditions separated by AND are TRUE.
• The OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Emparedados y
2 Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
helados
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
Página 18 de 132
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
FISSA Fabrica Inter.
22 Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
Salchichas S.A.
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
Furia Bacalhau e Frutos do
28 Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
Mar
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
Carrera 22 con Ave. Carlos
35 HILARIÓN-Abastos Carlos Hernández San Cristóbal 5022 Venezuela
Soublette #8-35
City Center Plaza 516 Main
36 Hungry Coyote Import Store Yoshi Latimer Elgin 97827 USA
St.
Hungry Owl All-Night
37 Patricia McKenna 8 Johnstown Road Cork Ireland
Grocers
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
Laughing Bacchus Wine
42 Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
Cellars
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
Carrera 52 con Ave. Bolívar
46 LILA-Supermercado Carlos González Barquisimeto 3508 Venezuela
#65-98 Llano Largo
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
South House 300
53 North/South Simon Crowther London SW7 1RZ UK
Queensbridge
Ing. Gustavo Moncada 8585
54 Océano Atlántico Ltda. Yvonne Moncada Buenos Aires 1010 Argentina
Piso 20-A
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
Henriette
56 Ottilies Käseladen Mehrheimerstr. 369 Köln 50739 Germany
Pfalzheim
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
Página 19 de 132
Guillermo
58 Pericles Comidas clásicas Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
Fernández
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
Art
75 Split Rail Beer & Ale P.O. Box 555 Lander 82520 USA
Braunschweiger
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
Miguel Angel
80 Tortuga Restaurante Avda. Azteca 123 México D.F. 05033 Mexico
Paolino
Anabela
81 Tradição Hipermercados Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
Domingues
Trail's Head Gourmet
82 Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
Provisioners
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany" AND
city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
Página 20 de 132
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany" OR
"Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
The following SQL statement selects all fields from "Customers" where country is "Germany" AND
city must be "Berlin" OR "München" (use parenthesis to form complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
The following SQL statement selects all fields from "Customers" where country is NOT "Germany"
and NOT "USA":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
Página 21 de 132
SQL ORDER BY Keyword
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
Página 22 de 132
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
Página 23 de 132
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. Here, the INSERT INTO syntax would be as follows:
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
Página 24 de 132
Insert Data Only in Specified Columns
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in the "CustomerName",
"City", and "Country" columns (CustomerID will be updated automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
The selection from the "Customers" table will now look like this:
Página 25 de 132
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
Tip: Always use IS NULL to look for NULL values.
Página 26 de 132
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE
statement. The WHERE clause specifies which record(s) that should be updated. If you omit the
WHERE clause, all records in the table will be updated!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Página 27 de 132
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
The following SQL statement will update the ContactName to "Juan" for all records where country
is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
Página 28 de 132
Taquería 2312 D.F.
120 Hanover
4 Around the Horn Thomas Hardy London WA1 1DP UK
Sq.
Berglunds Christina Berguvsvägen
5 Luleå S-958 22 Sweden
snabbköp Berglund 8
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example
UPDATE Customers
SET ContactName='Juan';
The selection from the "Customers" table will now look like this:
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE
clause, all records in the table will be deleted!
Página 29 de 132
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The "Customers" table will now look like this:
Página 30 de 132
Example
DELETE FROM Customers;
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large
number of records can impact performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT
clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY
and ROWNUM.
Página 31 de 132
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s))
WHERE ROWNUM <= number;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement shows the equivalent example for MySQL:
Example
SELECT * FROM Customers
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
Página 32 de 132
SQL TOP PERCENT Example
The following SQL statement selects the first 50% of the records from the "Customers" table (for
SQL Server/MS Access):
Example
SELECT TOP 50 PERCENT * FROM Customers;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;
Example
SELECT TOP 3 * FROM Customers
WHERE Country='Germany';
The following SQL statement shows the equivalent example for MySQL:
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;
Página 33 de 132
The SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Página 34 de 132
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
Página 35 de 132
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
Note: NULL values are not counted.
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored.
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
Note: NULL values are ignored.
Página 36 de 132
SQL LIKE Operator
There are two wildcards often used in conjunction with the LIKE operator:
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
Página 37 de 132
Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
Carrera 22 con Ave. Carlos
35 HILARIÓN-Abastos Carlos Hernández San Cristóbal 5022 Venezuela
Soublette #8-35
City Center Plaza 516 Main
36 Hungry Coyote Import Store Yoshi Latimer Elgin 97827 USA
St.
37 Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road Cork Ireland
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
Carrera 52 con Ave. Bolívar
46 LILA-Supermercado Carlos González Barquisimeto 3508 Venezuela
#65-98 Llano Largo
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
Página 38 de 132
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
South House 300
53 North/South Simon Crowther London SW7 1RZ UK
Queensbridge
Ing. Gustavo Moncada 8585
54 Océano Atlántico Ltda. Yvonne Moncada Buenos Aires 1010 Argentina
Piso 20-A
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369 Köln 50739 Germany
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
75 Split Rail Beer & Ale Art Braunschweiger P.O. Box 555 Lander 82520 USA
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 05033 Mexico
81 Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with "a":
Página 39 de 132
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have "or" in any
position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have "r" in the
second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that starts with "a" and
are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
The following SQL statement selects all customers with a ContactName that starts with "a" and
ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that does NOT start with
"a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
SQL Wildcards
Página 40 de 132
SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.
Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE
clause to search for a specified pattern in a column.
Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:
Página 41 de 132
CustomerID CustomerName ContactName Address City PostalCode Country
Página 42 de 132
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
Carrera 22 con Ave. Carlos
35 HILARIÓN-Abastos Carlos Hernández San Cristóbal 5022 Venezuela
Soublette #8-35
City Center Plaza 516 Main
36 Hungry Coyote Import Store Yoshi Latimer Elgin 97827 USA
St.
37 Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road Cork Ireland
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
Carrera 52 con Ave. Bolívar
46 LILA-Supermercado Carlos González Barquisimeto 3508 Venezuela
#65-98 Llano Largo
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
South House 300
53 North/South Simon Crowther London SW7 1RZ UK
Queensbridge
Ing. Gustavo Moncada 8585
54 Océano Atlántico Ltda. Yvonne Moncada Buenos Aires 1010 Argentina
Piso 20-A
Página 43 de 132
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369 Köln 50739 Germany
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
75 Split Rail Beer & Ale Art Braunschweiger P.O. Box 555 Lander 82520 USA
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 05033 Mexico
81 Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
Página 44 de 132
Using the _ Wildcard
The following SQL statement selects all customers with a City starting with any character, followed
by "ondon":
Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';
The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Or:
Página 45 de 132
Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
SQL IN Operator
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
Página 46 de 132
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
Carrera 22 con Ave. Carlos
35 HILARIÓN-Abastos Carlos Hernández San Cristóbal 5022 Venezuela
Soublette #8-35
City Center Plaza 516 Main
36 Hungry Coyote Import Store Yoshi Latimer Elgin 97827 USA
St.
37 Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road Cork Ireland
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
Carrera 52 con Ave. Bolívar
46 LILA-Supermercado Carlos González Barquisimeto 3508 Venezuela
#65-98 Llano Largo
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
South House 300
53 North/South Simon Crowther London SW7 1RZ UK
Queensbridge
Ing. Gustavo Moncada 8585
54 Océano Atlántico Ltda. Yvonne Moncada Buenos Aires 1010 Argentina
Piso 20-A
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369 Köln 50739 Germany
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
Página 47 de 132
75 Split Rail Beer & Ale Art Braunschweiger P.O. Box 555 Lander 82520 USA
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 05033 Mexico
81 Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" or
"UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany", "France" or
"UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
Página 48 de 132
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Página 49 de 132
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName between Carnarvon Tigers
and Chef Anton's Cajun Seasoning:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:
Página 50 de 132
10251 84 3 7/9/1996 1
10252 76 4 7/10/1996 2
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Página 51 de 132
Below is a selection from the "Customers" table:
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
The following SQL statement creates two aliases, one for the CustomerName column and one for
the ContactName column. Note: It requires double quotation marks or square brackets if the alias
name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
The following SQL statement creates an alias named "Address" that combine four columns
(Address, PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers;
Página 52 de 132
Alias for Tables Example
The following SQL statement selects all the orders from the customer with CustomerID=4 (Around
the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and
"o" respectively (Here we use aliases to make the SQL shorter):
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
The following SQL statement is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND
Customers.CustomerID=Orders.CustomerID;
Aliases can be useful when:
• There are more than one table involved in a query
• Functions are used in the query
• Column names are big or not very readable
• Two or more columns are combined together
SQL Joins
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Let's look at a selection from the "Orders" table:
Página 53 de 132
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:
Página 54 de 132
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables.
Página 55 de 132
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are records in the "Orders" table that do not have matches in
"Customers", these orders will not be shown!
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
Página 56 de 132
SQL LEFT JOIN Keyword
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Página 57 de 132
SQL LEFT JOIN Example
The following SQL statement will select all customers, and any orders they might have:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there
are no matches in the right table (Orders).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
Página 58 de 132
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
And a selection from the "Employees" table:
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if
there are no matches in the left table (Orders).
Página 59 de 132
Note: FULL OUTER JOIN can potentially return very large result-sets!
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerName OrderID
Alfreds Futterkiste Null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería Null
Página 60 de 132
Note: The FULL OUTER JOIN keyword returns all matching records from both tables whether
the other table matches or not. So, if there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will
be listed as well.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Example
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
Página 61 de 132
SQL UNION Operator
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Página 62 de 132
Charlotte 49 Gilbert
1 Exotic Liquid London EC1 4SD UK
Cooper St.
New Orleans Cajun P.O. Box New
2 Shelley Burke 70117 USA
Delights 78934 Orleans
Grandma Kelly's 707 Oxford Ann
3 Regina Murphy 48104 USA
Homestead Rd. Arbor
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Note: If some customers or suppliers have the same city, each city will only be listed once, because
UNION selects only distinct values. Use UNION ALL to also select duplicate values!
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
Página 63 de 132
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a
temporary name. An alias only exists for the duration of the query. So, here we have created a
temporary column named "Type", that list whether the contact person is a "Customer" or a
"Supplier".
Página 64 de 132
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(),
SUM(), AVG()) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Página 65 de 132
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Página 66 de 132
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The following SQL statement lists the number of customers in each country, sorted high to low
(Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
Página 67 de 132
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
And a selection from the "Employees" table:
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
The following SQL statement lists if the employees "Davolio" or "Fuller" have registered more than
25 orders:
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
The EXISTS operator returns TRUE if the subquery returns one or more records.
Página 68 de 132
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
The following SQL statement returns TRUE and lists the suppliers with a product price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
Página 69 de 132
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
ALL means that the condition will be true only if the operation is true for all values in the range.
Página 70 de 132
ALL Syntax With SELECT
SELECT ALL column_name(s)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
Página 71 de 132
SQL ANY Examples
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity equal to 10 (this will return TRUE because the Quantity column has some values
of 10):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity larger than 99 (this will return TRUE because the Quantity column has some
values larger than 99):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity larger than 1000 (this will return FALSE because the Quantity column has no
values larger than 1000):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
Página 72 de 132
Example
SELECT ALL ProductName
FROM Products
WHERE TRUE;
The following SQL statement lists the ProductName if ALL the records in the OrderDetails table
has Quantity equal to 10. This will of course return FALSE because the Quantity column has many
different values (not only the value of 10):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
Página 73 de 132
SQL SELECT INTO Statement
Página 74 de 132
SELECT * INTO CustomersGermany
FROM Customers
WHERE Country = 'Germany';
The following SQL statement copies data from more than one table into a new table:
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Tip: SELECT INTO can also be used to create a new, empty table using the schema of another.
Just add a WHERE clause that causes the query to return no data:
Página 75 de 132
Página 76 de 132
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Postal
SupplierID SupplierName ContactName Address City Country
Code
Charlotte 49 Gilbert
1 Exotic Liquid Londona EC1 4SD UK
Cooper St.
New Orleans Cajun P.O. Box New
2 Shelley Burke 70117 USA
Delights 78934 Orleans
Grandma Kelly's 707 Oxford
3 Regina Murphy Ann Arbor 48104 USA
Homestead Rd.
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
The following SQL statement copies "Suppliers" into "Customers" (fill all columns):
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
The following SQL statement copies only the German suppliers into "Customers":
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
Página 77 de 132
SQL CASE Statement
CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
Example
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
Página 78 de 132
END AS QuantityText
FROM OrderDetails;
The following SQL will order the customers by City. However, if City is NULL, then order by
Country:
Example
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
Solutions
MySQL
The MySQL IFNULL() function lets you return an alternative value if an expression is NULL:
Página 79 de 132
or we can use the COALESCE() function, like this:
Página 80 de 132
Execute a Stored Procedure
EXEC procedure_name;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Execute the stored procedure above as follows:
Example
EXEC SelectAllCustomers;
Página 81 de 132
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Execute the stored procedure above as follows:
Example
EXEC SelectAllCustomers @City = 'London';
Example
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
Execute the stored procedure above as follows:
Example
EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';
SQL Comments
SQL Comments
Comments are used to explain sections of SQL statements, or to prevent execution of SQL
statements.
Note: The examples in this chapter will not work in Firefox and Microsoft Edge!
Comments are not supported in Microsoft Access databases. Firefox and Microsoft Edge are using
Microsoft Access database in our examples.
Página 82 de 132
Single Line Comments
Single line comments start with --.
Any text between -- and the end of the line will be ignored (will not be executed).
The following example uses a single-line comment as an explanation:
Example
--Select all:
SELECT * FROM Customers;
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
The following example uses a single-line comment to ignore a statement:
Example
--SELECT * FROM Customers;
SELECT * FROM Products;
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
The following example uses a multi-line comment to ignore many statements:
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Página 83 de 132
To ignore just a part of a statement, also use the /* */ comment.
The following example uses a comment to ignore part of a line:
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;
The following example uses a comment to ignore part of a statement:
Example
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;
SQL Operators
Página 84 de 132
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
Syntax
CREATE DATABASE databasename;
Página 85 de 132
CREATE DATABASE Example
The following SQL statement creates a database called "testDB":
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a database is created,
you can check it in the list of databases with the following SQL command: SHOW DATABASES;
Syntax
DROP DATABASE databasename;
Note: Be careful before dropping a database. Deleting a database will result in loss of complete
information stored in the database!
Example
DROP DATABASE testDB;
Tip: Make sure you have admin privilege before dropping any database. Once a database is
dropped, you can check it in the list of databases with the following SQL command: SHOW
DATABASES;
Página 86 de 132
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath';
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak';
Tip: Always back up the database to a different drive than the actual database. Then, if you get a
disk crash, you will not lose your backup file along with the database.
Example
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
Tip: A differential back up reduces the back up time (since only the changes are backed up).
Página 87 de 132
The SQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date,
etc.).
Tip: For an overview of the available data types, go to our complete Data Types Reference.
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The PersonID column is of type int and will hold an integer.
The LastName, FirstName, Address, and City columns are of type varchar and will hold characters,
and the maximum length for these fields is 255 characters.
The empty "Persons" table will now look like this:
Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.
Página 88 de 132
Create Table Using Another Table
A copy of an existing table can also be created using CREATE TABLE.
The new table gets the same column definitions. All columns or specific columns can be selected.
If you create a new table using an existing table, the new table will be filled with the existing values
from the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
The following SQL creates a new table called "TestTables" (which is a copy of the "Customers"
table):
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!
Example
DROP TABLE Shippers;
Página 89 de 132
SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
Syntax
TRUNCATE TABLE table_name;
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
Example
ALTER TABLE Customers
ADD Email varchar(255);
Example
ALTER TABLE Customers
DROP COLUMN Email;
Página 90 de 132
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
My SQL / Oracle (prior version 10G):
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Oracle 10G and later:
ALTER TABLE table_name
MODIFY column_name datatype;
Página 91 de 132
We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or
four-digit format.
SQL Constraints
SQL constraints are used to specify rules for data in a table.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Página 92 de 132
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
This enforces a field to always contain a value, which means that you cannot insert a new record, or
update a record without adding a value to this field.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Página 93 de 132
Age int
);
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column
or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
Página 94 de 132
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
MySQL:
Página 95 de 132
ALTER TABLE Persons
DROP INDEX UC_Person;
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or
multiple columns (fields).
Página 96 de 132
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY;
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT PK_Person;
Página 97 de 132
SQL FOREIGN KEY Constraint
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY
in another table.
The table with the foreign key is called the child table, and the table with the primary key is called
the referenced or parent table.
Look at the following two tables:
Persons Table
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.
Página 98 de 132
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
SQL Server / Oracle / MS Access:
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
Página 99 de 132
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
SQL Server / Oracle / MS Access:
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
The default value will be added to all new records, if no other value is specified.
MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;
Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot
see the indexes, they are just used to speed up searches/queries.
MS Access:
DROP INDEX index_name ON table_name;
SQL Server:
DROP INDEX table_name.index_name;
DB2/Oracle:
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new
record.
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each
new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to
IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the
"Personid" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table. The "Personid"
column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".
By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new
record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change the
autoincrement to AUTOINCREMENT(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the
"Personid" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table. The "Personid"
column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the
"LastName" column would be set to "Monsen".
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are
trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However, if
a time portion is involved, it gets more complicated.
SQL Server comes with the following data types for storing a date or a date/time value in the
database:
• DATE - format YYYY-MM-DD
• DATETIME - format: YYYY-MM-DD HH:MI:SS
• SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
• TIMESTAMP - format: a unique number
Note: The date types are chosen for a column when you create a new table in your database!
SQL Views
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
We can query the view above as follows:
Example
SELECT * FROM [Brazil Customers];
The following SQL creates a view that selects every product in the "Products" table with a price
higher than the average price:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
We can query the view above as follows:
Example
SELECT * FROM [Products Above Average Price];
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Example
DROP VIEW [Brazil Customers];
SQL Injection
SQL Injection
SQL injection is a code injection technique that might destroy your database.
SQL injection is one of the most common web hacking techniques.
SQL injection is the placement of malicious code in SQL statements, via web page input.
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The rest of this chapter describes the potential dangers of using user input in SQL statements.
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' + uPass + '"'
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
A hacker might get access to user names and passwordsin a database by simply inserting " OR ""="
into the user name or password text box:
User Name:
Password:
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The SQL above is valid and will return all rows from the "Users" table, since OR ""="" is always
TRUE.
Example
SELECT * FROM Users; DROP TABLE Suppliers
Look at the following example:
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
And the following input:
User id:
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
Examples
The following examples shows how to build parameterized queries in some common web
languages.
SELECT STATEMENT IN ASP.NET:
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserId);
command.ExecuteReader();
INSERT INTO STATEMENT IN ASP.NET:
SQL Hosting
SQL Hosting
If you want your web site to be able to store and retrieve data from a database, your web server
should have access to a database-system that uses the SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will have to look for SQL
hosting plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS Access.
MS SQL Server
Microsoft's SQL Server is a popular database software for database-driven web sites with high
traffic.
SQL Server is a very powerful, robust and full featured SQL database system.
Oracle
Oracle is also a popular database software for database-driven web sites with high traffic.
MySQL
MySQL is also a popular database software for web sites.
MySQL is a very powerful, robust and full featured SQL database system.
MySQL is an inexpensive alternative to the expensive Microsoft and Oracle solutions.
MS Access
When a web site requires only a simple database, Microsoft Access can be a solution.
MS Access is not well suited for very high-traffic, and not as powerful as MySQL, SQL Server, or
Oracle.
The p parameter indicates the maximum total number of digits that can be
5-17
decimal(p,s) stored (both to the left and to the right of the decimal point). p must be a
bytes
value from 1 to 38. Default is 18.
The p parameter indicates the maximum total number of digits that can be
stored (both to the left and to the right of the decimal point). p must be a
SQL Keywords
Keyword Description
ADD Adds a column in an existing table
ADD CONSTRAINT Adds a constraint after a table is already created
Adds, deletes, or modifies columns in a table, or changes the data type
ALTER
of a column in a table
ALTER COLUMN Changes the data type of a column in a table
ALTER TABLE Adds, deletes, or modifies columns in a table
ALL Returns true if all of the subquery values meet the condition
AND Only includes rows where both conditions is true
ANY Returns true if any of the subquery values meet the condition
AS Renames a column or table with an alias
ASC Sorts the result set in ascending order
BACKUP DATABASE Creates a back up of an existing database
MySQL Functions
MySQL has many built-in functions.
This reference contains string, numeric, date, and some advanced functions in MySQL.