SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL...

67
4/7/2016 SQL Tutorial 1/3 « W3Schools Home Next Chapter » SQL Tutorial 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; Try it yourself » Click on the "Try it yourself" button to see how it works. Start learning SQL now! SQL Quiz Test Test your SQL skills at W3Schools! SQL is a standard language for accessing databases. Our SQL tutorial will teach you how to use SQL to access and manipulate data in: MySQL, SQL Server, Access, Oracle, Sybase, DB2, and other database systems. SQL

Transcript of SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL...

Page 1: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Tutorial

1/3

« W3Schools Home Next Chapter »

SQL Tutorial

Examples in Each ChapterWith our online SQL editor, you can edit the SQL statements, and click on a button toview the result.

Example

SELECT * FROM Customers;

Try it yourself »

Click on the "Try it yourself" button to see how it works.

Start learning SQL now!

SQL Quiz TestTest your SQL skills at W3Schools!

SQL is a standard language for accessing databases.

Our SQL tutorial will teach you how to use SQL to access andmanipulate data in: MySQL, SQL Server, Access, Oracle, Sybase,DB2, and other database systems.

SQL

Page 2: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Tutorial

2/3

W3Schools' Online CertificationThe perfect solution for professionals who need to balance work, family, and careerbuilding.

More than 10 000 certificates already issued!

Start SQL Quiz!

SQL Quick ReferenceAn SQL Quick Reference. Print it and put it in your pocket.

SQL Quick Reference

SQL Data TypesData types and ranges for Microsoft Access, MySQL and SQL Server.

SQL Data Types

W3Schools Exam

Get Your Certificate »

Page 3: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Tutorial

3/3

« W3Schools Home Next Chapter »

The HTML Certificate documents your knowledge of HTML.

The HTML5 Certificate documents your knowledge of advanced HTML5.

The CSS Certificate documents your knowledge of advanced CSS.

The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

The jQuery Certificate documents your knowledge of jQuery.

The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap framework.

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 4: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Introduction

1/2

« Previous Next Chapter »

Introduction to SQL

SQL is a standard language for accessing and manipulating databases.

What is SQL?SQL stands for Structured Query LanguageSQL lets you access and manipulate databasesSQL is an ANSI (American National Standards Institute) standard

What Can SQL do?SQL can execute queries against a databaseSQL can retrieve data from a databaseSQL can insert records in a databaseSQL can update records in a databaseSQL can delete records from a databaseSQL can create new databasesSQL can create new tables in a databaseSQL can create stored procedures in a databaseSQL can create views in a databaseSQL can set permissions on tables, procedures, and views

SQL is a Standard ‐ BUT....Although SQL is an ANSI (American National Standards Institute) standard, there aredifferent versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the major

Page 5: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Introduction

2/2

« Previous Next Chapter »

commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

Note: Most of the SQL database programs also have their ownproprietary extensions in addition to the SQL standard!

Using SQL in Your Web SiteTo 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 ASPTo use SQL to get the data you wantTo use HTML / CSS

RDBMSRDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS SQLServer, 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.

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 6: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Syntax

1/3

« Previous Next Chapter »

SQL Syntax

Database TablesA 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 MSAccess and MS SQL Server).

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

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

Page 7: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Syntax

2/3

SQL StatementsMost 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 is 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 systemsthat 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 CommandsSELECT ­ extracts data from a databaseUPDATE ­ updates data in a databaseDELETE ­ deletes data from a database

Page 8: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Syntax

3/3

« Previous Next Chapter »

INSERT 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

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 9: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT Statement

1/3

« Previous Next Chapter »

SQL SELECT Statement

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

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

The result is stored in a result table, called the result­set.

SQL SELECT Syntax

SELECT column_name,column_nameFROM table_name;

and

SELECT * FROM table_name;

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

Page 10: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT Statement

2/3

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

SELECT Column ExampleThe following SQL statement selects the "CustomerName" and "City" columns from the"Customers" table:

Example

SELECT CustomerName,City FROM Customers;

Try it yourself »

SELECT * ExampleThe following SQL statement selects all the columns from the "Customers" table:

Example

SELECT * FROM Customers;

Try it yourself »

Page 11: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT Statement

3/3

« Previous Next Chapter »

Navigation in a Result‐setMost database software systems allow navigation in the result­set with programmingfunctions, like: Move­To­First­Record, Get­Record­Content, Move­To­Next­Record, etc.

Programming functions like these are not a part of this tutorial. To learn about accessingdata with function calls, please visit our ASP tutorial or our PHP tutorial.

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 12: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT DISTINCT Statement

1/2

« Previous Next Chapter »

SQL SELECT DISTINCT Statement

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

The SQL SELECT DISTINCT StatementIn a table, a column may contain many duplicate values; and sometimes you only wantto list the different (distinct) values.

The DISTINCT keyword can be used to return only distinct (different) values.

SQL SELECT DISTINCT Syntax

SELECT DISTINCT column_name,column_nameFROM table_name;

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

Page 13: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT DISTINCT Statement

2/2

« Previous Next Chapter »

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

SELECT DISTINCT ExampleThe following SQL statement selects only the distinct values from the "City" columnsfrom the "Customers" table:

Example

SELECT DISTINCT City FROM Customers;

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 14: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL WHERE Clause

1/3

« Previous Next Chapter »

SQL WHERE Clause

The WHERE clause is used to filter records.

The SQL WHERE Clause The WHERE clause is used to extract only those records that fulfill a specified criterion.

SQL WHERE Syntax

SELECT column_name,column_nameFROM table_nameWHERE column_name operator value;

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

Page 15: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL WHERE Clause

2/3

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

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

Example

SELECT * FROM CustomersWHERE Country='Mexico';

Try it yourself »

Text Fields vs. Numeric FieldsSQL requires single quotes around text values (most database systems will also allowdouble quotes).

However, numeric fields should not be enclosed in quotes:

Example

SELECT * FROM CustomersWHERE CustomerID=1;

Try it yourself »

Page 16: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL WHERE Clause

3/3

« Previous Next Chapter »

Operators in The WHERE ClauseThe following operators can be used in the WHERE clause:

Operator Description

= Equal

<> Not equal. Note: In some versions of SQL this operator maybe written as !=

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN To specify multiple possible values for a column

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 17: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL AND & OR Operators

1/3

« Previous Next Chapter »

SQL AND & OR Operators

The AND & OR operators are used to filter records based on more than onecondition.

The SQL AND & OR OperatorsThe AND operator displays a record if both the first condition AND the second conditionare true.

The OR operator displays a record if either the first condition OR the second condition istrue.

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

Page 18: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL AND & OR Operators

2/3

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

AND Operator ExampleThe following SQL statement selects all customers from the country "Germany" AND thecity "Berlin", in the "Customers" table:

Example

SELECT * FROM CustomersWHERE Country='Germany'AND City='Berlin';

Try it yourself »

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

Example

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

Try it yourself »

Page 19: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL AND & OR Operators

3/3

« Previous Next Chapter »

Combining AND & ORYou can also combine AND and OR (use parenthesis to form complex expressions).

The following SQL statement selects all customers from the country "Germany" AND thecity must be equal to "Berlin" OR "München", in the "Customers" table:

Example

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

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 20: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL ORDER BY Keyword

1/3

« Previous Next Chapter »

SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result­set.

The SQL ORDER BY KeywordThe ORDER BY keyword is used to sort the result­set by one or more columns.

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

SQL ORDER BY Syntax

SELECT column_name, column_nameFROM table_nameORDER BY column_name ASC|DESC, column_name ASC|DESC;

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

Page 21: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL ORDER BY Keyword

2/3

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

ORDER BY ExampleThe following SQL statement selects all customers from the "Customers" table, sortedby the "Country" column:

Example

SELECT * FROM CustomersORDER BY Country;

Try it yourself »

ORDER BY DESC ExampleThe following SQL statement selects all customers from the "Customers" table, sortedDESCENDING by the "Country" column:

Example

SELECT * FROM CustomersORDER BY Country DESC;

Try it yourself »

Page 22: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL ORDER BY Keyword

3/3

« Previous Next Chapter »

ORDER BY Several Columns ExampleThe following SQL statement selects all customers from the "Customers" table, sortedby the "Country" and the "CustomerName" column:

Example

SELECT * FROM CustomersORDER BY Country, CustomerName;

Try it yourself »

ORDER BY Several Columns Example 2The following SQL statement selects all customers from the "Customers" table, sortedascending by the "Country" and descending by the "CustomerName" column:

Example

SELECT * FROM CustomersORDER BY Country ASC, CustomerName DESC;

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 23: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INSERT INTO Statement

1/4

« Previous Next Chapter »

SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table.

The SQL INSERT INTO StatementThe INSERT INTO statement is used to insert new records in a table.

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, onlytheir values:

INSERT INTO table_nameVALUES (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,...);

Demo DatabaseIn this tutorial we will use the well­known Northwind sample database.

Below is a selection from the "Customers" table:

Page 24: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INSERT INTO Statement

2/4

CustomerID CustomerName ContactName Address City PostalCode

87 Wartian Herkku PirkkoKoskitalo

Torikatu 38 Oulu 90110

88 WellingtonImportadora

Paula Parente Rua doMercado,12

Resende 08737­363

89 White CloverMarkets

Karl Jablonski 305 ­ 14thAve. S.Suite 3B

Seattle 98128

90 Wilman Kala MattiKarttunen

Keskuskatu45

Helsinki 21240

91 Wolski Zbyszek ul. Filtrowa68

Walla 01­012

INSERT INTO ExampleAssume we wish to insert a new row in the "Customers" table.

We can use the following SQL statement:

Example

INSERT INTO Customers (CustomerName, ContactName, Address, City,PostalCode, Country)VALUES ('Cardinal','Tom B. Erichsen','Skagen21','Stavanger','4006','Norway');

Try it yourself »

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

CustomerID CustomerName ContactName Address City PostalCode

Page 25: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INSERT INTO Statement

3/4

87 Wartian Herkku PirkkoKoskitalo

Torikatu 38 Oulu 90110

88 WellingtonImportadora

Paula Parente Rua doMercado,12

Resende 08737­363

89 White CloverMarkets

Karl Jablonski 305 ­ 14thAve. S.Suite 3B

Seattle 98128

90 Wilman Kala MattiKarttunen

Keskuskatu45

Helsinki 21240

91 Wolski Zbyszek ul. Filtrowa68

Walla 01­012

92 Cardinal Tom B.Erichsen

Skagen 21 Stavanger 4006

Did you notice that we did not insert any number into theCustomerID field?The CustomerID column is automatically updated with a unique numberfor each record in the table.

Insert Data Only in Specified ColumnsIt 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 ofcourse also be updated automatically):

Example

INSERT INTO Customers (CustomerName, City, Country)VALUES ('Cardinal', 'Stavanger', 'Norway');

Try it yourself »

Page 26: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INSERT INTO Statement

4/4

« Previous Next Chapter »

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

CustomerID CustomerName ContactName Address City PostalCode

87 Wartian Herkku PirkkoKoskitalo

Torikatu 38 Oulu 90110

88 WellingtonImportadora

Paula Parente Rua doMercado,12

Resende 08737­363

89 White CloverMarkets

Karl Jablonski 305 ­ 14thAve. S.Suite 3B

Seattle 98128

90 Wilman Kala MattiKarttunen

Keskuskatu45

Helsinki 21240

91 Wolski Zbyszek ul. Filtrowa68

Walla 01­012

92 Cardinal null null Stavanger null

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 27: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL UPDATE Statement

1/3

« Previous Next Chapter »

SQL UPDATE Statement

The UPDATE statement is used to update records in a table.

The SQL UPDATE StatementThe UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax

UPDATE table_nameSET column1=value1,column2=value2,...WHERE some_column=some_value;

Notice the WHERE clause in the SQL UPDATE statement!The WHERE clause specifies which record or records that should beupdated. If you omit the WHERE clause, all records will be updated!

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados y

Ana Trujillo Avda. de laConstitución

MéxicoD.F.

05021

Page 28: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL UPDATE Statement

2/3

helados 2222

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

SQL UPDATE ExampleAssume we wish to update the customer "Alfreds Futterkiste" with a new contact personand city.

We use the following SQL statement:

Example

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

Try it yourself »

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

CustomerID CustomerName ContactName Address City PostalCode

1 AlfredsFutterkiste

Alfred Schmidt Obere Str. 57 Hamburg 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

Page 29: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL UPDATE Statement

3/3

« Previous Next Chapter »

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

Update Warning!Be careful when updating records. If we had omitted the WHERE clause, in the exampleabove, like this:

UPDATE CustomersSET ContactName='Alfred Schmidt', City='Hamburg';

The "Customers" table would have looked like this:

CustomerID CustomerName ContactName Address City PostalCode

1 AlfredsFutterkiste

Alfred Schmidt Obere Str. 57 Hamburg 12209

2 Ana TrujilloEmparedados yhelados

Alfred Schmidt Avda. de laConstitución2222

Hamburg 05021

3 Antonio MorenoTaquería

Alfred Schmidt Mataderos2312

Hamburg 05023

4 Around the Horn Alfred Schmidt 120 HanoverSq.

Hamburg WA1 1DP

5 Berglundssnabbköp

Alfred Schmidt Berguvsvägen8

Hamburg S­958 22

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 30: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL DELETE Statement

1/3

« Previous Next Chapter »

SQL DELETE Statement

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

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

SQL DELETE Syntax

DELETE FROM table_nameWHERE some_column=some_value;

Notice the WHERE clause in the SQL DELETE statement!The WHERE clause specifies which record or records that should bedeleted. If you omit the WHERE clause, all records will be deleted!

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

Page 31: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL DELETE Statement

2/3

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

SQL DELETE ExampleAssume we wish to delete the customer "Alfreds Futterkiste" from the "Customers"table.

We use the following SQL statement:

Example

DELETE FROM CustomersWHERE CustomerName='Alfreds Futterkiste' AND ContactName='MariaAnders';

Try it yourself »

The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

Page 32: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL DELETE Statement

3/3

« Previous Next Chapter »

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

Delete All DataIt is possible to delete all rows in a table without deleting the table. This means that thetable structure, attributes, and indexes will be intact:

DELETE FROM table_name;

or

DELETE * FROM table_name;

Note: Be very careful when deleting records. You cannot undo this statement!

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 33: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

1/7

« Previous Next Chapter »

SQL Injection

An SQL Injection can destroy your database.

SQL in Web PagesIn the previous chapters, you have learned to retrieve (and update) database data, usingSQL.

When SQL is used to display data on a web page, it is common to let web users inputtheir own search values.

Since SQL statements are text only, it is easy, with a little piece of computer code, todynamically change SQL statements to provide the user with selected data:

Server Code

txtUserId = getRequestString("UserId");txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

The example above, creates a select statement by adding a variable (txtUserId) to aselect string. The variable is fetched from the user input (Request) to the page.

The rest of this chapter describes the potential dangers of using user input in SQLstatements.

SQL InjectionSQL injection is a technique where malicious users can inject SQL commands into an SQL

Page 34: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

2/7

statement, via web page input.

Injected SQL commands can alter SQL statement and compromise the security of a webapplication.

SQL Injection Based on 1=1 is Always TrueLook at the example above, one more time.

Let's say that the original purpose of the code was to create an SQL statement to selecta user with a given user id.

If there is nothing to prevent a user from entering "wrong" input, the user can entersome "smart" input like this:

UserId: 105 or 1=1

Server Result

SELECT * FROM Users WHERE UserId = 105 or 1=1

The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 isalways true.

Does the example above seem dangerous? What if the Users table contains names andpasswords?

The SQL statement above is much the same as this:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1

A smart hacker might get access to all the user names and passwords in a database bysimply inserting 105 or 1=1 into the input box.

Page 35: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

3/7

SQL Injection Based on ""="" is Always TrueHere is a common construction, used to verify user login to a web site:

User Name:

Password:

Server Code

uName = getRequestString("UserName");uPass = getRequestString("UserPass");

sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='"+ uPass + "'"

A smart hacker might get access to user names and passwords in a database by simplyinserting " or ""=" into the user name or password text box.

The code at the server will create a valid SQL statement like this:

Result

SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

The result SQL is valid. It will return all rows from the table Users, since WHERE ""="" isalways true.

SQL Injection Based on Batched SQL Statements Most databases support batched SQL statement, separated by semicolon.

Page 36: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

4/7

Example

SELECT * FROM Users; DROP TABLE Suppliers

The SQL above will return all rows in the Users table, and then delete the table calledSuppliers.

If we had the following server code:

Server Code

txtUserId = getRequestString("UserId");txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

And the following input:

User id:105; DROP TABLE Suppliers

The code at the server would create a valid SQL statement like this:

Result

SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers

Parameters for ProtectionSome web developers use a "blacklist" of words or characters to search for in SQL input,to prevent SQL injection attacks.

This is not a very good idea. Many of these words (like delete or drop) and characters(like semicolons and quotation marks), are used in common language, and should beallowed in many types of input.

Page 37: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

5/7

(In fact it should be perfectly legal to input an SQL statement in a database field.)

The only proven way to protect a web site from SQL injection attacks, is to use SQLparameters.

SQL parameters are values that are added to an SQL query at execution time, in acontrolled manner.

ASP.NET Razor Example

txtUserId = getRequestString("UserId");txtSQL = "SELECT * FROM Users WHERE UserId = @0";db.Execute(txtSQL,txtUserId);

Note that parameters are represented in the SQL statement by a @ marker.

The SQL engine checks each parameter to ensure that it is correct for its column and aretreated literally, and not as part of the SQL to be executed.

Another Example

txtNam = getRequestString("CustomerName");txtAdd = getRequestString("Address");txtCit = getRequestString("City");txtSQL = "INSERT INTO Customers (CustomerName,Address,City)Values(@0,@1,@2)";db.Execute(txtSQL,txtNam,txtAdd,txtCit);

You have just learned to avoid SQL injection. One of the top websitevulnerabilities.

ExamplesThe following examples shows how to build parameterized queries in some commonweb languages.

Page 38: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

6/7

« Previous Next Chapter »

SELECT STATEMENT IN ASP.NET:

txtUserId = getRequestString("UserId");sql = "SELECT * FROM Customers WHERE CustomerId = @0";command = new SqlCommand(sql);command.Parameters.AddWithValue("@0",txtUserID);command.ExecuteReader();

INSERT INTO STATEMENT IN ASP.NET:

txtNam = getRequestString("CustomerName");txtAdd = getRequestString("Address");txtCit = getRequestString("City");txtSQL = "INSERT INTO Customers (CustomerName,Address,City)Values(@0,@1,@2)";command = new SqlCommand(txtSQL);command.Parameters.AddWithValue("@0",txtNam);command.Parameters.AddWithValue("@1",txtAdd);command.Parameters.AddWithValue("@2",txtCit);command.ExecuteNonQuery();

INSERT INTO STATEMENT IN PHP:

$stmt = $dbh‐>prepare("INSERT INTO Customers(CustomerName,Address,City) VALUES (:nam, :add, :cit)");$stmt‐>bindParam(':nam', $txtNam);$stmt‐>bindParam(':add', $txtAdd);$stmt‐>bindParam(':cit', $txtCit);$stmt‐>execute();

Page 39: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Injection

7/7

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 40: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT TOP, LIMIT, ROWNUM

1/3

« Previous Next Chapter »

SQL SELECT TOP Clause

The SQL SELECT TOP ClauseThe SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause can be very useful on large tables with thousands of records.Returning a large number of records can impact on performance.

Note: Not all database systems support the 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 OracleMySQL Syntax

SELECT column_name(s)FROM table_nameLIMIT number;

Example

SELECT *FROM PersonsLIMIT 5;

Page 41: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT TOP, LIMIT, ROWNUM

2/3

Oracle Syntax

SELECT column_name(s)FROM table_nameWHERE ROWNUM <= number;

Example

SELECT *FROM PersonsWHERE ROWNUM <=5;

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

Page 42: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL SELECT TOP, LIMIT, ROWNUM

3/3

« Previous Next Chapter »

SQL SELECT TOP ExampleThe following SQL statement selects the two first records from the "Customers" table:

Example

SELECT TOP 2 * FROM Customers;

Try it yourself »

SQL SELECT TOP PERCENT ExampleThe following SQL statement selects the first 50% of the records from the "Customers"table:

Example

SELECT TOP 50 PERCENT * FROM Customers;

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 43: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL LIKE Operator

1/3

« Previous Next Chapter »

SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified patternin a column.

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

SQL LIKE Syntax

SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern;

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio Moreno Antonio Mataderos México 05023

Page 44: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL LIKE Operator

2/3

Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

SQL LIKE Operator ExamplesThe following SQL statement selects all customers with a City starting with the letter "s":

Example

SELECT * FROM CustomersWHERE City LIKE 's%';

Try it yourself »

Tip: The "%" sign is used to define wildcards (missing letters) both before and after thepattern. You will learn more about wildcards in the next chapter.

The following SQL statement selects all customers with a City ending with the letter "s":

Example

SELECT * FROM CustomersWHERE City LIKE '%s';

Try it yourself »

The following SQL statement selects all customers with a Country containing the pattern"land":

Page 45: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL LIKE Operator

3/3

« Previous Next Chapter »

Example

SELECT * FROM CustomersWHERE Country LIKE '%land%';

Try it yourself »

Using the NOT keyword allows you to select records that do NOT match the pattern.

The following SQL statement selects all customers with Country NOT containing thepattern "land":

Example

SELECT * FROM CustomersWHERE Country NOT LIKE '%land%';

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 46: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Wildcards

1/5

« Previous Next Chapter »

SQL Wildcards

A wildcard character can be used to substitute for any other character(s) in astring.

SQL Wildcard CharactersIn 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 DatabaseIn 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

Page 47: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Wildcards

2/5

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

Using the SQL % WildcardThe following SQL statement selects all customers with a City starting with "ber":

Example

SELECT * FROM CustomersWHERE City LIKE 'ber%';

Try it yourself »

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

Example

SELECT * FROM CustomersWHERE City LIKE '%es%';

Page 48: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Wildcards

3/5

Try it yourself »

Using the SQL _ WildcardThe following SQL statement selects all customers with a City starting with anycharacter, followed by "erlin":

Example

SELECT * FROM CustomersWHERE City LIKE '_erlin';

Try it yourself »

The following SQL statement selects all customers with a City starting with "L", followedby any character, followed by "n", followed by any character, followed by "on":

Example

SELECT * FROM CustomersWHERE City LIKE 'L_n_on';

Try it yourself »

Using the SQL [charlist] WildcardThe following SQL statement selects all customers with a City starting with "b", "s", or"p":

Example

Page 49: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Wildcards

4/5

« Previous Next Chapter »

SELECT * FROM CustomersWHERE City LIKE '[bsp]%';

Try it yourself »

The following SQL statement selects all customers with a City starting with "a", "b", or"c":

Example

SELECT * FROM CustomersWHERE City LIKE '[a‐c]%';

Try it yourself »

The following SQL statement selects all customers with a City NOT starting with "b", "s",or "p":

Example

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

or

SELECT * FROM CustomersWHERE City NOT LIKE '[bsp]%';

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 50: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Wildcards

5/5

Page 51: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL IN Operator

1/2

« Previous Next Chapter »

SQL IN Operator

The IN OperatorThe IN operator allows you to specify multiple values in a WHERE clause.

SQL IN Syntax

SELECT column_name(s)FROM table_nameWHERE column_name IN (value1,value2,...);

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

1 AlfredsFutterkiste

Maria Anders Obere Str. 57 Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120 HanoverSq.

London WA1 1DP

Page 52: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL IN Operator

2/2

« Previous Next Chapter »

5 Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8

Luleå S­958 22

IN Operator ExampleThe following SQL statement selects all customers with a City of "Paris" or "London":

Example

SELECT * FROM CustomersWHERE City IN ('Paris','London');

Try it yourself »

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 53: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL BETWEEN Operator

1/5

« Previous Next Chapter »

SQL BETWEEN Operator

The BETWEEN operator is used to select values within a range.

The SQL BETWEEN OperatorThe BETWEEN operator selects values within a range. The values can be numbers, text,or dates.

SQL BETWEEN Syntax

SELECT column_name(s)FROM table_nameWHERE column_name BETWEEN value1 AND value2;

Demo DatabaseIn this tutorial we will use the well­known Northwind sample database.

Below is a selection from the "Products" table:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10boxes x20 bags

18

2 Chang 1 1 24 ­ 12ozbottles

19

Page 54: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL BETWEEN Operator

2/5

3 Aniseed Syrup 1 2 12 ­ 550mlbottles

10

4 Chef Anton's CajunSeasoning

1 2 48 ­ 6oz jars

22

5 Chef Anton'sGumbo Mix

1 2 36boxes

21.35

BETWEEN Operator ExampleThe following SQL statement selects all products with a price BETWEEN 10 and 20:

Example

SELECT * FROM ProductsWHERE Price BETWEEN 10 AND 20;

Try it yourself »

NOT BETWEEN Operator ExampleTo display the products outside the range of the previous example, use NOT BETWEEN:

Example

SELECT * FROM ProductsWHERE Price NOT BETWEEN 10 AND 20;

Try it yourself »

Page 55: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL BETWEEN Operator

3/5

BETWEEN Operator with IN ExampleThe following SQL statement selects all products with a price BETWEEN 10 and 20, butproducts with a CategoryID of 1,2, or 3 should not be displayed:

Example

SELECT * FROM ProductsWHERE (Price BETWEEN 10 AND 20)AND NOT CategoryID IN (1,2,3);

Try it yourself »

BETWEEN Operator with Text Value ExampleThe following SQL statement selects all products with a ProductName beginning with anyof the letter BETWEEN 'C' and 'M':

Example

SELECT * FROM ProductsWHERE ProductName BETWEEN 'C' AND 'M';

Try it yourself »

NOT BETWEEN Operator with Text Value ExampleThe following SQL statement selects all products with a ProductName beginning with anyof the letter NOT BETWEEN 'C' and 'M':

Page 56: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL BETWEEN Operator

4/5

Example

SELECT * FROM ProductsWHERE ProductName NOT BETWEEN 'C' AND 'M';

Try it yourself »

Sample TableBelow is a selection from the "Orders" table:

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

BETWEEN Operator with Date Value ExampleThe following SQL statement selects all orders with an OrderDate BETWEEN '04­July­1996' and '09­July­1996':

Example

SELECT * FROM OrdersWHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;

Page 57: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL BETWEEN Operator

5/5

« Previous Next Chapter »

Try it yourself »

Notice that the BETWEEN operator can produce different result indifferent databases!In some databases, BETWEEN selects fields that are between andexcluding the test values.In other databases, BETWEEN selects fields that are between andincluding the test values.And in other databases, BETWEEN selects fields between the testvalues, including the first test value and excluding the last test value.

Therefore: Check how your database treats the BETWEEN operator!

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 58: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Aliases

1/4

« Previous Next Chapter »

SQL Aliases

SQL aliases are used to temporarily rename a table or a column heading.

SQL AliasesSQL aliases are used to give a database table, or a column in a table, a temporary name.

Basically aliases are created to make column names more readable.

SQL Alias Syntax for Columns

SELECT column_name AS alias_nameFROM table_name;

SQL Alias Syntax for Tables

SELECT column_name(s)FROM table_name AS alias_name;

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

2 Ana Trujillo Ana Trujillo Avda. de la México 05021

Page 59: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Aliases

2/4

Emparedados yhelados

Constitución2222

D.F.

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

4 Around the Horn Thomas Hardy 120Hanover Sq.

London WA1 1DP

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10354 58 8 1996­11­14 3

10355 4 6 1996­11­15 1

10356 86 6 1996­11­18 2

Alias Example for Table ColumnsThe following SQL statement specifies two aliases, one for the CustomerName columnand one for the ContactName column. Tip: It requires double quotation marks or squarebrackets if the column name contains spaces:

Example

SELECT CustomerName AS Customer, ContactName AS [Contact Person]FROM Customers;

Try it yourself »

In the following SQL statement we combine four columns (Address, City, PostalCode,and Country) and create an alias named "Address":

Page 60: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Aliases

3/4

Example

SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+CountryAS AddressFROM Customers;

Try it yourself »

Note: To get the SQL statement above to work in MySQL use the following:

SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,',',Country) AS AddressFROM Customers;

Alias Example for TablesThe following SQL statement selects all the orders from the customer withCustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, andgive them the table aliases of "c" and "o" respectively (Here we have used aliases tomake the SQL shorter):

Example

SELECT o.OrderID, o.OrderDate, c.CustomerNameFROM Customers AS c, Orders AS oWHERE c.CustomerName="Around the Horn" ANDc.CustomerID=o.CustomerID;

Try it yourself »

The same SQL statement without aliases:

Page 61: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Aliases

4/4

« Previous Next Chapter »

Example

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerNameFROM Customers, OrdersWHERE Customers.CustomerName="Around the Horn" ANDCustomers.CustomerID=Orders.CustomerID;

Try it yourself »

Aliases can be useful when:

There are more than one table involved in a queryFunctions are used in the queryColumn names are big or not very readableTwo or more columns are combined together

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 62: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Joins

1/3

« Previous Next Chapter »

SQL Joins

SQL joins are used to combine rows from two or more tables.

SQL JOINAn SQL JOIN clause is used to combine rows from two or more tables, based on acommon field between them.

The most common type of join is: SQL INNER JOIN (simple join). An SQL INNERJOIN returns all rows from multiple tables where the join condition is met.

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, have a look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados yhelados

Ana Trujillo Mexico

3 Antonio Moreno Taquería AntonioMoreno

Mexico

Page 63: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Joins

2/3

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" inthe "Customers" table. The relationship between the two tables above is the"CustomerID" column.

Then, if we run the following SQL statement (that contains an INNER JOIN):

Example

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDateFROM OrdersINNER JOIN CustomersON Orders.CustomerID=Customers.CustomerID;

Try it yourself »

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 SQL JOINsBefore we continue with examples, we will list the types of the different SQL JOINs youcan use:

INNER JOIN: Returns all rows when there is at least one match in BOTH tablesLEFT JOIN: Return all rows from the left table, and the matched rows from theright table

Page 64: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL Joins

3/3

« Previous Next Chapter »

RIGHT JOIN: Return all rows from the right table, and the matched rows from theleft tableFULL JOIN: Return all rows when there is a match in ONE of the tables

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.

Page 65: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INNER JOIN Keyword

1/3

« Previous Next Chapter »

SQL INNER JOIN Keyword

SQL INNER JOIN KeywordThe INNER JOIN keyword selects all rows from both tables as long as there is a matchbetween the columns in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s)FROM table1INNER JOIN table2ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)FROM table1JOIN table2ON table1.column_name=table2.column_name;

PS! INNER JOIN is the same as JOIN.

Page 66: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INNER JOIN Keyword

2/3

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

1 AlfredsFutterkiste

Maria Anders Obere Str.57

Berlin 12209

2 Ana TrujilloEmparedados yhelados

Ana Trujillo Avda. de laConstitución2222

MéxicoD.F.

05021

3 Antonio MorenoTaquería

AntonioMoreno

Mataderos2312

MéxicoD.F.

05023

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 INNER JOIN ExampleThe following SQL statement will return all customers with orders:

Example

SELECT Customers.CustomerName, Orders.OrderIDFROM CustomersINNER JOIN Orders

Page 67: SQL Tutorial - Welcome - College of Engineering, …ngf4/CS Books/W3Schools SQL.pdf · 4/7/2016 SQL Tutorial 1/3 ... SQL Quick Reference ... Most database software systems allow navigation

4/7/2016 SQL INNER JOIN Keyword

3/3

« Previous Next Chapter »

ON Customers.CustomerID=Orders.CustomerIDORDER BY Customers.CustomerName;

Try it yourself »

Note: The INNER JOIN keyword selects all rows from both tables as long as there is amatch between the columns. If there are rows in the "Customers" table that do nothave matches in "Orders", these customers will NOT be listed.

Copyright 1999­2015 by Refsnes Data. All Rights Reserved.