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
What Can SQL do?
- SQL can execute queries against a database
- SQL can retrieve data from a database
- SQL can insert records in a database
- SQL can update records in a database
- SQL can delete records from a database
- SQL can create new databases
- SQL can create new tables in a database
- SQL can create stored procedures in a database
- SQL can create views in a database
- SQL can set permissions on tables, procedures, and views
SQL is a Standard – BUT….
Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major commands (such asย SELECT,ย UPDATE,ย DELETE,ย INSERT,ย WHERE) in a similar manner.
Note:ย Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
Using SQL in Your Web Site
To build a web site that shows data from a database, you will need:
- 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
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
SQL statements consists of keywords that are easy to understand.
The following SQL statement returns all records from a table named “Customers”:
Example
Select all records from the Customers table:
SELECTย *ย FROMย Customers;
In this tutorial we will teach you all about the different SQL statements.
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. “Customers” or “Orders”), and 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 used in the examples:
| 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 |
The table above contains five records (one for each customer) and seven columns (CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).
Keep in Mind That…
- SQL keywords are NOT case sensitive:ย
selectย is the same asยSELECT
In this tutorial we will write all SQL keywords in upper-case.
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.
Some of The Most Important SQL Commands
SELECTย – extracts data from a databaseUPDATEย – updates data in a databaseDELETEย – deletes data from a databaseINSERT INTOย – inserts new data into a databaseCREATE DATABASEย – creates a new databaseALTER DATABASEย – modifies a databaseCREATE TABLEย – creates a new tableALTER TABLEย – modifies a tableDROP TABLEย – deletes a tableCREATE INDEXย – creates an index (search key)DROP INDEXย – deletes an index
SQLย SELECTย Statement
The SQL SELECT Statement
Theย SELECTย statement is used to select data from a database.
Example
Return data from the Customers table:
SELECTย CustomerName, Cityย FROMย Customers;
Syntax
SELECTcolumn1,ย column2, ...
FROMtable_name;
Here, column1, column2, … are theย field namesย of the table you want to select data from.
The table_name represents the name of theย tableย you want to select data from.
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
Select ALL columns
If you want to return all columns, without specifying every column name, you can use theย SELECT *ย syntax:
Example
Return all the columns from the Customers table:
SELECTย *ย FROMย Customers;
SQLย SELECT DISTINCTย Statement
The SQL SELECT DISTINCT Statement
Theย SELECT DISTINCTย statement is used to return only distinct (different) values.
Example
Select all the different countries from the “Customers” table:
SELECTย DISTINCTย Countryย FROMย Customers;
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
Syntax
SELECTย DISTINCTcolumn1,ย column2, ...
FROMtable_name;
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
SELECT Example Without DISTINCT
If you omit theย DISTINCTย keyword, the SQL statement returns the “Country” value from all the records of the “Customers” table:
Example
SELECTย Countryย FROMย Customers;
Count Distinct
By using theย DISTINCTย keyword in a function calledย COUNT, we can return the number of different countries.
Example
SELECTย COUNT(DISTINCTย Country)ย FROMย Customers;
Note: Theย COUNT(DISTINCTย column_name) is not supported in Microsoft Access databases.
Here is a workaround for MS Access:
Example
SELECTย Count(*)ย ASย DistinctCountries
FROMย (SELECTย DISTINCTย Countryย FROMย Customers);
SQLย WHEREย Clause
The SQL WHERE Clause
Theย WHEREย clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
Example
Select all customers from Mexico:
SELECTย *ย FROMย Customers
WHEREย Country=‘Mexico’;
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 used in the examples:
| 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 |
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECTย *ย FROMย Customers
WHEREย CustomerID=1;
Operators in The WHERE Clause
You can use other operators than theย =ย operator to filter the search.
Example
Select all customers with a CustomerID greater than 80:
SELECTย *ย FROMย Customers
WHEREย CustomerID >ย 80;
SQLย ORDER BYย Keyword
The SQL ORDER BY
Theย ORDER BYย keyword is used to sort the result-set in ascending or descending order.
Example
Sort the products by price:
SELECTย *ย FROMย Products
ORDERย BY Price;
Syntax
SELECTย column1,ย column2, ...
FROMย table_name
ORDERย BYย column1, column2, ...ย ASC|DESC;
Demo Database
Below is a selection from theย Productsย table used in the examples:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
DESC
Theย ORDER BYย keyword sorts the records in ascending order by default. To sort the records in descending order, use theย DESCย keyword.
Example
Sort the products from highest to lowest price:
SELECTย *ย FROMย Products
ORDERย BYย Priceย DESC;
Order Alphabetically
For string values theย ORDER BYย keyword will order alphabetically:
Example
Sort the products alphatbetically by ProductName:
SELECTย *ย FROMย Products
ORDERย BY ProductName;
Alphabetically DESC
To sort the table reverse alphabetically, use theย DESCย keyword:
Example
Sort the products by ProductName in reverse order:
SELECTย *ย FROMย Products
ORDERย BYย ProductNameย DESC;
ORDER BY Several Columns
The following SQL statement selects all customers from the “Customers” table, sorted by the “Country” and the “CustomerName” column. This means that it orders by Country, but if some rows have the same Country, it orders them by CustomerName:
Example
SELECTย *ย FROMย Customers
ORDERย BY Country, CustomerName;
Using Both ASC and DESC
The following SQL statement selects all customers from the “Customers” table, sorted ascending by the “Country” and descending by the “CustomerName” column:
Example
SELECTย *ย FROMย Customers
ORDERย BYย Countryย ASC, CustomerNameย DESC;
SQLย ANDย Operator
The SQL AND Operator
Theย WHEREย clause can contain one or manyย ANDย operators.
Theย ANDย operator is used to filter records based on more than one condition, like if you want to return all customers from Spain that starts with the letter ‘G’:
Example
Select all customers from Spain that starts with the letter ‘G’:
SELECTย *
FROMย Customers
WHEREย Country =ย ‘Spain’ย ANDย CustomerNameย LIKEย ‘G%’;
Syntax
SELECTย column1,ย column2, ...
FROMย table_name
WHEREย condition1ย ANDย condition2ย ANDย condition3 ...;
AND vs OR
Theย ANDย operator displays a record ifย allย the conditions are TRUE.
Theย ORย operator displays a record ifย anyย of the conditions are TRUE.
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
All Conditions Must Be True
The following SQL statement selects all fields fromย Customersย whereย Countryย is “Germany” ANDย Cityย is “Berlin” ANDย PostalCodeย is higher than 12000:
Example
SELECTย *ย FROMย Customers
WHEREย Country =ย ‘Germany’
ANDย City =ย ‘Berlin’
ANDย PostalCode >ย 12000;
Combining AND and OR
You can combine theย ANDย andย ORย operators.
The following SQL statement selects all customers from Spain that starts with a “G” or an “R”.
Make sure you use parenthesis to get the correct result.
Example
Select all Spanish customers that starts with either “G” or “R”:
SELECTย *ย FROMย Customers
WHEREย Country =ย ‘Spain’ย ANDย (CustomerNameย LIKEย ‘G%’ย ORย CustomerNameย LIKEย ‘R%’);
Without parenthesis, the select statement will return all customers from Spain that starts with a “G”,ย plusย all customers that starts with an “R”, regardless of the country value:
Example
Select all customers that either:
are from Spain and starts with either “G”,ย or
starts with the letter “R”:
SELECTย *ย FROMย Customers
WHEREย Country =ย ‘Spain’ย ANDย CustomerNameย LIKEย ‘G%’ย ORย CustomerNameย LIKEย ‘R%’;
SQLย ORย Operator
The SQL OR Operator
Theย WHEREย clause can contain one or moreย ORย operators.
Theย ORย operator is used to filter records based on more than one condition, like if you want to return all customers from Germany but also those from Spain:
Example
Select all customers from Germany or Spain:
SELECTย *
FROMย Customers
WHEREย Country =ย ‘Germany’ย ORย Country =ย ‘Spain’;
Syntax
SELECTย column1,ย column2, ...
FROMย table_name
WHEREย condition1ย ORย condition2ย ORย condition3 ...;
OR vs AND
Theย ORย operator displays a record ifย anyย of the conditions are TRUE.
Theย ANDย operator displays a record ifย allย the conditions are TRUE.
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
At Least One Condition Must Be True
The following SQL statement selects all fields from Customers where eitherย Cityย is “Berlin”,ย CustomerNameย starts with the letter “G” orย Countryย is “Norway”:
Example
SELECTย *ย FROMย Customers
WHEREย City =ย ‘Berlin’ย ORย CustomerNameย LIKEย ‘G%’ย ORย Country =ย ‘Norway’;
Combining AND and OR
You can combine theย ANDย andย ORย operators.
The following SQL statement selects all customers from Spain that starts with a “G” or an “R”.
Make sure you use parenthesis to get the correct result.
Example
Select all Spanish customers that starts with either “G” or “R”:
SELECTย *ย FROMย Customers
WHEREย Country =ย ‘Spain’ย ANDย (CustomerNameย LIKEย ‘G%’ย ORย CustomerNameย LIKEย ‘R%’);
Without parenthesis, the select statement will return all customers from Spain that starts with a “G”,ย plusย all customers that starts with an “R”, regardless of the country value:
Example
Select all customers that either:
are from Spain and starts with either “G”,ย or
starts with the letter “R”:
SELECTย *ย FROMย Customers
WHEREย Country =ย ‘Spain’ย ANDย CustomerNameย LIKEย ‘G%’ย ORย CustomerNameย LIKEย ‘R%’;
SQLย NOTย Operator
The NOT Operator
Theย NOTย operator is used in combination with other operators to give the opposite result, also called the negative result.
In the select statement below we want to return all customers that are NOT from Spain:
Example
Select only the customers that are NOT from Spain:
SELECTย *ย FROMย Customers
WHEREย NOTย Country =ย ‘Spain’;
In the example above, theย NOTย operator is used in combination with theย =ย operator, but it can be used in combination with other comparison and/or logical operators. See examples below.
Syntax
SELECTย column1,ย column2, ...
FROMย table_name
WHEREย NOTย condition;
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
NOT LIKE
Example
Select customers that does not start with the letter ‘A’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย NOTย LIKEย ‘A%’;
NOT BETWEEN
Example
Select customers with a customerID not between 10 and 60:
SELECTย *ย FROMย Customers
WHEREย CustomerIDย NOTย BETWEENย 10ย ANDย 60;
NOT IN
Example
Select customers that are not from Paris or London:
SELECTย *ย FROMย Customers
WHEREย Cityย NOTย INย (‘Paris’,ย ‘London’);
NOT Greater Than
Example
Select customers with a CustomerId not greater than 50:
SELECTย *ย FROMย Customers
WHEREย NOTย CustomerID >ย 50;
Note:ย There is a not-greater-then operator:ย !>ย that would give you the same result.
NOT Less Than
Example
Select customers with a CustomerID not less than 50:
SELECTย *ย FROMย Customers
WHEREย NOTย CustomerId <ย 50;
Note:ย There is a not-less-then operator:ย !<ย that would give you the same result.
SQLย INSERT INTOย Statement
The SQL INSERT INTO Statement
Theย INSERT INTOย statement is used to insert new records in a table.
INSERT INTO Syntax
It is possible to write theย INSERT INTOย statement in two ways:
1. Specify both the column names and the values to be inserted:
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:
INSERTย INTOย table_name
VALUESย (value1,ย value2,ย value3, ...);
Demo Database
Below is a selection from theย Customersย table used in the examples:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 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 |
INSERT INTO Example
The following SQL statement inserts a new record in the “Customers” table:
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:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 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 |
| 92 | Cardinal | Tom B. Erichsen | Skagen 21 | Stavanger | 4006 | Norway |
Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is anย auto-incrementย field and will be generated automatically when a new record is inserted into the table.
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:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 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 |
| 92 | Cardinal | null | null | Stavanger | null | Norway |
Insert Multiple Rows
It is also possible to insert multiple rows in one statement.
To insert multiple rows of data, we use the sameย INSERT INTOย statement, but with multiple values:
Example
INSERTย INTOย Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES
(‘Cardinal’,ย ‘Tom B. Erichsen’,ย ‘Skagen 21’,ย ‘Stavanger’,ย ‘4006’,ย ‘Norway’),
(‘Greasy Burger’,ย ‘Per Olsen’,ย ‘Gateveien 15’,ย ‘Sandnes’,ย ‘4306’,ย ‘Norway’),
(‘Tasty Tee’,ย ‘Finn Egan’,ย ‘Streetroad 19B’,ย ‘Liverpool’,ย ‘L1 0AA’,ย ‘UK’);
Make sure you separate each set of values with a commaย ,.
The selection from the “Customers” table will now look like this:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 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 |
| 92 | Cardinal | Tom B. Erichsen | Skagen 21 | Stavanger | 4006 | Norway |
| 93 | Greasy Burger | Per Olsen | Gateveien 15 | Sandnes | 4306 | Norway |
| 94 | Tasty Tee | Finn Egan | Streetroad 19B | Liverpool | L1 0AA | UK |
SQLย NULL Values
What is a NULL Value?
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value.
Note:ย A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation!
How to Test for NULL Values?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use theย IS NULLย andย IS NOT NULLย operators instead.
IS NULL Syntax
SELECTย column_names
FROMย table_name
WHEREย column_nameย ISย NULL;
IS NOT NULL Syntax
SELECTย column_names
FROMย table_name
WHEREย column_nameย ISย NOTย NULL;
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
The IS NULL Operator
Theย IS NULLย operator is used to test for empty values (NULL values).
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.
The IS NOT NULL Operator
Theย IS NOT NULLย operator is used to test for non-empty values (NOT NULL values).
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;
SQLย UPDATEย Statement
The SQL UPDATE Statement
Theย UPDATEย statement is used to modify the existing records in a table.
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 used in the examples:
| 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 |
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:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 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 |
UPDATE Multiple Records
It is theย WHEREย clause that determines how many records will be updated.
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:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
| 2 | Ana Trujillo Emparedados y helados | Juan | Avda. de la Constituciรณn 2222 | Mรฉxico D.F. | 05021 | Mexico |
| 3 | Antonio Moreno Taquerรญa | Juan | 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 |
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:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Juan | Obere Str. 57 | Frankfurt | 12209 | Germany |
| 2 | Ana Trujillo Emparedados y helados | Juan | Avda. de la Constituciรณn 2222 | Mรฉxico D.F. | 05021 | Mexico |
| 3 | Antonio Moreno Taquerรญa | Juan | Mataderos 2312 | Mรฉxico D.F. | 05023 | Mexico |
| 4 | Around the Horn | Juan | 120 Hanover Sq. | London | WA1 1DP | UK |
| 5 | Berglunds snabbkรถp | Juan | Berguvsvรคgen 8 | Luleรฅ | S-958 22 | Sweden |
SQLย DELETEย Statement
The SQL DELETE Statement
Theย DELETEย statement is used to delete existing records in a table.
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!
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
SQL DELETE Example
The following SQL statement deletes the customer “Alfreds Futterkiste” from the “Customers” table:
Example
DELETEย FROMย Customersย WHEREย CustomerName=‘Alfreds Futterkiste’;
The “Customers” table will now look like this:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 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 |
Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
DELETEย FROMย table_name;
The following SQL statement deletes all rows in the “Customers” table, without deleting the table:
Example
DELETEย FROMย Customers;
Delete a Table
To delete the table completely, use theย DROP TABLEย statement:
Example
Remove the Customers table:
DROPย TABLEย Customers;
SQLย TOP, LIMIT, FETCH FIRST or ROWNUMย Clause
The SQL SELECT TOP Clause
Theย SELECT TOPย clause is used to specify the number of records to return.
Theย SELECT TOPย clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.
Example
Select only the first 3 records of the Customers table:
SELECTย TOPย 3ย *ย FROMย Customers;
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.
SQL Server / MS Access Syntax:
SELECTย TOPย number|percentย column_name(s)
FROMย table_name
WHEREย condition;
MySQL Syntax:
SELECTย column_name(s)
FROMย table_name
WHEREย condition
LIMITย number;
Oracle 12 Syntax:
SELECTย column_name(s)
FROMย table_name
ORDERย BYย column_name(s)
FETCHย FIRSTย numberย ROWS ONLY;
Older Oracle Syntax:
SELECTย column_name(s)
FROMย table_name
WHEREย ROWNUM <=ย number;
Older Oracle Syntax (with ORDER BY):
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 used in the examples:
| 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 |
LIMIT
The following SQL statement shows the equivalent example for MySQL:
Example
Select the first 3 records of the Customers table:
SELECTย *ย FROMย Customers
LIMITย 3;
FETCH FIRST
The following SQL statement shows the equivalent example for Oracle:
Example
Select the first 3 records of the Customers table:
SELECTย *ย FROMย Customers
FETCHย FIRSTย 3ย ROWS ONLY;
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;
ADD a WHERE CLAUSE
The following SQL statement selects the first three records from the “Customers” table, where the country is “Germany” (for SQL Server/MS Access):
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;
ADD the ORDER BY Keyword
Add theย ORDER BYย keyword when you want to sort the result, and return the first 3 records of the sorted result.
For SQL Server and MS Access:
Example
Sort the result reverse alphabetically by CustomerName, and return the first 3 records:
SELECTย TOPย 3ย *ย FROMย Customers
ORDERย BYย CustomerNameย DESC;
The following SQL statement shows the equivalent example for MySQL:
Example
SELECTย *ย FROMย Customers
ORDERย BYย CustomerNameย DESC
LIMITย 3;
The following SQL statement shows the equivalent example for Oracle:
Example
SELECTย *ย FROMย Customers
ORDERย BYย CustomerNameย DESC
FETCHย FIRSTย 3ย ROWS ONLY;
SQLย MIN() and MAX()ย Functions
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 Example
Find the lowest price:
SELECTย MIN(Price)
FROMย Products;
MAX Example
Find the highest price:
SELECTย MAX(Price)
FROM Products;
Syntax
SELECTย MIN(column_name)
FROMย table_name
WHEREย condition;
SELECTย MAX(column_name)
FROMย table_name
WHEREย condition;
Demo Database
Below is a selection from theย Productsย table used in the examples:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
Set Column Name (Alias)
When you useย MIN()ย orย MAX(), the returned column will be namedย MIN(field)ย orย MAX(field)ย by default. To give the column a new name, use theย ASย keyword:
Example
SELECTย MIN(Price)ย ASย SmallestPrice
FROMย Products;
SQLย COUNT()ย Function
The SQL COUNT() Function
Theย COUNT()ย function returns the number of rows that matches a specified criterion.
Example
Find the total number of products in theย Productsย table:
SELECTย COUNT(*)
FROM Products;
Syntax
SELECTย COUNT(column_name)
FROMย table_name
WHEREย condition;
Demo Database
Below is a selection from theย Productsย table used in the examples:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
Add a Where Clause
You can add aย WHEREย clause to specify conditions:
Example
Find the number of products whereย Priceย is higher than 20:
SELECTย COUNT(ProductID)
FROMย Products
WHEREย Price >ย 20;
Specify Column
You can specify a column name instead of the asterix symbolย (*).
If you specify a column instead ofย (*), NULL values will not be counted.
Example
Find the number of products where theย ProductNameย is not null:
SELECTย COUNT(ProductName)
FROM Products;
Ignore Duplicates
You can ignore duplicates by using theย DISTINCTย keyword in theย COUNTย function.
Ifย DISTINCTย is specified, rows with the same value for the specified column will be counted as one.
Example
How manyย differentย prices are there in theย Productsย table:
SELECTย COUNT(DISTINCTย Price)
FROM Products;
Use an Alias
Give the counted column a name by using theย ASย keyword.
Example
Name the column “number of records”:
SELECTย COUNT(*)ย ASย [numberย ofย records]
FROMย Products;
SQLย SUM()ย Function
The SQL SUM() Function
Theย SUM()ย function returns the total sum of a numeric column.
Example
Return the sum of allย Quantityย fields in theย OrderDetailsย table:
SELECTย SUM(Quantity)
FROM OrderDetails;
Syntax
SELECTย SUM(column_name)
FROMย table_name
WHEREย condition;
Demo Database
Below is a selection from theย OrderDetailsย table used in the examples:
| OrderDetailID | OrderID | ProductID | Quantity |
|---|---|---|---|
| 1 | 10248 | 11 | 12 |
| 2 | 10248 | 42 | 10 |
| 3 | 10248 | 72 | 5 |
| 4 | 10249 | 14 | 9 |
| 5 | 10249 | 51 | 40 |
Add a Where Clause
You can add aย WHEREย clause to specify conditions:
Example
Return the number of orders made for the product withย ProductIDย 11:
SELECTย SUM(Quantity)
FROMย OrderDetails
WHEREย ProductId =ย 11;
Use an Alias
Give the summarized column a name by using theย ASย keyword.
Example
Name the column “total”:
SELECTย SUM(Quantity)ย ASย total
FROM OrderDetails;
SUM() With an Expression
The parameter inside theย SUM()ย function can also be an expression.
If we assume that each product in theย OrderDetailsย column costs 10 dollars, we can find the total earnings in dollars by multiply each quantity with 10:
Example
Use an expression inside theย SUM()ย function:
SELECTย SUM(Quantity *ย 10)
FROMย OrderDetails;
We can also join theย OrderDetailsย table to theย Productsย table to find the actual amount, instead of assuming it is 10 dollars:
Example
Joinย OrderDetailsย withย Products, and useย SUM()ย to find the total amount:
SELECTย SUM(Price * Quantity)
FROMย OrderDetails
LEFTย JOINย Productsย ONย OrderDetails.ProductID = Products.ProductID;
SQLย AVG()ย Function
The SQL AVG() Function
Theย AVG()ย function returns the average value of a numeric column.
Example
Find the average price of all products:
SELECTย AVG(Price)
FROMย Products;
Note:ย NULL values are ignored.
Syntax
SELECTย AVG(column_name)
FROMย table_name
WHEREย condition;
Demo Database
Below is a selection from theย Productsย table used in the examples:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
Add a Where Clause
You can add aย WHEREย clause to specify conditions:
Example
Return the average price of products in category 1:
SELECTย AVG(Price)
FROMย Products
WHEREย CategoryID =ย 1;
Use an Alias
Give the AVG column a name by using theย ASย keyword.
Example
Name the column “average price”:
SELECTย AVG(Price)ย ASย [average price]
FROM Products;
Higher Than Average
To list all records with a higher price than average, we can use theย AVG()ย function in a sub query:
Example
Return all products with a higher price than the average price:
SELECTย *ย FROMย Products
WHEREย price >ย (SELECTย AVG(price)ย FROMย Products);
SQLย LIKEย Operator
The SQL LIKE Operator
Theย LIKEย operator is used in aย WHEREย clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with theย LIKEย operator:
- ย The percent signย
%ย represents zero, one, or multiple characters - ย The underscore signย
_ย represents one, single character
Example
Select all customers that starts with the letter “a”:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘a%’;
Syntax
SELECTย column1, column2, ...
FROMย table_name
WHEREย columnNย LIKEย pattern;
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
The _ Wildcard
Theย _ย wildcard represents a single character.
It can be any character or number, but eachย _ย represents one, and only one, character.
Example
Return all customers from a city that starts with ‘L’ followed by one wildcard character, then ‘nd’ and then two wildcard characters:
SELECTย *ย FROMย Customers
WHEREย cityย LIKEย ‘L_nd__’;
The % Wildcard
Theย %ย wildcard represents any number of characters, even zero characters.
Example
Return all customers from a city thatย containsย the letter ‘L’:
SELECTย *ย FROMย Customers
WHEREย cityย LIKEย ‘%L%’;
Starts With
To return records that starts with a specific letter or phrase, add theย %ย at the end of the letter or phrase.
Example
Return all customers that starts with ‘La’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘La%’;
Tip:ย You can also combine any number of conditions usingย ANDย orย ORย operators.
Example
Return all customers that starts with ‘a’ or starts with ‘b’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘a%’ย ORย CustomerNameย LIKEย ‘b%’;
Ends With
To return records that ends with a specific letter or phrase, add theย %ย at the beginning of the letter or phrase.
Example
Return all customers that ends with ‘a’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘%a’;
Tip:ย You can also combine “starts with” and “ends with”:
Example
Return all customers that starts with “b” and ends with “s”:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘b%s’;
Contains
To return records that contains a specific letter or phrase, add theย %ย both before and after the letter or phrase.
Example
Return all customers that contains the phrase ‘or’
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘%or%’;
Combine Wildcards
Any wildcard, likeย %ย andย _ย , can be used in combination with other wildcards.
Example
Return all customers that starts with “a” and are at least 3 characters in length:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘a__%’;
Example
Return all customers that have “r” in the second position:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘_r%’;
Without Wildcard
If no wildcard is specified, the phrase has to have an exact match to return a result.
Example
Return all customers from Spain:
SELECTย *ย FROMย Customers
WHEREย Countryย LIKEย ‘Spain’;
SQLย Wildcards
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.
Example
Return all customers that starts with the letter ‘a’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘a%’;
Wildcard Characters
| Symbol | Description |
|---|---|
| % | Represents zero or more characters |
| _ | Represents a single character |
| [] | Represents any single character within the brackets * |
| ^ | Represents any character not in the brackets * |
| – | Represents any single character within the specified range * |
| {} | Represents any escaped character ** |
* Not supported in PostgreSQL and MySQL databases.
** Supported only in Oracle databases.
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
Using the % Wildcard
Theย %ย wildcard represents any number of characters, even zero characters.
Example
Return all customers that ends with the pattern ‘es’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘%es’;
Example
Return all customers thatย containsย the pattern ‘mer’:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘%mer%’;
Using the _ Wildcard
Theย _ย wildcard represents a single character.
It can be any character or number, but eachย _ย represents one, and only one, character.
Example
Return all customers with aย Cityย starting with any character, followed by “ondon”:
SELECTย *ย FROMย Customers
WHEREย Cityย LIKEย ‘_ondon’;
Example
Return all customers with aย Cityย starting with “L”, followed by any 3 characters, ending with “on”:
SELECTย *ย FROMย Customers
WHEREย Cityย LIKEย ‘L___on’;
Using the [] Wildcard
Theย []ย wildcard returns a result ifย anyย of the characters inside gets a match.
Example
Return all customers starting with either “b”, “s”, or “p”:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘[bsp]%’;
Using the – Wildcard
Theย -ย wildcard allows you to specify a range of characters inside theย []ย wildcard.
Example
Return all customers starting with “a”, “b”, “c”, “d”, “e” or “f”:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘[a-f]%’;
Combine Wildcards
Any wildcard, likeย %ย andย _ย , can be used in combination with other wildcards.
Example
Return all customers that starts with “a” and are at least 3 characters in length:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘a__%’;
Example
Return all customers that have “r” in the second position:
SELECTย *ย FROMย Customers
WHEREย CustomerNameย LIKEย ‘_r%’;
Without Wildcard
If no wildcard is specified, the phrase has to have an exact match to return a result.
Example
Return all customers from Spain:
SELECTย *ย FROMย Customers
WHEREย Countryย LIKEย ‘Spain’;
Microsoft Access Wildcards
The Microsoft Access Database has some other wildcards:
| Symbol | Description | Example |
|---|---|---|
| * | Represents zero or more characters | bl* finds bl, black, blue, and blob |
| ? | Represents a single character | h?t finds hot, hat, and hit |
| [] | Represents any single character within the brackets | h[oa]t finds hot and hat, but not hit |
| ! | Represents any character not in the brackets | h[!oa]t finds hit, but not hot and hat |
| – | Represents any single character within the specified range | c[a-b]t finds cat and cbt |
| # | Represents any single numeric character | 2#5 finds 205, 215, 225, 235, 245, 255, 265, 275, 285, and 295 |
SQLย INย Operator
The SQL IN Operator
Theย INย operator allows you to specify multiple values in aย WHEREย clause.
Theย INย operator is a shorthand for multipleย ORย conditions.
Example
Return all customers from ‘Germany’, ‘France’, or ‘UK’
SELECTย *ย FROMย Customers
WHEREย Countryย INย (‘Germany’,ย ‘France’,ย ‘UK’);
Syntax
SELECTย column_name(s)
FROMย table_name
WHEREย column_nameย INย (value1,ย value2, ...);
Demo Database
Below is a selection from theย Customersย table used in the examples:
| 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 |
NOT IN
By using theย NOTย keyword in front of theย INย operator, you return all records that are NOT any of the values in the list.
Example
Return all customers that are NOT from ‘Germany’, ‘France’, or ‘UK’:
SELECTย *ย FROMย Customers
WHEREย Countryย NOTย INย (‘Germany’,ย ‘France’,ย ‘UK’);
IN (SELECT)
You can also useย INย with a subquery in theย WHEREย clause.
With a subquery you can return all records from the main query that are present in the result of the subquery.
Example
Return all customers that have an order in theย Ordersย table:
SELECTย *ย FROMย Customers
WHEREย CustomerIDย INย (SELECTย CustomerIDย FROM Orders);
NOT IN (SELECT)
The result in the example above returned 74 records, that means that there are 17 customers that haven’t placed any orders.
Let us check if that is correct, by using theย NOT INย operator.
Example
Return all customers that have NOT placed any orders in theย Ordersย table:
SELECTย *ย FROMย Customers
WHEREย CustomerIDย NOTย INย (SELECTย CustomerIDย FROMย Orders);
SQLย BETWEENย Operator
The SQL BETWEEN Operator
Theย BETWEENย operator selects values within a given range. The values can be numbers, text, or dates.
Theย BETWEENย operator is inclusive: begin and end values are included.
Example
Selects all products with a price between 10 and 20:
SELECTย *ย FROMย Products
WHEREย Priceย BETWEENย 10ย ANDย 20;
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 used in the examples:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
NOT BETWEEN
To display the products outside the range of the previous example, useย NOT BETWEEN:
Example
SELECTย *ย FROMย Products
WHEREย Priceย NOTย BETWEENย 10ย ANDย 20;
BETWEEN with IN
The following SQL statement selects all products with a price between 10 and 20. In addition, the CategoryID must be either 1,2, or 3:
Example
SELECTย *ย FROMย Products
WHEREย Priceย BETWEENย 10ย ANDย 20
ANDย CategoryIDย INย (1,2,3);
BETWEEN Text Values
The following SQL statement selects all products with a ProductName alphabetically between Carnarvon Tigers and Mozzarella di Giovanni:
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;
NOT BETWEEN Text Values
The following SQL statement selects all products with a ProductName not between Carnarvon Tigers and Mozzarella di Giovanni:
Example
SELECTย *ย FROMย Products
WHEREย ProductNameย NOTย BETWEENย ‘Carnarvon Tigers’ย ANDย ‘Mozzarella di Giovanni’
ORDERย BY ProductName;
BETWEEN Dates
The following SQL statement selects all orders with an OrderDate between ’01-July-1996′ and ’31-July-1996′:
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’;
Sample Table
Below is a selection from theย Ordersย table used in the examples:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10248 | 90 | 5 | 7/4/1996 | 3 |
| 10249 | 81 | 6 | 7/5/1996 | 1 |
| 10250 | 34 | 4 | 7/8/1996 | 2 |
| 10251 | 84 | 3 | 7/9/1996 | 1 |
| 10252 | 76 | 4 | 7/10/1996 | 2 |
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:
| OrderID | CustomerID | OrderDate |
|---|---|---|
| 10308 | 2 | 1996-09-18 |
| 10309 | 37 | 1996-09-19 |
| 10310 | 77 | 1996-09-20 |
Then, look at a selection from the “Customers” table:
| CustomerID | CustomerName | ContactName | Country |
|---|---|---|---|
| 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:
| OrderID | CustomerName | OrderDate |
|---|---|---|
| 10308 | Ana Trujillo Emparedados y helados | 9/18/1996 |
| 10365 | Antonio Moreno Taquerรญa | 11/27/1996 |
| 10383 | Around the Horn | 12/16/1996 |
| 10355 | Around the Horn | 11/15/1996 |
| 10278 | Berglunds snabbkรถp | 8/12/1996 |
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tablesLEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right tableRIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left tableFULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
ย ย
ย ย
ย ย 
SQLย INNER JOIN
INNER JOIN
Theย INNER JOINย keyword selects records that have matching values in both tables.
Let’s look at a selection of theย Productsย table:
| ProductID | ProductName | CategoryID | Price |
|---|---|---|---|
| 1 | Chais | 1 | 18 |
| 2 | Chang | 1 | 19 |
| 3 | Aniseed Syrup | 2 | 10 |
And a selection of theย Categoriesย table:
| CategoryID | CategoryName | Description |
|---|---|---|
| 1 | Beverages | Soft drinks, coffees, teas, beers, and ales |
| 2 | Condiments | Sweet and savory sauces, relishes, spreads, and seasonings |
| 3 | Confections | Desserts, candies, and sweet breads |
We will join the Products table with the Categories table, by using theย CategoryIDย field from both tables:
Example
Join Products and Categories with the INNER JOIN keyword:
SELECTย ProductID, ProductName, CategoryName
FROMย Products
INNERย JOINย Categoriesย ON Products.CategoryID = Categories.CategoryID;

Note:ย Theย INNER JOINย keyword returns only rows with a match in both tables. Which means that if you have a product with no CategoryID, or with a CategoryID that is not present in the Categories table, that record would not be returned in the result.
Syntax
SELECTย column_name(s)
FROMย table1
INNERย JOINย table2
ONย table1.column_nameย =ย table2.column_name;
Naming the Columns
It is a good practice to include the table name when specifying columns in the SQL statement.
Example
Specify the table names:
SELECTย Products.ProductID, Products.ProductName, Categories.CategoryName
FROMย Products
INNERย JOINย Categoriesย ONย Products.CategoryID = Categories.CategoryID;
The example above works without specifying table names, because none of the specified column names are present in both tables. If you try to includeย CategoryIDย in theย SELECTย statement, you will get an error if you do not specify the table name (becauseย CategoryIDย is present in both tables).
JOIN or INNER JOIN
JOINย andย INNER JOINย will return the same result.
INNERย is the default join type forย JOIN, so when you writeย JOINย the parser actually writesย INNER JOIN.
Example
JOIN is the same as INNER JOIN:
SELECTย Products.ProductID, Products.ProductName, Categories.CategoryName
FROMย Products
JOINย Categoriesย ON Products.CategoryID = Categories.CategoryID;
JOIN Three Tables
The following SQL statement selects all orders with customer and shipper information:
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);
SQLย LEFT JOINย Keyword
SQL LEFT JOIN Keyword
Theย LEFT JOINย keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.
LEFT JOIN Syntax
SELECTย column_name(s)
FROMย table1
LEFTย JOINย table2
ONย table1.column_nameย =ย table2.column_name;
Note:ย In some databases LEFT JOIN is called LEFT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the “Customers” table:
| 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 |
And a selection from the “Orders” table:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10308 | 2 | 7 | 1996-09-18 | 3 |
| 10309 | 37 | 3 | 1996-09-19 | 1 |
| 10310 | 77 | 8 | 1996-09-20 | 2 |
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).
SQLย RIGHT JOINย Keyword
SQL RIGHT JOIN Keyword
Theย RIGHT JOINย keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from the left side, if there is no match.
RIGHT JOIN Syntax
SELECTย column_name(s)
FROMย table1
RIGHTย JOINย table2
ONย table1.column_nameย =ย table2.column_name;
Note:ย In some databasesย RIGHT JOINย is calledย RIGHT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the “Orders” table:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10308 | 2 | 7 | 1996-09-18 | 3 |
| 10309 | 37 | 3 | 1996-09-19 | 1 |
| 10310 | 77 | 8 | 1996-09-20 | 2 |
And a selection from the “Employees” table:
| EmployeeID | LastName | FirstName | BirthDate | Photo |
|---|---|---|---|---|
| 1 | Davolio | Nancy | 12/8/1968 | EmpID1.pic |
| 2 | Fuller | Andrew | 2/19/1952 | EmpID2.pic |
| 3 | Leverling | Janet | 8/30/1963 | EmpID3.pic |
SQL RIGHT JOIN Example
The following SQL statement will return all employees, and any orders they might have placed:
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).
SQLย FULL OUTER JOINย Keyword
SQL FULL OUTER JOIN Keyword
Theย FULL OUTER JOINย keyword returns all records when there is a match in left (table1) or right (table2) table records.
Tip:ย FULL OUTER JOINย andย FULL JOINย are the same.
FULL OUTER JOIN Syntax
SELECTย column_name(s)
FROMย table1
FULLย OUTERย JOINย table2
ONย table1.column_nameย =ย table2.column_name
WHEREย condition;

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:
| 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 |
And a selection from the “Orders” table:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10308 | 2 | 7 | 1996-09-18 | 3 |
| 10309 | 37 | 3 | 1996-09-19 | 1 |
| 10310 | 77 | 8 | 1996-09-20 | 2 |
SQL FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders:
SELECTย Customers.CustomerName, Orders.OrderID
FROMย Customers
FULLย OUTERย JOINย Ordersย ONย Customers.CustomerID=Orders.CustomerID
ORDERย BYย Customers.CustomerName;
A selection from the result set may look like this:
| CustomerName | OrderID |
|---|---|
| Null | 10309 |
| Null | 10310 |
| Alfreds Futterkiste | Null |
| Ana Trujillo Emparedados y helados | 10308 |
| Antonio Moreno Taquerรญa | Null |
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.
SQLย Self Join
SQL Self Join
A self join is a regular join, but the table is joined with itself.
Self Join Syntax
SELECTย column_name(s)
FROMย table1 T1, table1 T2
WHEREย condition;
T1ย andย T2ย are different table aliases for the same table.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the “Customers” table:
| 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 |
SQL Self Join Example
The following SQL statement matches customers that are from the same city:
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;
SQLย UNIONย Operator
The SQL UNION Operator
Theย UNIONย operator is used to combine the result-set of two or moreย SELECTย statements.
- 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;
UNION ALL Syntax
Theย UNIONย operator selects only distinct values by default. To allow duplicate values, useย UNION ALL:
SELECTย column_name(s)ย FROMย table1
UNIONย ALL
SELECTย column_name(s)ย FROMย table2;
Note:ย The column names in the result-set are usually equal to the column names in the firstย SELECTย statement.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the “Customers” table:
| 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 |
And a selection from the “Suppliers” table:
| SupplierID | SupplierName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | London | EC1 4SD | UK |
| 2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA |
| 3 | Grandma Kelly’s Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA |
SQL UNION Example
The following SQL statement returns the cities (only distinct values) from both the “Customers” and the “Suppliers” table:
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!
SQL UNION ALL Example
The following SQL statement returns the cities (duplicate values also) from both the “Customers” and the “Suppliers” table:
Example
SELECTย Cityย FROMย Customers
UNIONย ALL
SELECTย Cityย FROMย Suppliers
ORDERย BY City;
SQL UNION With WHERE
The following SQL statement returns the German cities (only distinct values) from both the “Customers” and the “Suppliers” table:
Example
SELECTย City, Countryย FROMย Customers
WHEREย Country=‘Germany’
UNION
SELECTย City, Countryย FROMย Suppliers
WHEREย Country=‘Germany’
ORDERย BY City;
SQL UNION ALL With WHERE
The following SQL statement returns the German cities (duplicate values also) from both the “Customers” and the “Suppliers” table:
Example
SELECTย City, Countryย FROMย Customers
WHEREย Country=‘Germany’
UNIONย ALL
SELECTย City, Countryย FROMย Suppliers
WHEREย Country=‘Germany’
ORDERย BY City;
Another UNION Example
The following SQL statement lists all customers and suppliers:
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”.
SQLย GROUP BYย Statement
The SQL GROUP BY Statement
Theย GROUP BYย statement groups rows that have the same values into summary rows, like “find the number of customers in each country”.
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:
| 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 |
SQL GROUP BY Examples
The following SQL statement lists the number of customers in each country:
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;
Demo Database
Below is a selection from the “Orders” table in the Northwind sample database:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10248 | 90 | 5 | 1996-07-04 | 3 |
| 10249 | 81 | 6 | 1996-07-05 | 1 |
| 10250 | 34 | 4 | 1996-07-08 | 2 |
And a selection from the “Shippers” table:
| ShipperID | ShipperName |
|---|---|
| 1 | Speedy Express |
| 2 | United Package |
| 3 | Federal Shipping |
GROUP BY With JOIN Example
The following SQL statement lists the number of orders sent by each shipper:
Example
SELECTย Shippers.ShipperName,ย COUNT(Orders.OrderID)ย ASย NumberOfOrdersย FROMย Orders
LEFTย JOINย Shippersย ONย Orders.ShipperID = Shippers.ShipperID
GROUPย BYย ShipperName;
SQLย HAVINGย Clause
The SQL HAVING Clause
Theย HAVINGย clause was added to SQL because theย WHEREย keyword cannot be used with aggregate functions.
HAVING Syntax
SELECTย column_name(s)
FROMย table_name
WHEREย condition
GROUPย BYย column_name(s)
HAVINGย condition
ORDERย BYย column_name(s);
Demo Database
Below is a selection from the “Customers” table in 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 |
SQL HAVING Examples
The following SQL statement lists the number of customers in each country. Only include countries with more than 5 customers:
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:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10248 | 90 | 5 | 1996-07-04 | 3 |
| 10249 | 81 | 6 | 1996-07-05 | 1 |
| 10250 | 34 | 4 | 1996-07-08 | 2 |
And a selection from the “Employees” table:
| EmployeeID | LastName | FirstName | BirthDate | Photo | Notes |
|---|---|---|---|---|---|
| 1 | Davolio | Nancy | 1968-12-08 | EmpID1.pic | Education includes a BA…. |
| 2 | Fuller | Andrew | 1952-02-19 | EmpID2.pic | Andrew received his BTS…. |
| 3 | Leverling | Janet | 1963-08-30 | EmpID3.pic | Janet has a BS degree…. |
More HAVING Examples
The following SQL statement lists the employees that have registered more than 10 orders:
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;
SQLย EXISTS Operator
The SQL EXISTS Operator
Theย EXISTSย operator is used to test for the existence of any record in a subquery.
Theย EXISTSย operator returns TRUE if the subquery returns one or more records.
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:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
And a selection from the “Suppliers” table:
| SupplierID | SupplierName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | London | EC1 4SD | UK |
| 2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA |
| 3 | Grandma Kelly’s Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA |
| 4 | Tokyo Traders | Yoshi Nagase | 9-8 Sekimai Musashino-shi | Tokyo | 100 | Japan |
SQL EXISTS Examples
The following SQL statement returns TRUE and lists the suppliers with a product price less than 20:
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
WHEREย EXISTSย (SELECTย ProductNameย FROMย Productsย WHEREย Products.SupplierID = Suppliers.supplierIDย ANDย Price =ย 22);
SQLย ANY and ALL Operators
The SQL ANY and ALL Operators
Theย ANYย andย ALLย operators allow you to perform a comparison between a single column value and a range of other values.
The SQL ANY Operator
Theย ANYย operator:
- returns a boolean value as a result
- returns TRUE if ANY of the subquery values meet the condition
ANYย means that the condition will be true if the operation is true for any of the values in the range.
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 <=).
The SQL ALL Operator
Theย ALLย operator:
- returns a boolean value as a result
- returns TRUE if ALL of the subquery values meet the condition
- is used withย
SELECT,ยWHEREย andยHAVINGย statements
ALLย means that the condition will be true only if the operation is true for all values in the range.
ALL Syntax With SELECT
SELECTย ALLย column_name(s)
FROMย table_name
WHEREย condition;
ALL Syntax With WHERE or HAVING
SELECTย column_name(s)
FROMย table_name
WHEREย column_name operatorย ALL
(SELECTย column_name
FROMย table_name
WHEREย condition);
Note:ย Theย operatorย must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Demo Database
Below is a selection from theย “Products”ย table in the Northwind sample database:
| ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
|---|---|---|---|---|---|
| 1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
| 2 | Chang | 1 | 1 | 24 – 12 oz bottles | 19 |
| 3 | Aniseed Syrup | 1 | 2 | 12 – 550 ml bottles | 10 |
| 4 | Chef Anton’s Cajun Seasoning | 2 | 2 | 48 – 6 oz jars | 22 |
| 5 | Chef Anton’s Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
| 6 | Grandma’s Boysenberry Spread | 3 | 2 | 12 – 8 oz jars | 25 |
| 7 | Uncle Bob’s Organic Dried Pears | 3 | 7 | 12 – 1 lb pkgs. | 30 |
| 8 | Northwoods Cranberry Sauce | 3 | 2 | 12 – 12 oz jars | 40 |
| 9 | Mishi Kobe Niku | 4 | 6 | 18 – 500 g pkgs. | 97 |
And a selection from theย “OrderDetails”ย table:
| OrderDetailID | OrderID | ProductID | Quantity |
|---|---|---|---|
| 1 | 10248 | 11 | 12 |
| 2 | 10248 | 42 | 10 |
| 3 | 10248 | 72 | 5 |
| 4 | 10249 | 14 | 9 |
| 5 | 10249 | 51 | 40 |
| 6 | 10250 | 41 | 10 |
| 7 | 10250 | 51 | 35 |
| 8 | 10250 | 65 | 15 |
| 9 | 10251 | 22 | 6 |
| 10 | 10251 | 57 | 15 |
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);
SQL ALL Examples
The following SQL statement lists ALL the product names:
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);
SQLย SELECT INTOย Statement
The SQL SELECT INTO Statement
Theย SELECT INTOย statement copies data from one table into a new table.
SELECT INTO Syntax
Copy all columns into a new table:
SELECTย *
INTOย newtableย [INย externaldb]
FROMย oldtable
WHEREย condition;
Copy only some columns into a new table:
SELECTย column1,ย column2,ย column3, …
INTOย newtableย [INย externaldb]
FROMย oldtable
WHEREย condition;
The new table will be created with the column-names and types as defined in the old table. You can create new column names using theย ASย clause.
SQL SELECT INTO Examples
The following SQL statement creates a backup copy of Customers:
SELECTย *ย INTOย CustomersBackup2017
FROMย Customers;
The following SQL statement uses theย INย clause to copy the table into a new table in another database:
SELECTย *ย INTOย CustomersBackup2017ย INย ‘Backup.mdb’
FROMย Customers;
The following SQL statement copies only a few columns into a new table:
SELECTย CustomerName, ContactNameย INTOย CustomersBackup2017
FROMย Customers;
The following SQL statement copies only the German customers into a new table:
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:
SELECTย *ย INTOย newtable
FROMย oldtable
WHEREย 1ย =ย 0;
SQLย INSERT INTO SELECTย Statement
The SQL INSERT INTO SELECT Statement
Theย INSERT INTO SELECTย statement copies data from one table and inserts it into another table.
Theย INSERT INTO SELECTย statement requires that the data types in source and target tables match.
Note:ย The existing records in the target table are unaffected.
INSERT INTO SELECT Syntax
Copy all columns from one table to another table:
INSERTย INTOย table2
SELECTย *ย FROMย table1
WHEREย condition;
Copy only some columns from one table into another table:
INSERTย INTOย table2ย (column1,ย column2,ย column3, …)
SELECTย column1,ย column2,ย column3, …
FROMย table1
WHEREย condition;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the “Customers” table:
| 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 |
And a selection from the “Suppliers” table:
| SupplierID | SupplierName | ContactName | Address | City | Postal Code | Country |
|---|---|---|---|---|---|---|
| 1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | Londona | EC1 4SD | UK |
| 2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA |
| 3 | Grandma Kelly’s Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA |
SQL INSERT INTO SELECT Examples
Example
Copy “Suppliers” into “Customers” (the columns that are not filled with data, will contain NULL):
INSERTย INTOย Customers (CustomerName,ย City, Country)
SELECTย SupplierName, City, Countryย FROMย Suppliers;
Example
Copy “Suppliers” into “Customers” (fill all columns):
INSERTย INTOย Customers (CustomerName, ContactName, Address, City, PostalCode,ย Country)
SELECTย SupplierName, ContactName, Address, City, PostalCode,ย Countryย FROMย Suppliers;
Example
Copy only the German suppliers into “Customers”:
INSERTย INTOย Customers (CustomerName,ย City, Country)
SELECTย SupplierName, City, Countryย FROMย Suppliers
WHEREย Country=‘Germany’;
SQLย CASEย Expression
The SQL CASE Expression
Theย CASEย expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in theย ELSEย clause.
If there is noย ELSEย part and no conditions are true, it returns NULL.
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:
| OrderDetailID | OrderID | ProductID | Quantity |
|---|---|---|---|
| 1 | 10248 | 11 | 12 |
| 2 | 10248 | 42 | 10 |
| 3 | 10248 | 72 | 5 |
| 4 | 10249 | 14 | 9 |
| 5 | 10249 | 51 | 40 |
SQL CASE Examples
The following SQL goes through conditions and returns a value when the first condition is met:
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’
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);
SQLย NULLย Functions
SQL IFNULL(), ISNULL(), COALESCE(), and NVL() Functions
Look at the following “Products” table:
| P_Id | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder |
|---|---|---|---|---|
| 1 | Jarlsberg | 10.45 | 16 | 15 |
| 2 | Mascarpone | 32.56 | 23 | |
| 3 | Gorgonzola | 15.67 | 9 | 20 |
Suppose that the “UnitsOnOrder” column is optional, and may contain NULL values.
Look at the following SELECT statement:
SELECTย ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROMย Products;
In the example above, if any of the “UnitsOnOrder” values are NULL, the result will be NULL.
Solutions
MySQL
The MySQLย IFNULL()ย function lets you return an alternative value if an expression is NULL:
SELECTย ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder,ย 0))
FROMย Products;
or we can use theย COALESCE()ย function, like this:
SELECTย ProductName, UnitPrice * (UnitsInStock +ย COALESCE(UnitsOnOrder,ย 0))
FROMย Products;
SQL Server
The SQL Serverย ISNULL()ย function lets you return an alternative value when an expression is NULL:
SELECTย ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder,ย 0))
FROMย Products;
or we can use theย COALESCE()ย function, like this:
SELECTย ProductName, UnitPrice * (UnitsInStock +ย COALESCE(UnitsOnOrder,ย 0))
FROMย Products;
MS Access
The MS Accessย IsNull()ย function returns TRUE (-1) if the expression is a null value, otherwise FALSE (0):
SELECTย ProductName, UnitPrice * (UnitsInStock + IIF(IsNull(UnitsOnOrder),ย 0, UnitsOnOrder))
FROMย Products;
Oracle
The Oracleย NVL()ย function achieves the same result:
SELECTย ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder,ย 0))
FROMย Products;
or we can use theย COALESCE()ย function, like this:
SELECTย ProductName, UnitPrice * (UnitsInStock +ย COALESCE(UnitsOnOrder,ย 0))
FROMย Products;
SQLย Stored Procedures for SQL Server
What is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.
Stored Procedure Syntax
CREATEย PROCEDUREย procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXECย procedure_name;
Demo Database
Below is a selection from the “Customers” table in 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 |
Stored Procedure Example
The following SQL statement creates a stored procedure named “SelectAllCustomers” that selects all records from the “Customers” table:
Example
CREATEย PROCEDUREย SelectAllCustomers
AS
SELECTย *ย FROMย Customers
GO;
Execute the stored procedure above as follows:
Example
EXEC SelectAllCustomers;
Stored Procedure With One Parameter
The following SQL statement creates a stored procedure that selects Customers from a particular City from the “Customers” table:
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’;
Stored Procedure With Multiple Parameters
Setting up multiple parameters is very easy. Just list each parameter and the data type separated by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a particular City with a particular PostalCode from the “Customers” table:
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: Comments are not supported in Microsoft Access databases!
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ย */.
Any text between /* and */ will be ignored.
The following example uses a multi-line comment as an explanation:
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;
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
SQL Arithmetic Operators
| Operator | Description | |
|---|---|---|
| + | Add | |
| – | Subtract | |
| * | Multiply | |
| / | Divide | |
| % | Modulo |
SQL Bitwise Operators
| Operator | Description |
|---|---|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | Bitwise exclusive OR |
SQL Comparison Operators
| Operator | Description | |
|---|---|---|
| = | Equal to | |
| > | Greater than | |
| < | Less than | |
| >= | Greater than or equal to | |
| <= | Less than or equal to | |
| <> | Not equal to |
SQL Compound Operators
| Operator | Description |
|---|---|
| += | Add equals |
| -= | Subtract equals |
| *= | Multiply equals |
| /= | Divide equals |
| %= | Modulo equals |
| &= | Bitwise AND equals |
| ^-= | Bitwise exclusive equals |
| |*= | Bitwise OR equals |
SQL Logical Operators
| Operator | Description | |
|---|---|---|
| ALL | TRUE if all of the subquery values meet the condition | |
| AND | TRUE if all the conditions separated by AND is TRUE | |
| ANY | TRUE if any of the subquery values meet the condition | |
| BETWEEN | TRUE if the operand is within the range of comparisons | |
| EXISTS | TRUE if the subquery returns one or more records | |
| IN | TRUE if the operand is equal to one of a list of expressions | |
| LIKE | TRUE if the operand matches a pattern | |
| NOT | Displays a record if the condition(s) is NOT TRUE | |
| OR | TRUE if any of the conditions separated by OR is TRUE | |
| SOME | TRUE if any of the subquery values meet the condition |

