Monday, October 19, 2015

SQL Wildcard Characters

SQL Wildcard Characters

In SQL, wildcard characters are used with the SQL LIKE operator.
SQL wildcards are used to search for data within a table. 
With SQL, the wildcards are:
Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist]
or
[!charlist]
Matches only a character NOT specified within the brackets

Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:

ustomerID 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 SQL % Wildcard

The following SQL statement selects all customers with a City starting with "ber":

Example

SELECT * FROM Customers
WHERE City LIKE 'ber%'; 
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 
14  Chop-suey Chinese  Yang Wang  Hauptstr. 29  Bern  3012  Switzerland 
49  Magazzini Alimentari Riuniti  Giovanni Rovelli  Via Ludovico il Moro 22  Bergamo  24100  Italy 
 

The following SQL statement selects all customers with a City containing the pattern "es": 

Example

SELECT * FROM Customers
WHERE City LIKE '%es%'; 
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
12  Cactus Comidas para llevar  Patricio Simpson  Cerrito 333  Buenos Aires  1010  Argentina 
18  Du monde entier  Janine Labrune  67, rue des Cinquante Otages  Nantes  44000  France 
26  France restauration  Carine Schmitt  54, rue Royale  Nantes  44000  France 
38  Island Trading  Helen Bennett  Garden House Crowther Way  Cowes  PO31 7PJ  UK 
40  La corne d'abondance  Daniel Tonini  67, avenue de l'Europe  Versailles  78000  France 
 
 

Using the SQL _ Wildcard

The following SQL statement selects all customers with a City starting with any character, followed by "erlin":

Example

SELECT * FROM Customers
WHERE City LIKE '_erlin'; 
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 
 
 
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';
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Around the Horn  Thomas Hardy  120 Hanover Sq.  London  WA1 1DP  UK 
11  B's Beverages  Victoria Ashworth  Fauntleroy Circus  London  EC2 5NT  UK 
16  Consolidated Holdings  Elizabeth Brown  Berkeley Gardens 12 Brewery   London  WX1 6LT  UK 
19  Eastern Connection  Ann Devon  35 King George  London  WX3 6FW  UK 
 
 The following SQL statement selects all customers with a City starting with "b", "s", or "p":

Example

SELECT * FROM Customers
WHERE City LIKE '[bsp]%'; 
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 
Blondel père et fils  Frédérique Citeaux  24, place Kléber  Strasbourg  67000  France 
12  Cactus Comidas para llevar  Patricio Simpson  Cerrito 333  Buenos Aires  1010  Argentina 
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 
 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]%';
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 
12  Cactus Comidas para llevar  Patricio Simpson  Cerrito 333  Buenos Aires  1010  Argentina 
14  Chop-suey Chinese  Yang Wang  Hauptstr. 29  Bern  3012  Switzerland 
17  Drachenblut Delikatessend  Sven Ottlieb  Walserweg 21  Aachen  52066  Germany 
24  Folk och fä HB  Maria Larsson  Åkergatan 24  Bräcke  S-844 67  Sweden 
29  Galería del gastrónomo  Eduardo Saavedra  Rambla de Cataluña, 23  Barcelona  08022  Spain 
31  Gourmet Lanchonetes  André Fonseca  Av. Brasil, 442  Campinas  04876-786  Brazil 
 
The following SQL statement selects all customers with a City NOT starting with "b", "s", or "p":

Example

SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

or

SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Ana Trujillo Emparedados y helados  Ana Trujillo  Avda. de la Constitución 2222  México D.F.  05021  Mexico 
Antonio Moreno Taquería  Antonio Moreno  Mataderos 2312  México D.F.  05023  Mexico 
Around the Horn  Thomas Hardy  120 Hanover Sq.  London  WA1 1DP  UK 
Berglunds snabbköp  Christina Berglund  Berguvsvägen 8  Luleå  S-958 22  Sweden 
Blauer See Delikatessen  Hanna Moos  Forsterstr. 57  Mannheim  68306  Germany 
 

Sunday, October 18, 2015

SELECT TOP Clause,

SQL Server / MS Access Syntax


SELECT TOP number|percent column_name(s)
FROM table_name;



SQL SELECT TOP Equivalent in MySQL and Oracle


MySQL Syntax


SELECT column_name(s)
FROM table_name
LIMIT number;

Example


SELECT *
FROM Persons
LIMIT 5;
Using the SQL % Wildcard The following SQL statement selects all customers with a City starting with "ber": Example SELECT * FROM Customers WHERE City LIKE 'ber%';

Oracle Syntax


SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;

Example


SELECT *
FROM Persons
WHERE ROWNUM <=5;

Example


SELECT TOP 2 * FROM Customers; 

Example


SELECT TOP 50 PERCENT * FROM Customers;

The SQL LIKE Operator

The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax


SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

Example


SELECT * FROM Customers
WHERE City LIKE 's%'; 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Blondel père et fils  Frédérique Citeaux  24, place Kléber  Strasbourg  67000  France 
15  Comércio Mineiro  Pedro Afonso  Av. dos Lusíadas, 23  São Paulo  05432-043  Brazil 
21  Familia Arquibaldo  Aria Cruz  Rua Orós, 92  São Paulo  05442-030  Brazil 
30  Godos Cocina Típica  José Pedro Freyre  C/ Romero, 33  Sevilla  41101  Spain 
35  HILARIÓN-Abastos  Carlos Hernández  Carrera 22 con Ave. Carlos Soublette #8-35  San Cristóbal  5022  Venezuela 

Example


SELECT * FROM Customers
WHERE City LIKE '%s'; 
ustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
12  Cactus Comidas para llevar  Patricio Simpson  Cerrito 333  Buenos Aires  1010  Argentina 
18  Du monde entier  Janine Labrune  67, rue des Cinquante Otages  Nantes  44000  France 
26  France restauration  Carine Schmitt  54, rue Royale  Nantes  44000  France 
31  Gourmet Lanchonetes  André Fonseca  Av. Brasil, 442  Campinas  04876-786  Brazil 
33  GROSELLA-Restaurante  Manuel Pereira  5ª Ave. Los Palos Grandes  Caracas  1081  Venezuela 
38  Island Trading  Helen Bennett  Garden House Crowther Way  Cowes  PO31 7PJ  UK 
40  La corne d'abondance  Daniel Tonini  67, avenue de l'Europe  Versailles  78000  France 
50  Maison Dewey  Catherine Dewey  Rue Joseph-Bens 532  Bruxelles  B-1180  Belgium 
54  Océano Atlántico Ltda.  Yvonne Moncada  Ing. Gustavo Moncada 8585 Piso 20-A  Buenos Aires  1010  Argentina 
57  Paris spécialités  Marie Bertrand  265, boulevard Charonne  Paris  75012  France 
64  Rancho grande  Sergio Gutiérrez  Av. del Libertador 900  Buenos Aires  1010  Argentina 
74  Spécialités du monde  Dominique Perrier  25, rue Lauriston  Paris  75016  France 
83  Vaffeljernet  Palle Ibsen  Smagsløget 45  Århus  8200  Denmark 

Example


SELECT * FROM Customers
WHERE Country LIKE '%land%'; 
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
14  Chop-suey Chinese  Yang Wang  Hauptstr. 29  Bern  3012  Switzerland 
37  Hungry Owl All-Night Grocers  Patricia McKenna  8 Johnstown Road  Cork  Ireland 
68  Richter Supermarkt  Michael Holz  Grenzacherweg 237  Genève  1203  Switzerland 
87  Wartian Herkku  Pirkko Koskitalo  Torikatu 38  Oulu  90110  Finland 
90  Wilman Kala  Matti Karttunen  Keskuskatu 45  Helsinki  21240  Finland 
91  Wolski  Zbyszek  ul. Filtrowa 68  Walla  01-012  Poland 
he following SQL statement selects all customers with Country NOT containing the pattern "land":

Example


SELECT * FROM Customers
WHERE Country NOT LIKE '%land%'; 

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 
Ana Trujillo Emparedados y helados  Ana Trujillo  Avda. de la Constitución 2222  México D.F.  05021  Mexico 
Antonio Moreno Taquería  Antonio Moreno  Mataderos 2312  México D.F.  05023  Mexico 
Around the Horn  Thomas Hardy  120 Hanover Sq.  London  WA1 1DP  UK 
Berglunds snabbköp  Christina Berglund  Berguvsvägen 8  Luleå  S-958 22  Sweden 
Blauer See Delikatessen  Hanna Moos  Forsterstr. 57  Mannheim  68306  Germany 
Blondel père et fils  Frédérique Citeaux  24, place Kléber  Strasbourg  67000  France 
Bólido Comidas preparadas  Martín Sommer  C/ Araquil, 67  Madrid  28023  Spain 
Bon app'  Laurence Lebihans  12, rue des Bouchers  Marseille  13008  France 















































SQL DELETE Statement

The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax

DELETE FROM table_name
WHERE some_column=some_value
 

Example

DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders'; 
 

Delete All Data

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;

or

DELETE * FROM table_name;
 
 

SQL INSERT INTO, and Update Statements

SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only their values:

INSERT INTO table_name
VALUES (value1,value2,value3,...);
 
The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
 
"Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
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

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
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
92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway
 
 

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 row, but only insert data in the "CustomerName", "City", and "Country" columns (and the CustomerID field will of course also be updated automatically):

Example

INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
 
The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
 
"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
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 UPDATE Example

Assume we wish to update the customer "Alfreds Futterkiste" with a new contact person and city.
We use the following SQL statement:

Example

UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
 

SQL WHERE AND & OR Operators Syntax ORDER BY Keyword

SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;


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


WHERE Clause Example

The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table:

Example

SELECT * FROM Customers
WHERE Country='Mexico';


CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Ana Trujillo Emparedados y helados  Ana Trujillo  Avda. de la Constitución 2222  México D.F.  05021  Mexico 
Antonio Moreno Taquería  Antonio Moreno  Mataderos 2312  México D.F.  05023  Mexico 

AND & OR Operators

Example

SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin'; 
Number of Records: 1
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 

OR Operator Example

The following SQL statement selects all customers from the city "Berlin" OR "München", in the "Customers" table: 

Example

SELECT * FROM Customers
WHERE City='Berlin'
OR City='München'; 

Number of Records:
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
Alfreds Futterkiste  Maria Anders  Obere Str. 57  Berlin  12209  Germany 








Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).
The following SQL statement selects all customers from the country "Germany" AND the city must be equal to "Berlin" OR "München", in the "Customers" table:

Example

SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');

SQL ORDER BY Syntax

SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;


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;


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;


ORDER BY Several Columns Example

The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" and the "CustomerName" column:

Example

SELECT * FROM Customers
ORDER BY Country, CustomerName;
 

ORDER BY Several Columns Example 2

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 SELECT DISTINCT Syntax

SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name,column_name
FROM table_name;
 
"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
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

Example

SELECT DISTINCT City FROM Customers;
 

SQL Quereis SELECT * FROM Customers;

"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
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).

Some of The Most Important SQL Commands

  • SELECT - extracts data from a database
  • UPDATE - updates data in a database
  • 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 
The following SQL statement selects all the records in the "Customers" table:

 SELECT * FROM Customers; 

SQL is NOT case sensitive: select is the same as SELECT

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

SQL SELECT Syntax

SELECT column_name,column_name
FROM table_name;
 
SELECT * FROM table_name;
 

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;