SQL Tutorial

SQL is a standard language for storing, manipulating and retrieving data in databases.

Our SQL tutorial will teach you how to use SQL in: MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems.Start learning SQL now »

Examples in Each Chapter

With our online SQL editor, you can edit the SQL statements, and click on a button to view the result.

Example

SELECT * FROM Customers;

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:

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.

Database Tables

A database most often contains one or more tables. Each table is identified by a name (e.g. “Customers” or “Orders”). Tables contain records (rows) with data.

In this tutorial we will use the well-known Northwind sample database (included in MS Access and MS SQL Server).

Below is a selection from the “Customers” table:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

The table above contains five records (one for each customer) and seven columns (CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).


SQL Statements

Most of the actions you need to perform on a database are done with SQL statements.

The following SQL statement selects all the records in the “Customers” table:

Example

SELECT * FROM Customers;Try it Yourself »

In this tutorial we will teach you all about the different SQL statements.



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 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 SQL SELECT Statement

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax

SELECT column1, column2, …
FROM table_name;

Here, column1, column2, … are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax:SELECT * FROM table_name;


Demo Database

Below is a selection from the “Customers” table in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SELECT Column Example

The following SQL statement selects the “CustomerName” and “City” columns from the “Customers” table:

Example

SELECT CustomerName, City FROM Customers;Try it Yourself »


SELECT * Example

The following SQL statement selects all the columns from the “Customers” table:

Example

SELECT * FROM Customers;

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

SELECT DISTINCT Syntax

SELECT DISTINCT column1, column2, …
FROM table_name;


Demo Database

Below is a selection from the “Customers” table in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

SELECT Example Without DISTINCT

The following SQL statement selects ALL (including the duplicates) values from the “Country” column in the “Customers” table:

Example

SELECT Country FROM Customers;Try it Yourself »

Now, let us use the DISTINCT keyword with the above SELECT statement and see the result.



SELECT DISTINCT Examples

The following SQL statement selects only the DISTINCT values from the “Country” column in the “Customers” table:

Example

SELECT DISTINCT Country FROM Customers;Try it Yourself »

The following SQL statement lists the number of different (distinct) customer countries:

Example

SELECT COUNT(DISTINCT Country) FROM Customers;Try it Yourself »

Note: The example above will not work in Firefox! Because COUNT(DISTINCT column_name) is not supported in Microsoft Access databases. Firefox is using Microsoft Access in our examples.

Here is the workaround for MS Access:

Example

SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);Try it Yourself »


Test Yourself With Exercises

Exercise:

Select all the different values from the Country column in the Customers table.

The SQL WHERE Clause

The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

WHERE Syntax

SELECT column1, column2, …
FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE statement, etc.!


Demo Database

Below is a selection from the “Customers” table in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

https://8c7beb2959bfb5ec29c89e20c8cfac81.safeframe.googlesyndication.com/safeframe/1-0-37/html/container.html

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’;Try it Yourself »


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;Try it Yourself »


Operators in The WHERE Clause

The following operators can be used in the WHERE clause:

OperatorDescriptionExample
=EqualTry it
>Greater thanTry it
<Less thanTry it
>=Greater than or equalTry it
<=Less than or equalTry it
<>Not equal. Note: In some versions of SQL this operator may be written as !=Try it
BETWEENBetween a certain rangeTry it
LIKESearch for a patternTry it
INTo specify multiple possible values for a columnTry it

Test Yourself With Exercises

Exercise:

Select all records where the City column has the value “Berlin”.

The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

  • The AND operator displays a record if all the conditions separated by AND are TRUE.
  • The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax

SELECT column1, column2, …
FROM table_name
WHERE condition1 AND condition2 AND condition3 …;

OR Syntax

SELECT column1, column2, …
FROM table_name
WHERE condition1 OR condition2 OR condition3 …;

NOT Syntax

SELECT column1, column2, …
FROM table_name
WHERE NOT condition;


Demo Database

The table below shows the complete “Customers” table from the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden
6Blauer See DelikatessenHanna MoosForsterstr. 57Mannheim68306Germany
7Blondel père et filsFrédérique Citeaux24, place KléberStrasbourg67000France
8Bólido Comidas preparadasMartín SommerC/ Araquil, 67Madrid28023Spain
9Bon app’Laurence Lebihans12, rue des BouchersMarseille13008France
10Bottom-Dollar MarketseElizabeth Lincoln23 Tsawassen Blvd.TsawassenT2F 8M4Canada
11B’s BeveragesVictoria AshworthFauntleroy CircusLondonEC2 5NTUK
12Cactus Comidas para llevarPatricio SimpsonCerrito 333Buenos Aires1010Argentina
13Centro comercial MoctezumaFrancisco ChangSierras de Granada 9993México D.F.05022Mexico
14Chop-suey ChineseYang WangHauptstr. 29Bern3012Switzerland
15Comércio MineiroPedro AfonsoAv. dos Lusíadas, 23São Paulo05432-043Brazil
16Consolidated HoldingsElizabeth BrownBerkeley Gardens 12 BreweryLondonWX1 6LTUK
17Drachenblut DelikatessendSven OttliebWalserweg 21Aachen52066Germany
18Du monde entierJanine Labrune67, rue des Cinquante OtagesNantes44000France
19Eastern ConnectionAnn Devon35 King GeorgeLondonWX3 6FWUK
20Ernst HandelRoland MendelKirchgasse 6Graz8010Austria
21Familia ArquibaldoAria CruzRua Orós, 92São Paulo05442-030Brazil
22FISSA Fabrica Inter. Salchichas S.A.Diego RoelC/ Moralzarzal, 86Madrid28034Spain
23Folies gourmandesMartine Rancé184, chaussée de TournaiLille59000France
24Folk och fä HBMaria LarssonÅkergatan 24BräckeS-844 67Sweden
25FrankenversandPeter FrankenBerliner Platz 43München80805Germany
26France restaurationCarine Schmitt54, rue RoyaleNantes44000France
27Franchi S.p.A.Paolo AccortiVia Monte Bianco 34Torino10100Italy
28Furia Bacalhau e Frutos do MarLino RodriguezJardim das rosas n. 32Lisboa1675Portugal
29Galería del gastrónomoEduardo SaavedraRambla de Cataluña, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
31Gourmet LanchonetesAndré FonsecaAv. Brasil, 442Campinas04876-786Brazil
32Great Lakes Food MarketHoward Snyder2732 Baker Blvd.Eugene97403USA
33GROSELLA-RestauranteManuel Pereira5ª Ave. Los Palos GrandesCaracas1081Venezuela
34Hanari CarnesMario PontesRua do Paço, 67Rio de Janeiro05454-876Brazil
35HILARIÓN-AbastosCarlos HernándezCarrera 22 con Ave. Carlos Soublette #8-35San Cristóbal5022Venezuela
36Hungry Coyote Import StoreYoshi LatimerCity Center Plaza 516 Main St.Elgin97827USA
37Hungry Owl All-Night GrocersPatricia McKenna8 Johnstown RoadCorkIreland
38Island TradingHelen BennettGarden House Crowther WayCowesPO31 7PJUK
39Königlich EssenPhilip CramerMaubelstr. 90Brandenburg14776Germany
40La corne d’abondanceDaniel Tonini67, avenue de l’EuropeVersailles78000France
41La maison d’AsieAnnette Roulet1 rue Alsace-LorraineToulouse31000France
42Laughing Bacchus Wine CellarsYoshi Tannamuri1900 Oak St.VancouverV3F 2K1Canada
43Lazy K Kountry StoreJohn Steel12 Orchestra TerraceWalla Walla99362USA
44Lehmanns MarktstandRenate MessnerMagazinweg 7Frankfurt a.M.60528Germany
45Let’s Stop N ShopJaime Yorres87 Polk St. Suite 5San Francisco94117USA
46LILA-SupermercadoCarlos GonzálezCarrera 52 con Ave. Bolívar #65-98 Llano LargoBarquisimeto3508Venezuela
47LINO-DelicatesesFelipe IzquierdoAve. 5 de Mayo PorlamarI. de Margarita4980Venezuela
48Lonesome Pine RestaurantFran Wilson89 Chiaroscuro Rd.Portland97219USA
49Magazzini Alimentari RiunitiGiovanni RovelliVia Ludovico il Moro 22Bergamo24100Italy
50Maison DeweyCatherine DeweyRue Joseph-Bens 532BruxellesB-1180Belgium
51Mère PaillardeJean Fresnière43 rue St. LaurentMontréalH1J 1C3Canada
52Morgenstern GesundkostAlexander FeuerHeerstr. 22Leipzig04179Germany
53North/SouthSimon CrowtherSouth House 300 QueensbridgeLondonSW7 1RZUK
54Océano Atlántico Ltda.Yvonne MoncadaIng. Gustavo Moncada 8585 Piso 20-ABuenos Aires1010Argentina
55Old World DelicatessenRene Phillips2743 Bering St.Anchorage99508USA
56Ottilies KäseladenHenriette PfalzheimMehrheimerstr. 369Köln50739Germany
57Paris spécialitésMarie Bertrand265, boulevard CharonneParis75012France
58Pericles Comidas clásicasGuillermo FernándezCalle Dr. Jorge Cash 321México D.F.05033Mexico
59Piccolo und mehrGeorg PippsGeislweg 14Salzburg5020Austria
60Princesa Isabel VinhossIsabel de CastroEstrada da saúde n. 58Lisboa1756Portugal
61Que DelíciaBernardo BatistaRua da Panificadora, 12Rio de Janeiro02389-673Brazil
62Queen CozinhaLúcia CarvalhoAlameda dos Canàrios, 891São Paulo05487-020Brazil
63QUICK-StopHorst KlossTaucherstraße 10Cunewalde01307Germany
64Rancho grandeSergio GutiérrezAv. del Libertador 900Buenos Aires1010Argentina
65Rattlesnake Canyon GroceryPaula Wilson2817 Milton Dr.Albuquerque87110USA
66Reggiani CaseificiMaurizio MoroniStrada Provinciale 124Reggio Emilia42100Italy
67Ricardo AdocicadosJanete LimeiraAv. Copacabana, 267Rio de Janeiro02389-890Brazil
68Richter SupermarktMichael HolzGrenzacherweg 237Genève1203Switzerland
69Romero y tomilloAlejandra CaminoGran Vía, 1Madrid28001Spain
70Santé GourmetJonas BergulfsenErling Skakkes gate 78Stavern4110Norway
71Save-a-lot MarketsJose Pavarotti187 Suffolk Ln.Boise83720USA
72Seven Seas ImportsHari Kumar90 Wadhurst Rd.LondonOX15 4NBUK
73Simons bistroJytte PetersenVinbæltet 34København1734Denmark
74Spécialités du mondeDominique Perrier25, rue LauristonParis75016France
75Split Rail Beer & AleArt BraunschweigerP.O. Box 555Lander82520USA
76Suprêmes délicesPascale CartrainBoulevard Tirou, 255CharleroiB-6000Belgium
77The Big CheeseLiz Nixon89 Jefferson Way Suite 2Portland97201USA
78The Cracker BoxLiu Wong55 Grizzly Peak Rd.Butte59801USA
79Toms SpezialitätenKarin JosephsLuisenstr. 48Münster44087Germany
80Tortuga RestauranteMiguel Angel PaolinoAvda. Azteca 123México D.F.05033Mexico
81Tradição HipermercadosAnabela DominguesAv. Inês de Castro, 414São Paulo05634-030Brazil
82Trail’s Head Gourmet ProvisionersHelvetius Nagy722 DaVinci Blvd.Kirkland98034USA
83VaffeljernetPalle IbsenSmagsløget 45Århus8200Denmark
84Victuailles en stockMary Saveley2, rue du CommerceLyon69004France
85Vins et alcools ChevalierPaul Henriot59 rue de l’AbbayeReims51100France
86Die Wandernde KuhRita MüllerAdenauerallee 900Stuttgart70563Germany
87Wartian HerkkuPirkko KoskitaloTorikatu 38Oulu90110Finland
88Wellington ImportadoraPaula ParenteRua do Mercado, 12Resende08737-363Brazil
89White Clover MarketsKarl Jablonski305 – 14th Ave. S. Suite 3BSeattle98128USA
90Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91WolskiZbyszekul. Filtrowa 68Walla01-012Poland


AND Example

The following SQL statement selects all fields from “Customers” where country is “Germany” AND city is “Berlin”:

Example

SELECT * FROM Customers
WHERE Country=’Germany’ AND City=’Berlin’;Try it Yourself »


OR Example

The following SQL statement selects all fields from “Customers” where city is “Berlin” OR “München”:

Example

SELECT * FROM Customers
WHERE City=’Berlin’ OR City=’München’;Try it Yourself »

The following SQL statement selects all fields from “Customers” where country is “Germany” OR “Spain”:

Example

SELECT * FROM Customers
WHERE Country=’Germany’ OR Country=’Spain’;Try it Yourself »


NOT Example

The following SQL statement selects all fields from “Customers” where country is NOT “Germany”:

Example

SELECT * FROM Customers
WHERE NOT Country=’Germany’;Try it Yourself »


Combining AND, OR and NOT

You can also combine the AND, OR and NOT operators.

The following SQL statement selects all fields from “Customers” where country is “Germany” AND city must be “Berlin” OR “München” (use parenthesis to form complex expressions):

Example

SELECT * FROM Customers
WHERE Country=’Germany’ AND (City=’Berlin’ OR City=’München’);Try it Yourself »

The following SQL statement selects all fields from “Customers” where country is NOT “Germany” and NOT “USA”:

Example

SELECT * FROM Customers
WHERE NOT Country=’Germany’ AND NOT Country=’USA’;Try it Yourself »


Test Yourself With Exercises

Exercise:

Select all records where the City column has the value ‘Berlin’ and the PostalCode column has the value 12209.

The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

ORDER BY Syntax

SELECT column1, column2, …
FROM table_name
ORDER BY column1, column2, … ASC|DESC;


Demo Database

Below is a selection from the “Customers” table in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

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;Try it Yourself »



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;Try it Yourself »


ORDER BY Several Columns Example

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;Try it Yourself »


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;Try it Yourself »


Test Yourself With Exercises

Exercise:

Select all records from the Customers table, sort the result alphabetically by the column City.

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.

The first way specifies both the column names and the values to be inserted:INSERT INTO table_name (column1, column2, column3, …)
VALUES (value1, value2, value3, …);

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. 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 in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
89White Clover MarketsKarl Jablonski305 – 14th Ave. S. Suite 3BSeattle98128USA
90
Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91
WolskiZbyszekul. Filtrowa 68Walla01-012Poland


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’);Try it Yourself »

The selection from the “Customers” table will now look like this:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
89White Clover MarketsKarl Jablonski305 – 14th Ave. S. Suite 3BSeattle98128USA
90
Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91
WolskiZbyszekul. Filtrowa 68Walla01-012Poland
92CardinalTom B. ErichsenSkagen 21Stavanger4006Norway

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’);Try it Yourself »

The selection from the “Customers” table will now look like this:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
89White Clover MarketsKarl Jablonski305 – 14th Ave. S. Suite 3BSeattle98128USA
90
Wilman KalaMatti KarttunenKeskuskatu 45Helsinki21240Finland
91
WolskiZbyszekul. Filtrowa 68Walla01-012Poland
92Cardinalnullnull StavangernullNorway

Test Yourself With Exercises

Exercise:

Insert a new record in the Customers table.

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 in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1
Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4
Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden


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;

Leave a Comment

Your email address will not be published. Required fields are marked *