HTML Quotation and Citation Elements


In this chapter we will go through the <blockquote>,<q>, <abbr>, <address>, <cite>, and <bdo> HTML elements.


Example

Here is a quote from WWF's website:

For 60 years, WWF has worked to help people and nature thrive. As the world's leading conservation organization, WWF works in nearly 100 countries. At every level, we collaborate with people around the world to develop and deliver innovative solutions that protect communities, wildlife, and the places in which they live.

HTML <blockquote> for Quotations

The HTML <blockquote> element defines a section that is quoted from another source.

Browsers usually indent <blockquote> elements.

Example

<p>Here is a quote from WWF's website:</p>
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 60 years, WWF has worked to help people and nature thrive. As the world's leading conservation organization, WWF works in nearly 100 countries. At every level, we collaborate with people around the world to develop and deliver innovative solutions that protect communities, wildlife, and the places in which they live.
</blockquote>

HTML <q> for Short Quotations

The HTML <q> tag defines a short quotation.

Browsers normally insert quotation marks around the quotation.

Example

<p>WWF's goal is to: <q>Build a future where people live in harmony with nature.</q></p>


HTML <abbr> for Abbreviations

The HTML <abbr> tag defines an abbreviation or an acronym, like "HTML", "CSS", "Mr.", "Dr.", "ASAP", "ATM".

Marking abbreviations can give useful information to browsers, translation systems and search-engines.

Tip: Use the global title attribute to show the description for the abbreviation/acronym when you mouse over the element. 

Example

<p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>

HTML <address> for Contact Information

The HTML <address> tag defines the contact information for the author/owner of a document or an article.

The contact information can be an email address, URL, physical address, phone number, social media handle, etc.

The text in the <address> element usually renders in italic, and browsers will always add a line break before and after the <address> element.

Example

<address>
Written by John Doe.<br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</address>

HTML <cite> for Work Title

The HTML <cite> tag defines the title of a creative work (e.g. a book, a poem, a song, a movie, a painting, a sculpture, etc.).

Note: A person's name is not the title of a work.

The text in the <cite> element usually renders in italic.

Example

<p><cite>The Scream</cite> by Edvard Munch. Painted in 1893.</p>

HTML <bdo> for Bi-Directional Override

BDO stands for Bi-Directional Override.

The HTML <bdo> tag is used to override the current text direction:

Example

<bdo dir="rtl">This text will be written from right to left</bdo>

MySQL is a widely used relational database management system (RDBMS).

MySQL is free and open-source.

MySQL is ideal for both small and large applications.


Examples in Each Chapter

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

Example

SELECT * FROM Customers;

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


MySQL HOME

Introduction to MySQL

 

MySQL is a very popular open-source relational database management system (RDBMS).


What is MySQL?

  • MySQL is a relational database management system
  • MySQL is open-source
  • MySQL is free
  • MySQL is ideal for both small and large applications
  • MySQL is very fast, reliable, scalable, and easy to use
  • MySQL is cross-platform
  • MySQL is compliant with the ANSI SQL standard
  • MySQL was first released in 1995
  • MySQL is developed, distributed, and supported by Oracle Corporation
  • MySQL is named after co-founder Monty Widenius's daughter: My

Who Uses MySQL?

  • Huge websites like Facebook, Twitter, Airbnb, Booking.com, Uber, GitHub, YouTube, etc.
  • Content Management Systems like WordPress, Drupal, Joomla!, Contao, etc.
  • A very large number of web developers around the world

Show Data On Your Web Site

To build a web site that shows data from a database, you will need:

  • An RDBMS database program (like MySQL)
  • A server-side scripting language, like PHP
  • To use SQL to get the data you want
  • To use HTML / CSS to style the page

 

 
MySQL Intro

What is RDBMS?

RDBMS stands for Relational Database Management System.

RDBMS is a program used to maintain a relational database.

RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server, Oracle, and Microsoft Access.

RDBMS uses SQL queries to access the data in the database.


What is a Database Table?

A table is a collection of related data entries, and it consists of columns and rows.

A column holds specific information about every record in the table.

A record (or row) is each individual entry that exists in a table.

Look at a selection from the Northwind "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 columns in the "Customers" table above are: CustomerID, CustomerName, ContactName, Address, City, PostalCode and Country. The table has 5 records (rows).



What is a Relational Database?

A relational database defines database relationships in the form of tables. The tables are related to each other - based on data common to each.

Look at the following three tables "Customers", "Orders", and "Shippers" from the Northwind database:

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 relationship between the "Customers" table and the "Orders" table is the CustomerID column:

Orders Table

OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10278

5

8

1996-08-12

2

10280

5

2

1996-08-14

1

10308

2

7

1996-09-18

3

10355

4

6

1996-11-15

1

10365

3

3

1996-11-27

2

MySQL RDBMS

MySQL SQL


What is SQL?

SQL is the standard language for dealing with Relational Databases.

SQL is used to insert, search, update, and delete database records.


How to Use SQL

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

Example

SELECT * FROM Customers;

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

In this tutorial we will use the well-known Northwind sample database.

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

CustomerID CustomerName ContactName Address City PostalCode Country
1

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4

Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

SELECT Columns Example

The following SQL statement selects the "CustomerName", "City", and "Country" columns from the "Customers" table:

Example

SELECT CustomerName, City, Country FROM Customers;

SELECT * Example

The following SQL statement selects ALL the columns from the "Customers" table:

Example

SELECT * FROM Customers;


The MySQL 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;

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;

Now, let us use the SELECT DISTINCT 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;

The following SQL statement counts and returns the number of different (distinct) countries in the "Customers" table:

Example

SELECT COUNT(DISTINCT Country) FROM Customers;

Test Yourself With Exercises

Exercise:

Insert the missing statement to get all the columns from the Customers table.

 * FROM Customers;

 

 

 
MySQL SELECT
 

The MySQL WHERE Clause

The WHERE clause is used to filter records.

It 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 statements, it is also used in UPDATE, DELETE, etc.!


Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
1

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4

Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden


WHERE Clause Example

The following SQL statement selects all the customers from "Mexico":

Example

SELECT * FROM Customers
WHERE Country = 'Mexico';

Text Fields vs. Numeric Fields

SQL requires single quotes around text values (most database systems will also allow double quotes).

However, numeric fields should not be enclosed in quotes:

Example

SELECT * FROM Customers
WHERE CustomerID = 1;

Operators in The WHERE Clause

The following operators can be used in the WHERE clause:

Operator Description Example
= Equal  
> Greater than  
< Less than  
>= Greater than or equal  
<= Less than or equal  
<> Not equal. Note: In some versions of SQL this operator may be written as !=  
BETWEEN Between a certain range  
LIKE Search for a pattern  
IN To specify multiple possible values for a column  

Test Yourself With Exercises

Exercise:

Select all records where the City column has the value "Berlin".

SELECT * FROM Customers
  = ;

 

 

 
MySQL WHERE
 

The MySQL 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:

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con Ave. Carlos Soublette #8-35 San Cristóbal 5022 Venezuela
36 Hungry Coyote Import Store Yoshi Latimer City Center Plaza 516 Main St. Elgin 97827 USA
37 Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road Cork   Ireland
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
46 LILA-Supermercado Carlos González Carrera 52 con Ave. Bolívar #65-98 Llano Largo Barquisimeto 3508 Venezuela
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
53 North/South Simon Crowther South House 300 Queensbridge London SW7 1RZ UK
54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Piso 20-A Buenos Aires 1010 Argentina
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369 Köln 50739 Germany
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
75 Split Rail Beer & Ale Art Braunschweiger P.O. Box 555 Lander 82520 USA
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 05033 Mexico
81 Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland


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

OR Example

The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "Stuttgart":

Example

SELECT * FROM Customers
WHERE City = 'Berlin' OR City = 'Stuttgart';

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

Example

SELECT * FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';

NOT Example

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

Example

SELECT * FROM Customers
WHERE NOT Country = 'Germany';

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 "Stuttgart" (use parenthesis to form complex expressions):

Example

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

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

Test Yourself With Exercises

Exercise:

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

 * FROM Customers
 City = 'Berlin'
  = 12209;

 

 

 
MySQL AND, OR, NOT
 

The MySQL 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:

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

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

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;

Test Yourself With Exercises

Exercise:

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

SELECT * FROM Customers
 ;

 

 

 
MySQL ORDER BY
 

The MySQL INSERT INTO Statement

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

INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows:

INSERT INTO table_name
VALUES (value1, value2, value3, ...);

Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90

Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91

Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland


INSERT INTO Example

The following SQL statement inserts a new record in the "Customers" table:

Example

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

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

CustomerID CustomerName ContactName Address City PostalCode Country
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90

Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91

Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway

Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an field and will be generated automatically when a new record is inserted into the table.


Insert Data Only in Specified Columns

It is also possible to only insert data in specific columns.

The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):

Example

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

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

CustomerID CustomerName ContactName Address City PostalCode Country
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90

Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91

Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal null null Stavanger null Norway

Test Yourself With Exercises

Exercise:

Insert a new record in the Customers table.

 Customers 
CustomerName, 
Address, 
City, 
PostalCode,
Country
 
'Hekkan Burger',
'Gateveien 15',
'Sandnes',
'4306',
'Norway';

 

 

 
MySQL INSERT INTO

MySQL NULL Values

 

What is a NULL Value?

A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value.

Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation!


How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
1

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4

Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden


The IS NULL Operator

The IS NULL operator is used to test for empty values (NULL values).

The following SQL lists all customers with a NULL value in the "Address" field:

Example

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

Tip: Always use IS NULL to look for NULL values.


The IS NOT NULL Operator

The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

The following SQL lists all customers with a value in the "Address" field:

Example

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;

Test Yourself With Exercises

Exercise:

Select all records from the Customers where the PostalCode column is empty.

SELECT * FROM Customers
WHERE   ;

 

 

 
MySQL NULL Values

The MySQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!


Demo Database

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

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

4

Around the Horn

Thomas Hardy

120 Hanover Sq.

London

WA1 1DP

UK


UPDATE Table

The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new city.

Example

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;

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

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Alfred Schmidt

Obere Str. 57

Frankfurt

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

4

Around the Horn

Thomas Hardy

120 Hanover Sq.

London

WA1 1DP

UK



UPDATE Multiple Records

It is the WHERE clause that determines how many records will be updated.

The following SQL statement will update the PostalCode to 00000 for all records where country is "Mexico":

Example

UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';

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

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Alfred Schmidt

Obere Str. 57

Frankfurt

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

00000

Mexico

3

Antonio Moreno Taquería

MySQL UPDATE

 

The MySQL DELETE Statement

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

DELETE Syntax

DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!


Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
1

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4

Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden


SQL DELETE Example

The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:

Example

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4

Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

Delete All Records

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

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table, without deleting the table:

Example

DELETE FROM Customers;

Test Yourself With Exercises

Exercise:

Delete all the records from the Customers table where the Country value is 'Norway'.

 Customers
 Country = 'Norway';

 

 

 
MySQL DELETE

The MySQL LIMIT Clause

The LIMIT clause is used to specify the number of records to return.

The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

LIMIT Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;


Demo Database

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

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

4

Around the Horn

Thomas Hardy

120 Hanover Sq.

London

WA1 1DP

UK

5

Berglunds snabbköp

Christina Berglund

Berguvsvägen 8

Luleå

S-958 22

Sweden



MySQL LIMIT Examples

The following SQL statement selects the first three records from the "Customers" table:

ExampleGet your own SQL Server

SELECT * FROM Customers
LIMIT 3;

-

What if we want to select records 4 - 6 (inclusive)?

MySQL provides a way to handle this: by using OFFSET.

The SQL query below says "return only 3 records, start on record 4 (OFFSET 3)":

Example

SELECT * FROM Customers
LIMIT 3 OFFSET 3;

-


ADD a WHERE CLAUSE

The following SQL statement selects the first three records from the "Customers" table, where the country is "Germany":

Example

SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

 

MySQL LIMIT
 

MySQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN() Syntax

SELECT MIN(column_name)
FROM table_name
WHERE condition;

MAX() Syntax

SELECT MAX(column_name)
FROM table_name
WHERE condition;

Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

MIN() Example

The following SQL statement finds the price of the cheapest product:

Example

SELECT MIN(Price) AS SmallestPrice
FROM Products;


MAX() Example

The following SQL statement finds the price of the most expensive product:

Example

SELECT MAX(Price) AS LargestPrice
FROM Products;

Test Yourself With Exercises

Exercise:

Use the MIN function to select the record with the smallest value of the Price column.

SELECT 
FROM Products;

 

 

 
MySQL MIN and MAX

MySQL COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criterion.

COUNT() Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

The AVG() function returns the average value of a numeric column. 

AVG() Syntax

SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the total sum of a numeric column. 

SUM() Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;

Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35


COUNT() Example

The following SQL statement finds the number of products:

Example

SELECT COUNT(ProductID)
FROM Products;

Note: NULL values are not counted.


AVG() Example

The following SQL statement finds the average price of all products:

Example

SELECT AVG(Price)
FROM Products;

Note: NULL values are ignored.


Demo Database

Below is a selection from the "OrderDetails" table in the Northwind sample database:

OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40

SUM() Example

The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:

Example

SELECT SUM(Quantity)
FROM OrderDetails;

Note: NULL values are ignored.


Test Yourself With Exercises

Exercise:

Use the correct function to return the number of records that have the Price value set to 18.

SELECT (*)
FROM Products
 Price = 18;


The MySQL LIKE Operator

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

There are two wildcards often used in conjunction with the LIKE operator:

  • The percent sign (%) represents zero, one, or multiple characters
  • The underscore sign (_) represents one, single character

The percent sign and the underscore can also be used in combinations!

LIKE Syntax

SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

Tip: You can also combine any number of conditions using AND or OR operators.

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator

Description

WHERE CustomerName LIKE 'a%'

Finds any values that start with "a"

WHERE CustomerName LIKE '%a'

Finds any values that end with "a"

WHERE CustomerName LIKE '%or%'

Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%'

Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%'

Finds any values that start with "a" and are at least 2 characters in length

WHERE CustomerName LIKE 'a__%'

Finds any values that start with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'

Finds any values that start with "a" and ends with "o"


Demo Database

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

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

4

Around the Horn

Thomas Hardy

120 Hanover Sq.

London

WA1 1DP

UK

5

Berglunds snabbköp

Christina Berglund

Berguvsvägen 8

Luleå

S-958 22

Sweden

6

Blauer See Delikatessen

Hanna Moos

Forsterstr. 57

Mannheim

68306

Germany

7

Blondel père et fils

Frédérique Citeaux

24, place Kléber

Strasbourg

67000

France

8

Bólido Comidas preparadas

Martín Sommer

C/ Araquil, 67

Madrid

28023

Spain

9

Bon app'

Laurence Lebihans

12, rue des Bouchers

Marseille

13008

France

10

Bottom-Dollar Marketse

Elizabeth Lincoln

23 Tsawassen Blvd.

Tsawassen

T2F 8M4

Canada

11

B's Beverages

Victoria Ashworth

Fauntleroy Circus

London

EC2 5NT

UK

12

Cactus Comidas para llevar

Patricio Simpson

Cerrito 333

Buenos Aires

1010

Argentina

13

Centro comercial Moctezuma

Francisco Chang

Sierras de Granada 9993

México D.F.

MySQL Wildcards


MySQL Wildcard Characters

A wildcard character is used to substitute one or more characters in a string.

Wildcard characters are used with the operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

Wildcard Characters in MySQL

Symbol Description Example
% Represents zero or more characters bl% finds bl, black, blue, and blob
_ Represents a single character h_t finds hot, hat, and hit

The wildcards can also be used in combinations!

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con Ave. Carlos Soublette #8-35 San Cristóbal 5022 Venezuela
36 Hungry Coyote Import Store Yoshi Latimer City Center Plaza 516 Main St. Elgin 97827 USA
37 Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road Cork Ireland
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
46 LILA-Supermercado Carlos González Carrera 52 con Ave. Bolívar #65-98 Llano Largo Barquisimeto 3508 Venezuela
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
53 North/South Simon Crowther South House 300 Queensbridge London SW7 1RZ UK
54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Piso 20-A Buenos Aires 1010 Argentina
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369 Köln 50739 Germany
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
75 Split Rail Beer & Ale Art Braunschweiger P.O. Box 555 Lander 82520 USA
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 05033 Mexico
81 Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland


Using the % Wildcard

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

Example

SELECT * FROM Customers
WHERE City LIKE 'ber%';

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

Example

SELECT * FROM Customers
WHERE City LIKE '%es%';

Using the _ Wildcard

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

Example

SELECT * FROM Customers
WHERE City LIKE '_ondon';

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

Example

SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

Test Yourself With Exercises

Exercise:

Select all records where the second letter of the City is an "a".

SELECT * FROM Customers
WHERE City LIKE '%';



The MySQL IN Operator

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

The IN operator is a shorthand for multiple OR conditions.

IN Syntax

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

or:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);

Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden
6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France
8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain
9 Bon app' Laurence Lebihans 12, rue des Bouchers Marseille 13008 France
10 Bottom-Dollar Marketse Elizabeth Lincoln 23 Tsawassen Blvd. Tsawassen T2F 8M4 Canada
11 B's Beverages Victoria Ashworth Fauntleroy Circus London EC2 5NT UK
12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina
13 Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. 05022 Mexico
14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland
15 Comércio Mineiro Pedro Afonso Av. dos Lusíadas, 23 São Paulo 05432-043 Brazil
16 Consolidated Holdings Elizabeth Brown Berkeley Gardens 12 Brewery London WX1 6LT UK
17 Drachenblut Delikatessend Sven Ottlieb Walserweg 21 Aachen 52066 Germany
18 Du monde entier Janine Labrune 67, rue des Cinquante Otages Nantes 44000 France
19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK
20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria
21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
22 FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid 28034 Spain
23 Folies gourmandes Martine Rancé 184, chaussée de Tournai Lille 59000 France
24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden
25 Frankenversand Peter Franken Berliner Platz 43 München 80805 Germany
26 France restauration Carine Schmitt 54, rue Royale Nantes 44000 France
27 Franchi S.p.A. Paolo Accorti Via Monte Bianco 34 Torino 10100 Italy
28 Furia Bacalhau e Frutos do Mar Lino Rodriguez Jardim das rosas n. 32 Lisboa 1675 Portugal
29 Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona 08022 Spain
30 Godos Cocina Típica José Pedro Freyre C/ Romero, 33 Sevilla 41101 Spain
31 Gourmet Lanchonetes André Fonseca Av. Brasil, 442 Campinas 04876-786 Brazil
32 Great Lakes Food Market Howard Snyder 2732 Baker Blvd. Eugene 97403 USA
33 GROSELLA-Restaurante Manuel Pereira 5ª Ave. Los Palos Grandes Caracas 1081 Venezuela
34 Hanari Carnes Mario Pontes Rua do Paço, 67 Rio de Janeiro 05454-876 Brazil
35 HILARIÓN-Abastos Carlos Hernández Carrera 22 con Ave. Carlos Soublette #8-35 San Cristóbal 5022 Venezuela
36 Hungry Coyote Import Store Yoshi Latimer City Center Plaza 516 Main St. Elgin 97827 USA
37 Hungry Owl All-Night Grocers Patricia McKenna 8 Johnstown Road Cork Ireland
38 Island Trading Helen Bennett Garden House Crowther Way Cowes PO31 7PJ UK
39 Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg 14776 Germany
40 La corne d'abondance Daniel Tonini 67, avenue de l'Europe Versailles 78000 France
41 La maison d'Asie Annette Roulet 1 rue Alsace-Lorraine Toulouse 31000 France
42 Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver V3F 2K1 Canada
43 Lazy K Kountry Store John Steel 12 Orchestra Terrace Walla Walla 99362 USA
44 Lehmanns Marktstand Renate Messner Magazinweg 7 Frankfurt a.M. 60528 Germany
45 Let's Stop N Shop Jaime Yorres 87 Polk St. Suite 5 San Francisco 94117 USA
46 LILA-Supermercado Carlos González Carrera 52 con Ave. Bolívar #65-98 Llano Largo Barquisimeto 3508 Venezuela
47 LINO-Delicateses Felipe Izquierdo Ave. 5 de Mayo Porlamar I. de Margarita 4980 Venezuela
48 Lonesome Pine Restaurant Fran Wilson 89 Chiaroscuro Rd. Portland 97219 USA
49 Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo 24100 Italy
50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium
51 Mère Paillarde Jean Fresnière 43 rue St. Laurent Montréal H1J 1C3 Canada
52 Morgenstern Gesundkost Alexander Feuer Heerstr. 22 Leipzig 04179 Germany
53 North/South Simon Crowther South House 300 Queensbridge London SW7 1RZ UK
54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Piso 20-A Buenos Aires 1010 Argentina
55 Old World Delicatessen Rene Phillips 2743 Bering St. Anchorage 99508 USA
56 Ottilies Käseladen Henriette Pfalzheim Mehrheimerstr. 369 Köln 50739 Germany
57 Paris spécialités Marie Bertrand 265, boulevard Charonne Paris 75012 France
58 Pericles Comidas clásicas Guillermo Fernández Calle Dr. Jorge Cash 321 México D.F. 05033 Mexico
59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria
60 Princesa Isabel Vinhoss Isabel de Castro Estrada da saúde n. 58 Lisboa 1756 Portugal
61 Que Delícia Bernardo Batista Rua da Panificadora, 12 Rio de Janeiro 02389-673 Brazil
62 Queen Cozinha Lúcia Carvalho Alameda dos Canàrios, 891 São Paulo 05487-020 Brazil
63 QUICK-Stop Horst Kloss Taucherstraße 10 Cunewalde 01307 Germany
64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina
65 Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque 87110 USA
66 Reggiani Caseifici Maurizio Moroni Strada Provinciale 124 Reggio Emilia 42100 Italy
67 Ricardo Adocicados Janete Limeira Av. Copacabana, 267 Rio de Janeiro 02389-890 Brazil
68 Richter Supermarkt Michael Holz Grenzacherweg 237 Genève 1203 Switzerland
69 Romero y tomillo Alejandra Camino Gran Vía, 1 Madrid 28001 Spain
70 Santé Gourmet Jonas Bergulfsen Erling Skakkes gate 78 Stavern 4110 Norway
71 Save-a-lot Markets Jose Pavarotti 187 Suffolk Ln. Boise 83720 USA
72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK
73 Simons bistro Jytte Petersen Vinbæltet 34 København 1734 Denmark
74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
75 Split Rail Beer & Ale Art Braunschweiger P.O. Box 555 Lander 82520 USA
76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium
77 The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland 97201 USA
78 The Cracker Box Liu Wong 55 Grizzly Peak Rd. Butte 59801 USA
79 Toms Spezialitäten Karin Josephs Luisenstr. 48 Münster 44087 Germany
80 Tortuga Restaurante Miguel Angel Paolino Avda. Azteca 123 México D.F. 05033 Mexico
81 Tradição Hipermercados Anabela Domingues Av. Inês de Castro, 414 São Paulo 05634-030 Brazil
82 Trail's Head Gourmet Provisioners Helvetius Nagy 722 DaVinci Blvd. Kirkland 98034 USA
83 Vaffeljernet Palle Ibsen Smagsløget 45 Århus 8200 Denmark
84 Victuailles en stock Mary Saveley 2, rue du Commerce Lyon 69004 France
85 Vins et alcools Chevalier Paul Henriot 59 rue de l'Abbaye Reims 51100 France
86 Die Wandernde Kuh Rita Müller Adenauerallee 900 Stuttgart 70563 Germany
87 Wartian Herkku Pirkko Koskitalo Torikatu 38 Oulu 90110 Finland
88 Wellington Importadora Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland


IN Operator Examples

The following SQL statement selects all customers that are located in "Germany", "France" or "UK":

Example

SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":

Example

SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as the suppliers:

Example

SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

Test Yourself With Exercises

Exercise:

Use the IN operator to select all the records where Country is either "Norway" or "France".

SELECT * FROM Customers
 
'France';



The MySQL BETWEEN Operator

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

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 bags 18
2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun Seasoning 1 2 48 - 6 oz jars 22
5 Chef Anton's Gumbo Mix 1 2 36 boxes 21.35

BETWEEN Example

The following SQL statement selects all products with a price between 10 and 20:

Example

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;


NOT BETWEEN Example

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

Example

SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN with IN Example

The following SQL statement selects all products with a price between 10 and 20. In addition; do not show products with a CategoryID of 1,2, or 3:

Example

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

BETWEEN Text Values Example

The following SQL statement selects all products with a ProductName between "Carnarvon Tigers" and "Mozzarella di Giovanni":

Example

SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

The following SQL statement selects all products with a ProductName between "Carnarvon Tigers" and "Chef Anton's Cajun Seasoning":

Example

SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;

NOT BETWEEN Text Values Example

The following SQL statement selects all products with a ProductName not between "Carnarvon Tigers" and "Mozzarella di Giovanni":

Example

SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

Sample Table

Below is a selection from the "Orders" table in the Northwind sample database:

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

The following SQL statement selects all orders with an OrderDate between '01-July-1996' and '31-July-1996':

Example

SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

Test Yourself With Exercises

Exercise:

Use the BETWEEN operator to select all the records where the value of the Price column is between 10 and 20.

SELECT * FROM Products
WHERE Price 
;


MySQL Aliases

Aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.

Alias Column Syntax

SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax

SELECT column_name(s)
FROM table_name AS alias_name;


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

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

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 for Columns Examples

The following SQL statement creates two aliases, one for the CustomerID column and one for the CustomerName column:

ExampleGet your own SQL Server

SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;

-

The following SQL statement creates two aliases, one for the CustomerName column and one for the ContactName column. Note: Single or double quotation marks are required if the alias name contains spaces:

Example

SELECT CustomerName AS Customer, ContactName AS "Contact Person"
FROM Customers;

-

The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode, City and Country):

Example

SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City, Country) AS Address
FROM Customers;

-


Alias for Tables Example

The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter):

Example

SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

-

The following SQL statement is the same as above, but without aliases:

Example

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;

-

Aliases can be useful when:

  • There are more than one table involved in a query
  • Functions are used in the query
  • Column names are big or not very readable
  • Two or more columns are combined together

 

MySQL Joining Tables

JOIN clause is used to combine rows from two or more tables, based on a related column between them.

Let's look at a selection from the "Orders" table:

OrderID

CustomerID

OrderDate

10308

2

1996-09-18

10309

37

1996-09-19

10310

77

1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Country

1

Alfreds Futterkiste

Maria Anders

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mexico

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

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables:

Example

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

-

and it will produce something like this:

OrderID

CustomerName

OrderDate

10308

Ana Trujillo Emparedados y helados

9/18/1996

10365

Antonio Moreno Taquería

11/27/1996

10383

Around the Horn

12/16/1996

10355

Around the Horn

11/15/1996

10278

Berglunds snabbköp

8/12/1996



Supported Types of Joins in MySQL

  • INNER JOIN: Returns records that have matching values in both tables
  • LEFT JOIN: Returns all records from the left table, and the matched records from the right table
  • RIGHT JOIN: Returns all records from the right table, and the matched records from the left table
  • CROSS JOIN: Returns all records from both tables


MySQL INNER JOIN  MySQL LEFT JOIN  MySQL RIGHT JOIN  MySQL CROSS JOIN


MySQL INNER JOIN Keyword

The INNER JOIN keyword selects records that have matching values in both tables.

MySQL INNER JOIN

INNER JOIN Syntax

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

And a selection from the "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


MySQL INNER JOIN Example

The following SQL statement selects all orders with customer information:

Example

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are records in the "Orders" table that do not have matches in "Customers", these orders will not be shown!


JOIN Three Tables

The following SQL statement selects all orders with customer and shipper information:

Example

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

Test Yourself With Exercises

Exercise:

Choose the correct JOIN clause to select all records from the two tables where there is a match in both tables.

SELECT *
FROM Orders

ON Orders.CustomerID=
Customers.CustomerID;


MySQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records (if any) from the right table (table2).

MySQL LEFT JOIN

LEFT JOIN Syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

And a selection from the "Orders" table:

OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10308

2

7

1996-09-18

3

10309

37

3

1996-09-19

1

10310

77

8

1996-09-20

2


MySQL LEFT JOIN Example

The following SQL statement will select all customers, and any orders they might have:

Example

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

-

Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there are no matches in the right table (Orders).

 

 

MySQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records (if any) from the left table (table1).

MySQL RIGHT JOIN

RIGHT JOIN Syntax

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

And a selection from the "Employees" table:

EmployeeID LastName FirstName BirthDate Photo
1 Davolio Nancy 12/8/1968 EmpID1.pic
2 Fuller Andrew 2/19/1952 EmpID2.pic
3 Leverling Janet 8/30/1963 EmpID3.pic

MySQL RIGHT JOIN Example

The following SQL statement will return all employees, and any orders they might have placed:

Example

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if there are no matches in the left table (Orders).



Test Yourself With Exercises

Exercise:

Choose the correct JOIN clause to select all the records from the Customers table plus all the matches in the Orders table.

SELECT *
FROM Orders

ON Orders.CustomerID=
Customers.CustomerID;

 

 

 

SQL CROSS JOIN Keyword

The CROSS JOIN keyword returns all records from both tables (table1 and table2).

MySQL CROSS JOIN

CROSS JOIN Syntax

SELECT column_name(s)
FROM table1
CROSS JOIN table2;

Note: CROSS JOIN can potentially return very large result-sets!


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

And a selection from the "Orders" table:

OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10308

2

7

1996-09-18

3

10309

37

3

1996-09-19

1

10310

77

8

1996-09-20

2



MySQL CROSS JOIN Example

The following SQL statement selects all customers, and all orders:

Example

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders;

-

Note: The CROSS JOIN keyword returns all matching records from both tables whether the other table matches or not. So, if there are rows in "Customers" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will be listed as well.

If you add a WHERE clause (if table1 and table2 has a relationship), the CROSS JOIN will produce the same result as the INNER JOIN clause:

Example

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders
WHERE Customers.CustomerID=Orders.CustomerID;

-

 

MySQL Self Join

A self join is a regular join, but the table is joined with itself.

Self Join Syntax

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

T1 and T2 are different table aliases for the same table.


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico


MySQL Self Join Example

The following SQL statement matches customers that are from the same city:

Example

SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;

 

The MySQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.

  • Every SELECT statement within UNION must have the same number of columns
  • The columns must also have similar data types
  • The columns in every SELECT statement must also be in the same order

UNION Syntax

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL Syntax

The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:

SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the result-set are usually equal to the column names in the first SELECT statement.


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

And a selection from the "Suppliers" table:

SupplierID

SupplierName

ContactName

Address

City

PostalCode

Country

1

Exotic Liquid

Charlotte Cooper

49 Gilbert St.

London

EC1 4SD

UK

2

New Orleans Cajun Delights

Shelley Burke

P.O. Box 78934

New Orleans

70117

USA

3

Grandma Kelly's Homestead

Regina Murphy

707 Oxford Rd.

Ann Arbor

48104

USA



SQL UNION Example

The following SQL statement returns the cities (only distinct values) from both the "Customers" and the "Suppliers" table:

Example

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

-

Note: If some customers or suppliers have the same city, each city will only be listed once, because UNION selects only distinct values. Use UNION ALL to also select duplicate values!


SQL UNION ALL Example

The following SQL statement returns the cities (duplicate values also) from both the "Customers" and the "Suppliers" table:

Example

SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

-


SQL UNION With WHERE

The following SQL statement returns the German cities (only distinct values) from both the "Customers" and the "Suppliers" table:

Example

SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

The MySQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT()MAX()MIN()SUM()AVG()) to group the result-set by one or more columns.

GROUP BY Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);


Demo Database

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

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

4

Around the Horn

Thomas Hardy

120 Hanover Sq.

London

WA1 1DP

UK

5

Berglunds snabbköp

Christina Berglund

Berguvsvägen 8

Luleå

S-958 22

Sweden



MySQL GROUP BY Examples

The following SQL statement lists the number of customers in each country:

ExampleGet your own SQL Server

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

-

The following SQL statement lists the number of customers in each country, sorted high to low:

Example

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

-


Demo Database

Below is a selection from the "Orders" table in the Northwind sample database:

OrderID

CustomerID

EmployeeID

OrderDate

ShipperID

10248

90

5

1996-07-04

3

10249

81

6

1996-07-05

1

10250

34

4

1996-07-08

2

And a selection from the "Shippers" table:

ShipperID

ShipperName

1

Speedy Express

2

United Package

3

Federal Shipping


GROUP BY With JOIN Example

The following SQL statement lists the number of orders sent by each shipper:

Example

SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

 


The MySQL HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

HAVING Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Demo Database

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

CustomerID CustomerName ContactName Address City PostalCode Country
1

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4

Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

MySQL HAVING Examples

The following SQL statement lists the number of customers in each country. Only include countries with more than 5 customers:

Example

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

The following SQL statement lists the number of customers in each country, sorted high to low (Only include countries with more than 5 customers):

Example

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;


Demo Database

Below is a selection from the "Orders" table in the Northwind sample database:

OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2

And a selection from the "Employees" table:

EmployeeID LastName FirstName BirthDate Photo Notes
1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....
2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....
3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....

More HAVING Examples

The following SQL statement lists the employees that have registered more than 10 orders:

Example

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

The following SQL statement lists if the employees "Davolio" or "Fuller" have registered more than 25 orders:

Example

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

The MySQL EXISTS Operator

The EXISTS operator is used to test for the existence of any record in a subquery.

The EXISTS operator returns TRUE if the subquery returns one or more records.

EXISTS Syntax

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(
SELECT column_name FROM table_name WHERE condition);


Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID

ProductName

SupplierID

CategoryID

Unit

Price

1

Chais

1

1

10 boxes x 20 bags

18

2

Chang

1

1

24 - 12 oz bottles

19

3

Aniseed Syrup

1

2

12 - 550 ml bottles

10

4

Chef Anton's Cajun Seasoning

2

2

48 - 6 oz jars

22

5

Chef Anton's Gumbo Mix

2

2

36 boxes

21.35

And a selection from the "Suppliers" table:

SupplierID

SupplierName

ContactName

Address

City

PostalCode

Country

1

Exotic Liquid

Charlotte Cooper

49 Gilbert St.

London

EC1 4SD

UK

2

New Orleans Cajun Delights

Shelley Burke

P.O. Box 78934

New Orleans

70117

USA

3

Grandma Kelly's Homestead

Regina Murphy

707 Oxford Rd.

Ann Arbor

48104

USA

4

Tokyo Traders

Yoshi Nagase

9-8 Sekimai Musashino-shi

Tokyo

100

Japan



MySQL EXISTS Examples

The following SQL statement returns TRUE and lists the suppliers with a product price less than 20:

Example

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);

-

The following SQL statement returns TRUE and lists the suppliers with a product price equal to 22:

Example

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);

-

 

The MySQL ANY and ALL Operators

The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.


The ANY Operator

The ANY operator:

  • returns a boolean value as a result
  • returns TRUE if ANY of the subquery values meet the condition

ANY means that the condition will be true if the operation is true for any of the values in the range.

ANY Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
  (
SELECT column_name
  
FROM table_name
  
WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).


The ALL Operator

The ALL operator:

  • returns a boolean value as a result
  • returns TRUE if ALL of the subquery values meet the condition
  • is used with SELECTWHERE and HAVING statements

ALL means that the condition will be true only if the operation is true for all values in the range.

ALL Syntax With SELECT

SELECT ALL column_name(s)
FROM table_name
WHERE condition;

ALL Syntax With WHERE or HAVING

SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
  (
SELECT column_name
  
FROM table_name
  
WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).


Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID

ProductName

SupplierID

CategoryID

Unit

Price

1

Chais

1

1

10 boxes x 20 bags

18

2

Chang

1

1

24 - 12 oz bottles

19

3

Aniseed Syrup

1

2

12 - 550 ml bottles

10

4

Chef Anton's Cajun Seasoning

2

2

48 - 6 oz jars

22

5

Chef Anton's Gumbo Mix

2

2

36 boxes

21.35

6

Grandma's Boysenberry Spread

3

2

12 - 8 oz jars

25

7

Uncle Bob's Organic Dried Pears

3

7

12 - 1 lb pkgs.

30

8

Northwoods Cranberry Sauce

3

2

12 - 12 oz jars

40

9

Mishi Kobe Niku

4

6

18 - 500 g pkgs.

97

And a selection from the "OrderDetails" table:

OrderDetailID

OrderID

ProductID

Quantity

1

10248

11

12

2

10248

42

10

3

10248

72

5

4

10249

14

9

5

10249

51

40

The MySQL INSERT INTO SELECT Statement

The INSERT INTO SELECT statement copies data from one table and inserts it into another table.

The INSERT INTO SELECT statement requires that the data types in source and target tables matches.

Note: The existing records in the target table are unaffected.

INSERT INTO SELECT Syntax

Copy all columns from one table to another table:

INSERT INTO table2
SELECT * FROM table1
WHERE condition;

Copy only some columns from one table into another table:

INSERT INTO table2 (column1column2column3, ...)
SELECT column1column2column3, ...
FROM table1
WHERE condition;


Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

1

Alfreds Futterkiste

Maria Anders

Obere Str. 57

Berlin

12209

Germany

2

Ana Trujillo Emparedados y helados

Ana Trujillo

Avda. de la Constitución 2222

México D.F.

05021

Mexico

3

Antonio Moreno Taquería

Antonio Moreno

Mataderos 2312

México D.F.

05023

Mexico

And a selection from the "Suppliers" table:

SupplierID

SupplierName

ContactName

Address

City

Postal Code

Country

1

Exotic Liquid

Charlotte Cooper

49 Gilbert St.

Londona

EC1 4SD

UK

2

New Orleans Cajun Delights

Shelley Burke

P.O. Box 78934

New Orleans

70117

USA

3

Grandma Kelly's Homestead

Regina Murphy

707 Oxford Rd.

Ann Arbor

48104

USA



MySQL INSERT INTO SELECT Examples

The following SQL statement copies "Suppliers" into "Customers" (the columns that are not filled with data, will contain NULL):

Example

INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;

The following SQL statement copies "Suppliers" into "Customers" (fill all columns):

Example

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;

The following SQL statement copies only the German suppliers into "Customers":

Example

INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

 


The MySQL CASE Statement

The CASE statement goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.

CASE Syntax

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;

Demo Database

Below is a selection from the "OrderDetails" table in the Northwind sample database:

OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40


MySQL CASE Examples

The following SQL goes through conditions and returns a value when the first condition is met:

Example

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN 'The quantity is greater than 30'
    WHEN Quantity = 30 THEN 'The quantity is 30'
    ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

The following SQL will order the customers by City. However, if City is NULL, then order by Country:

Example

SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);


MySQL IFNULL() and COALESCE() Functions

Look at the following "Products" table:

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23  
3 Gorgonzola 15.67 9 20

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.

Look at the following SELECT statement:

SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;

In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be NULL.


MySQL IFNULL() Function

The MySQL function lets you return an alternative value if an expression is NULL.

The example below returns 0 if the value is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;

MySQL COALESCE() Function

Or we can use the function, like this:

SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;

MySQL Comments


MySQL Comments

Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.


Single Line Comments

Single line comments start with --.

Any text between -- and the end of the line will be ignored (will not be executed).

The following example uses a single-line comment as an explanation:

Example

-- Select all:
SELECT * FROM Customers;

The following example uses a single-line comment to ignore the end of a line:

Example

SELECT * FROM Customers -- WHERE City='Berlin';

The following example uses a single-line comment to ignore a statement:

Example

-- SELECT * FROM Customers;
SELECT * FROM Products;


Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

Example

/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

The following example uses a multi-line comment to ignore many statements:

Example

/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;

To ignore just a part of a statement, also use the /* */ comment.

The following example uses a comment to ignore part of a line:

Example

SELECT CustomerName, /*City,*/ Country FROM Customers;

The following example uses a comment to ignore part of a statement:

Example

SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;

MySQL Operators

 

MySQL Arithmetic Operators

Operator Description  
+ Add  
- Subtract  
* Multiply  
/ Divide  
% Modulo  

MySQL Bitwise Operators

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR

MySQL Comparison Operators

Operator Description  
= Equal to  
> Greater than  
< Less than  
>= Greater than or equal to  
<= Less than or equal to  
<> Not equal to  


MySQL Compound Operators

Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
&= Bitwise AND equals
^-= Bitwise exclusive equals
|*= Bitwise OR equals

MySQL Logical Operators

Operator Description  
ALL TRUE if all of the subquery values meet the condition  
AND TRUE if all the conditions separated by AND is TRUE  
ANY TRUE if any of the subquery values meet the condition  
BETWEEN TRUE if the operand is within the range of comparisons  
EXISTS TRUE if the subquery returns one or more records  
IN TRUE if the operand is equal to one of a list of expressions  
LIKE TRUE if the operand matches a pattern  
NOT Displays a record if the condition(s) is NOT TRUE  
OR TRUE if any of the conditions separated by OR is TRUE  
SOME TRUE if any of the subquery values meet the condition  

 

 
 

The MySQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

Syntax

CREATE DATABASE databasename;

CREATE DATABASE Example

The following SQL statement creates a database called "testDB":

Example

CREATE DATABASE testDB;

Tip: Make sure you have admin privilege before creating any database. Once a database is created, you can check it in the list of databases with the following SQL command: SHOW DATABASES;

 

 

 

The MySQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.

Syntax

DROP DATABASE databasename;

Note: Be careful before dropping a database. Deleting a database will result in loss of complete information stored in the database!


DROP DATABASE Example

The following SQL statement drops the existing database "testDB":

Example

DROP DATABASE testDB;

Tip: Make sure you have admin privilege before dropping any database. Once a database is dropped, you can check it in the list of databases with the following SQL command: SHOW DATABASES;

 

The MySQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

Syntax

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);

The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).

Tip: For an overview of the available data types, go to our complete Data Types Reference.


MySQL CREATE TABLE Example

The following example creates a table called "Persons" that contains five columns: PersonID, LastName, FirstName, Address, and City:

Example

CREATE TABLE Persons (
    PersonID int,
    LastName varchar(
255),
    FirstName varchar(
255),
    Address varchar(
255),
    City varchar(
255)
);

The PersonID column is of type int and will hold an integer.

The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters.

The empty "Persons" table will now look like this:

PersonID

LastName

FirstName

Address

City

 

 

 

 

 

Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.



Create Table Using Another Table

A copy of an existing table can also be created using CREATE TABLE.

The new table gets the same column definitions. All columns or specific columns can be selected.

If you create a new table using an existing table, the new table will be filled with the existing values from the old table.

Syntax

CREATE TABLE new_table_name AS
    
SELECT column1, column2,...
    
FROM existing_table_name
    
WHERE ....;

The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table): 

Example

CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;

 

The MySQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.

Syntax

DROP TABLE table_name;

Note: Be careful before dropping a table. Deleting a table will result in loss of complete information stored in the table!


MySQL DROP TABLE Example

The following SQL statement drops the existing table "Shippers":

Example

DROP TABLE Shippers;


MySQL TRUNCATE TABLE

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.

Syntax

TRUNCATE TABLE table_name;

 

MySQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing table.


ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name
ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example

ALTER TABLE Customers
ADD Email varchar(255);


ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):

ALTER TABLE table_name
DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

Example

ALTER TABLE Customers
DROP COLUMN Email;


ALTER TABLE - MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name
MODIFY COLUMN column_name datatype;



MySQL ALTER TABLE Example

Look at the "Persons" table:

ID

LastName

FirstName

Address

City

1

Hansen

Ola

Timoteivn 10

Sandnes

2

Svendson

Tove

Borgvn 23

Sandnes

3

Pettersen

Kari

Storgt 20

Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

Example

ALTER TABLE Persons
ADD DateOfBirth date;

Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MySQL, go to our complete Data Types reference.

The "Persons" table will now look like this:

ID

LastName

FirstName

Address

City

 

1

Hansen

Ola

Timoteivn 10

Sandnes

 

2

Svendson

Tove

Borgvn 23

Sandnes

 

3

Pettersen

Kari

Storgt 20

Stavanger

 


Change Data Type Example

Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

Example

ALTER TABLE Persons
MODIFY COLUMN DateOfBirth year;

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-digit format.


DROP COLUMN Example

Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

Example

ALTER TABLE Persons
DROP COLUMN DateOfBirth;

The "Persons" table will now look like this:

ID

LastName

FirstName

Address

City

1

Hansen

Ola

Timoteivn 10

Sandnes

2

Svendson

Tove

Borgvn 23

Sandnes

3

Pettersen

Kari

Storgt 20

Stavanger

 

MySQL Constraints


SQL constraints are used to specify rules for data in a table.


Create Constraints

Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE statement.

Syntax

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ....
);

MySQL Constraints

SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted.

Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

  • - Ensures that a column cannot have a NULL value
  • - Ensures that all values in a column are different
  • - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
  • - Prevents actions that would destroy links between tables
  • - Ensures that the values in a column satisfies a specific condition
  • - Sets a default value for a column if no value is specified
  • - Used to create and retrieve data from the database very quickly


MySQL NOT NULL Constraint

By default, a column can hold NULL values.

The NOT NULL constraint enforces a column to NOT accept NULL values.

This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.


NOT NULL on CREATE TABLE

The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL values when the "Persons" table is created:

Example

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);

NOT NULL on ALTER TABLE

To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use the following SQL:

Example

ALTER TABLE Persons
MODIFY Age int NOT NULL;


MySQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different.

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.

However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.


UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    UNIQUE (ID)
);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT UC_Person UNIQUE (ID,LastName)
);


UNIQUE Constraint on ALTER TABLE

To create a UNIQUE constraint on the "ID" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ADD UNIQUE (ID);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a UNIQUE Constraint

To drop a UNIQUE constraint, use the following SQL:

ALTER TABLE Persons
DROP INDEX UC_Person;


MySQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table.

Primary keys must contain UNIQUE values, and cannot contain NULL values.

A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).



PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ADD PRIMARY KEY (ID);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have been declared to not contain NULL values (when the table was first created).


DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons
DROP PRIMARY KEY;

MySQL FOREIGN KEY Constraint

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.

The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

Look at the following two tables:

Persons Table

PersonID

LastName

FirstName

Age

1

Hansen

Ola

30

2

Svendson

Tove

23

3

Pettersen

Kari

20

Orders Table

OrderID

OrderNumber

PersonID

1

77895

3

2

44678

3

3

22456

2

4

24562

1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons" table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the parent table.



FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:

CREATE TABLE Orders (
    OrderID int 
NOT NULL,
    OrderNumber int 
NOT NULL,
    PersonID int,
    
PRIMARY KEY (OrderID),
    
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Orders (
    OrderID int 
NOT NULL,
    OrderNumber int 
NOT NULL,
    PersonID int,
    
PRIMARY KEY (OrderID),
    
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
    
REFERENCES Persons(PersonID)
);


FOREIGN KEY on ALTER TABLE

To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created, use the following SQL:

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);


DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;

 


MySQL CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a column it will allow only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.


CHECK on CREATE TABLE

The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The CHECK constraint ensures that the age of a person must be 18, or older:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255),
    CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);


CHECK on ALTER TABLE

To create a CHECK constraint on the "Age" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL:

ALTER TABLE Persons
DROP CHECK CHK_PersonAge;


MySQL DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.


DEFAULT on CREATE TABLE

The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT 'Sandnes'
);

The DEFAULT constraint can also be used to insert system values, by using functions like :

CREATE TABLE Orders (
    ID int NOT NULL,
    OrderNumber int NOT NULL,
    OrderDate date DEFAULT CURRENT_DATE()
);

DEFAULT on ALTER TABLE

To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';

DROP a DEFAULT Constraint

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons
ALTER City DROP DEFAULT;


MySQL CREATE INDEX Statement

The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So, only create indexes on columns that will be frequently searched against.

CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name
ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

MySQL CREATE INDEX Example

The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the "Persons" table:

CREATE INDEX idx_lastname
ON Persons (LastName);

If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:

CREATE INDEX idx_pname
ON Persons (LastName, FirstName);

DROP INDEX Statement

The DROP INDEX statement is used to delete an index in a table.

ALTER TABLE table_name
DROP INDEX index_name;


What is an AUTO INCREMENT Field?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.

Often this is the primary key field that we would like to be created automatically every time a new record is inserted.


MySQL AUTO_INCREMENT Keyword

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.

The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table:

CREATE TABLE Persons (
    Personid int NOT NULL AUTO_INCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (Personid)
);

To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:

ALTER TABLE Persons AUTO_INCREMENT=100;

When we insert a new record into the "Persons" table, we do NOT have to specify a value for the "Personid" column (a unique value will be added automatically):

INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen');

The SQL statement above would insert a new record into the "Persons" table. The "Personid" column would be assigned a unique value automatically. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".


MySQL Dates

The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database.

As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it gets more complicated.


MySQL Date Data Types

MySQL comes with the following data types for storing a date or a date/time value in the database:

  • DATE - format YYYY-MM-DD
  • DATETIME - format: YYYY-MM-DD HH:MI:SS
  • TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
  • YEAR - format YYYY or YY

Note: The date data type are set for a column when you create a new table in your database!


Working with Dates

Look at the following table:

Orders Table

OrderId

ProductName

OrderDate

1

Geitost

2008-11-11

2

Camembert Pierrot

2008-11-09

3

Mozzarella di Giovanni

2008-11-11

4

Mascarpone Fabioli

2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.

We use the following SELECT statement:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:

OrderId

ProductName

OrderDate

1

Geitost

2008-11-11

3

Mozzarella di Giovanni

2008-11-11

Note: Two dates can easily be compared if there is no time component involved!

Now, assume that the "Orders" table looks like this (notice the added time-component in the "OrderDate" column):

OrderId

ProductName

OrderDate

1

Geitost

2008-11-11 13:23:44

2

Camembert Pierrot

2008-11-09 15:45:21

3

Mozzarella di Giovanni

2008-11-11 11:12:01

4

Mascarpone Fabioli

2008-10-29 14:56:59

If we use the same SELECT statement as above:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

we will get no result! This is because the query is looking only for dates with no time portion.

Tip: To keep your queries simple and easy to maintain, do not use time-components in your dates, unless you have to!

 

MySQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the data were coming from one single table.

A view is created with the CREATE VIEW statement.

CREATE VIEW Syntax

CREATE VIEW view_name AS
SELECT column1column2, ...
FROM table_name
WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the view, every time a user queries it.


MySQL CREATE VIEW Examples

The following SQL creates a view that shows all customers from Brazil:

Example

CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

We can query the view above as follows:

Example

SELECT * FROM [Brazil Customers];

The following SQL creates a view that selects every product in the "Products" table with a price higher than the average price:

Example

CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

We can query the view above as follows:

Example

SELECT * FROM [Products Above Average Price];



MySQL Updating a View

A view can be updated with the CREATE OR REPLACE VIEW statement.

CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS
SELECT column1column2, ...
FROM table_name
WHERE condition;

The following SQL adds the "City" column to the "Brazil Customers" view:

Example

CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';


MySQL Dropping a View

A view is deleted with the DROP VIEW statement.

DROP VIEW Syntax

DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:

Example

DROP VIEW [Brazil Customers];

 

The data type of a column defines what value the column can hold: integer, character, money, date and time, binary, and so on.


MySQL Data Types (Version 8.0)

Each column in a database table is required to have a name and a data type.

An SQL developer must decide what type of data that will be stored inside each column when creating a table. The data type is a guideline for SQL to understand what type of data is expected inside of each column, and it also identifies how SQL will interact with the stored data.

In MySQL there are three main data types: string, numeric, and date and time.

String Data Types

Data type

Description

CHAR(size)

A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1

VARCHAR(size)

A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535

BINARY(size)

Equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1

VARBINARY(size)

Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies the maximum column length in bytes.

TINYBLOB

For BLOBs (Binary Large OBjects). Max length: 255 bytes

TINYTEXT

Holds a string with a maximum length of 255 characters

TEXT(size)

Holds a string with a maximum length of 65,535 bytes

BLOB(size)

For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT

Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB

For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data

LONGTEXT

Holds a string with a maximum length of 4,294,967,295 characters

LONGBLOB

For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data

ENUM(val1, val2, val3, ...)

A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them

SET(val1, val2, val3, ...)

A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list



Numeric Data Types

Data type

Description

BIT(size)

A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1.

TINYINT(size)

A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255)

BOOL

Zero is considered as false, nonzero values are considered as true.

BOOLEAN

Equal to BOOL

SMALLINT(size)

A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255)

MEDIUMINT(size)

A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255)

INT(size)

A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255)

INTEGER(size)

Equal to INT(size)

BIGINT(size)

A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255)

FLOAT(sized)

A floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. This syntax is deprecated in MySQL 8.0.17, and it will be removed in future MySQL versions

FLOAT(p)

A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE()

DOUBLE(sized)

A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter

DOUBLE PRECISION(sized)

 

DECIMAL(sized)

An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.

DEC(sized)

Equal to DECIMAL(size,d)

Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values for the column. If you add the ZEROFILL option, MySQL automatically also adds the UNSIGNED attribute to the column.

Date and Time Data Types

Data type

Description

DATE

A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'

DATETIME(fsp)

A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization and updating to the current date and time

TIMESTAMP(fsp)

A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition

TIME(fsp)

A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'

YEAR

A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.

 

MySQL has many built-in functions.

This reference contains string, numeric, date, and some advanced functions in MySQL.


MySQL String Functions

Function

Description

ASCII

Returns the ASCII value for the specific character

CHAR_LENGTH

Returns the length of a string (in characters)

CHARACTER_LENGTH

Returns the length of a string (in characters)

CONCAT

Adds two or more expressions together

CONCAT_WS

Adds two or more expressions together with a separator

FIELD

Returns the index position of a value in a list of values

FIND_IN_SET

Returns the position of a string within a list of strings

FORMAT

Formats a number to a format like "#,###,###.##", rounded to a specified number of decimal places

INSERT

Inserts a string within a string at the specified position and for a certain number of characters

INSTR

Returns the position of the first occurrence of a string in another string

LCASE

Converts a string to lower-case

LEFT

Extracts a number of characters from a string (starting from left)

LENGTH

Returns the length of a string (in bytes)

LOCATE

Returns the position of the first occurrence of a substring in a string

LOWER

Converts a string to lower-case

LPAD

Left-pads a string with another string, to a certain length

LTRIM

Removes leading spaces from a string

MID

Extracts a substring from a string (starting at any position)

POSITION

Returns the position of the first occurrence of a substring in a string

REPEAT

Repeats a string as many times as specified

REPLACE

Replaces all occurrences of a substring within a string, with a new substring

REVERSE

Reverses a string and returns the result

RIGHT

Extracts a number of characters from a string (starting from right)

RPAD

Right-pads a string with another string, to a certain length

RTRIM

Removes trailing spaces from a string

SPACE

Returns a string of the specified number of space characters

STRCMP

Compares two strings

SUBSTR

Extracts a substring from a string (starting at any position)

SUBSTRING

Extracts a substring from a string (starting at any position)

SUBSTRING_INDEX

Returns a substring of a string before a specified number of delimiter occurs

TRIM

Removes leading and trailing spaces from a string

UCASE

Converts a string to upper-case

UPPER

Converts a string to upper-case



MySQL Numeric Functions

Function

Description

ABS

Returns the absolute value of a number

ACOS

Returns the arc cosine of a number

ASIN

Returns the arc sine of a number

ATAN

Returns the arc tangent of one or two numbers

ATAN2

Returns the arc tangent of two numbers

AVG

Returns the average value of an expression

CEIL

Returns the smallest integer value that is >= to a number

CEILING

Returns the smallest integer value that is >= to a number

COS

Returns the cosine of a number

COT

Returns the cotangent of a number

COUNT

Returns the number of records returned by a select query

DEGREES

Converts a value in radians to degrees

DIV

Used for integer division

EXP

Returns e raised to the power of a specified number

FLOOR

Returns the largest integer value that is <= to a number

GREATEST

Returns the greatest value of the list of arguments

LEAST

Returns the smallest value of the list of arguments

LN

Returns the natural logarithm of a number

LOG

Returns the natural logarithm of a number, or the logarithm of a number to a specified base

Example

Return the ASCII value of the first character in "CustomerName":

SELECT ASCII(CustomerName) AS NumCodeOfFirstChar
FROM Customers;

 


Definition and Usage

The ASCII() function returns the ASCII value for the specific character.

Syntax

ASCII(character)

Parameter Values

Parameter

Description

character

Required. The character to return the ASCII value for. If more than one character is entered, it will only return the value for the first character

Technical Details

Works in:

From MySQL 4.0

 

Example

Return the length of the string:

SELECT CHAR_LENGTH("SQL Tutorial"AS LengthOfString;

 


Definition and Usage

The CHAR_LENGTH() function return the length of a string (in characters).

Note: This function is equal to the CHARACTER_LENGTH() function.

Syntax

CHAR_LENGTH(string)

Parameter Values

Parameter

Description

string

Required. The string to count the length for

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Return the length of the text in the "CustomerName" column:

SELECT CHAR_LENGTH(CustomerName) AS LengthOfName
FROM Customers;

 

Example

Return the length of the string:

SELECT CHARACTER_LENGTH("SQL Tutorial"AS LengthOfString;

-


Definition and Usage

The CHARACTER_LENGTH() function return the length of a string (in characters).

Note: This function is equal to the CHAR_LENGTH() function.

Syntax

CHARACTER_LENGTH(string)

Parameter Values

Parameter

Description

string

Required. The string to count the length for

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Return the length of the text in the "CustomerName" column:

SELECT CHARACTER_LENGTH(CustomerName) AS LengthOfName
FROM Customers;

-

 

Example

Add several strings together:

SELECT CONCAT("SQL ""Tutorial ""is ""fun!"AS ConcatenatedString;

-


Definition and Usage

The CONCAT() function adds two or more expressions together.

Note: Also look at the CONCAT_WS() function.

Syntax

CONCAT(expression1expression2expression3,...)

Parameter Values

Parameter

Description

expression1,
expression2,
expression3,
etc.

Required. The expressions to add together.

Note: If any of the expressions is a NULL value, it returns NULL

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Add three columns into one "Address" column:

SELECT CONCAT(Address, " ", PostalCode, " ", City) AS Address
FROM Customers;

-

 

Example

Add several expressions together, and add a "-" separator between them:

SELECT CONCAT_WS("-""SQL""Tutorial""is""fun!"AS ConcatenatedString;

-


Definition and Usage

The CONCAT_WS() function adds two or more expressions together with a separator.

Note: Also look at the CONCAT() function.

Syntax

CONCAT_WS(separatorexpression1expression2expression3,...)

Parameter Values

Parameter

Description

separator

Required. The separator to add between each of the expressions. If separator is NULL, this function returns NULL

expression1,
expression2,
expression3,
etc.

Required. The expressions to add together. An expression with a NULL value will be skipped

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Add three columns (and add a space between them) into one "Address" column:

SELECT CONCAT_WS(" ", Address, PostalCode, City) AS Address
FROM Customers;

-

 

Example

Return the index position of  "q" in the string list:

SELECT FIELD("q", "s", "q", "l");

Definition and Usage

The FIELD() function returns the index position of a value in a list of values.

This function performs a case-insensitive search.

Note: If the specified value is not found in the list of values, this function will return 0. If value is NULL, this function will return 0.

Syntax

FIELD(value, val1, val2, val3, ...)

Parameter Values

Parameter Description
value Required. The value to search for in the list
val1, val2, val3, .... Required. The list of values to search

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the index position of "c" in the string list:

SELECT FIELD("c", "a", "b");

Example

Return the index position of "Q" in the string list:

SELECT FIELD("Q", "s", "q", "l");

Example

Return the index position of 5 in the numeric list:

SELECT FIELD(5, 0, 1, 2, 3, 4, 5);

Example

Search for "q" within the list of strings:

SELECT FIND_IN_SET("q""s,q,l");

-


Definition and Usage

The FIND_IN_SET() function returns the position of a string within a list of strings.

Syntax

FIND_IN_SET(stringstring_list)

Parameter Values

Parameter

Description

string

Required. The string to search for

string_list

Required. The list of string values to be searched (separated by commas)

Return Values

  • If string is not found in string_list, this function returns 0
  • If string or string_list is NULL, this function returns NULL
  • If string_list is an empty string (""), this function returns 0

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Search for "a" within the list of strings:

SELECT FIND_IN_SET("a""s,q,l");

-

Example

Search for "q" within the list of strings (string list is NULL):

SELECT FIND_IN_SET("q"null);

-

 

Example

Format the number as "#,###,###.##" (and round with two decimal places):

SELECT FORMAT(250500.5634, 2);

Definition and Usage

The FORMAT() function formats a number to a format like "#,###,###.##", rounded to a specified number of decimal places, then it returns the result as a string.

Syntax

FORMAT(number, decimal_places)

Parameter Values

Parameter Description
number Required. The number to be formatted
decimal_places Required. The number of decimal places for number. If this parameter is 0, this function returns a string with no decimal places

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Format the number as a format of "#,###,###.##" (and round with 0 decimal places):

SELECT FORMAT(250500.5634, 0);

Example

Insert the string "Example" into the string "W3Schools.com". Replace the first nine characters:

SELECT INSERT("W3Schools.com"19"Example");

-


Definition and Usage

The INSERT() function inserts a string within a string at the specified position and for a certain number of characters.

Syntax

INSERT(stringpositionnumberstring2)

Parameter Values

Parameter

Description

string

Required. The string that will be modified

position

Required. The position where to insert string2

number

Required. The number of characters to replace

string2

Required. The string to insert into string

Return Values

  • If position is outside the length of string, this function returns string
  • If number is higher than the length of the rest of the string, this function replaces string from position until the end of string

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Insert the string "no" into the string "W3Schools.com". Replace three characters, starting from position 11:

SELECT INSERT("W3Schools.com"113"no");

-

 

Example

Search for "3" in string "W3Schools.com", and return position:

SELECT INSTR("W3Schools.com""3"AS MatchPosition;

-


Definition and Usage

The INSTR() function returns the position of the first occurrence of a string in another string.

This function performs a case-insensitive search.

Syntax

INSTR(string1string2)

Parameter Values

Parameter

Description

string1

Required. The string that will be searched

string2

Required. The string to search for in string1. If string2 is not found, this function returns 0

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Search for "COM" in string "W3Schools.com", and return position:

SELECT INSTR("W3Schools.com""COM"AS MatchPosition;

-

Example

Search for "a" in CustomerName column, and return position:

SELECT INSTR(CustomerName, "a")
FROM Customers;

-

 

Example

Convert the text to lower-case:

SELECT LCASE("SQL Tutorial is FUN!");

-


Definition and Usage

The LCASE() function converts a string to lower-case.

Note: The LOWER() function is a synonym for the LCASE() function.

Syntax

LCASE(text)

Parameter Values

Parameter

Description

text

Required. The string to convert

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Convert the text in "CustomerName" to lower-case:

SELECT LCASE(CustomerName) AS LowercaseCustomerName
FROM Customers;

-

 

Example

Extract 3 characters from a string (starting from left):

SELECT LEFT("SQL Tutorial"3AS ExtractString;

-


Definition and Usage

The LEFT() function extracts a number of characters from a string (starting from left).

Tip: Also look at the RIGHT() function.

Syntax

LEFT(stringnumber_of_chars)

Parameter Values

Parameter

Description

string

Required. The string to extract from

number_of_chars

Required. The number of characters to extract. If this parameter is larger than the number of characters in string, this function will return string

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Extract 5 characters from the text in the "CustomerName" column (starting from left):

SELECT LEFT(CustomerName, 5AS ExtractString
FROM Customers;

-

 

Example

Return the length of the string, in bytes:

SELECT LENGTH("SQL Tutorial"AS LengthOfString;

-


Definition and Usage

The LENGTH() function returns the length of a string (in bytes).

Syntax

LENGTH(string)

Parameter Values

Parameter

Description

string

Required. The string to count the length for

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Return the length of the text in the "CustomerName" column, in bytes:

SELECT LENGTH(CustomerName) AS LengthOfName
FROM Customers;

 

Example

Search for "3" in string "W3Schools.com", and return position:

SELECT LOCATE("3""W3Schools.com"AS MatchPosition;

-


Definition and Usage

The LOCATE() function returns the position of the first occurrence of a substring in a string.

If the substring is not found within the original string, this function returns 0.

This function performs a case-insensitive search.

Note: This function is equal to the POSITION() function.

Syntax

LOCATE(substringstringstart)

Parameter Values

Parameter

Description

substring

Required. The substring to search for in string

string

Required. The string that will be searched

start

Optional. The starting position for the search. Position 1 is default

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Search for "com" in string "W3Schools.com" (start at position 3), and return position:

SELECT LOCATE("com""W3Schools.com"3AS MatchPosition;

-

Example

Search for "a" in CustomerName column, and return position:

SELECT LOCATE("a", CustomerName)
FROM Customers;

-

 

Example

Convert the text to lower-case:

SELECT LOWER("SQL Tutorial is FUN!");

-


Definition and Usage

The LOWER() function converts a string to lower-case.

Note: The LCASE() function is equal to the LOWER() function.

Syntax

LOWER(text)

Parameter Values

Parameter

Description

text

Required. The string to convert

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Convert the text in "CustomerName" to lower-case:

SELECT LOWER(CustomerName) AS LowercaseCustomerName
FROM Customers;

-

 

Example

Left-pad the string with "ABC", to a total length of 20:

SELECT LPAD("SQL Tutorial"20"ABC");

-


Definition and Usage

The LPAD() function left-pads a string with another string, to a certain length.

Note: Also look at the RPAD() function.

Syntax

LPAD(stringlengthlpad_string)

Parameter Values

Parameter

Description

string

Required. The original string. If the length of the original string is larger than the length parameter, this function removes the overfloating characters from string

length

Required. The length of the string after it has been left-padded

lpad_string

Required. The string to left-pad to string

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Left-pad the text in "CustomerName" with "ABC", to a total length of 30:

SELECT LPAD(CustomerName, 30"ABC"AS LeftPadCustomerName
FROM Customers;

-

 

Example

Remove leading spaces from a string:

SELECT LTRIM("     SQL Tutorial"AS LeftTrimmedString;

 


Definition and Usage

The LTRIM() function removes leading spaces from a string.

Syntax

LTRIM(string)

Parameter Values

Parameter

Description

string

Required. The string to remove leading spaces from

Technical Details

Works in:

From MySQL 4.0

 

Example

Extract a substring from a string (start at position 5, extract 3 characters):

SELECT MID("SQL Tutorial", 5, 3) AS ExtractString;

Definition and Usage

The MID() function extracts a substring from a string (starting at any position).

Note: The MID() and functions equals the function.

Syntax

MID(string, start, length)

Parameter Values

Parameter Description
string Required. The string to extract from
start Required. The start position. Can be both a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string
length Required. The number of characters to extract

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract a substring from the text in a column (start at position 2, extract 5 characters):

SELECT MID(CustomerName, 2, 5) AS ExtractString
FROM Customers;

Example

Extract a substring from a string (start from the end, at position -5, extract 5 characters):

SELECT MID("SQL Tutorial", -5, 5) AS ExtractString;

Example

Search for "3" in string "W3Schools.com", and return position:

SELECT POSITION("3" IN "W3Schools.com") AS MatchPosition;

Definition and Usage

The POSITION() function returns the position of the first occurrence of a substring in a string.

If the substring is not found within the original string, this function returns 0.

This function performs a case-insensitive search.

Note: The function is equal to the POSITION() function.

Syntax

POSITION(substring IN string)

Parameter Values

Parameter Description
substring Required. The substring to search for in string
string Required. The original string that will be searched

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Search for "COM" in string "W3Schools.com", and return position:

SELECT POSITION("COM" IN "W3Schools.com") AS MatchPosition;

Example

Search for "a" in CustomerName column, and return position:

SELECT POSITION("a" IN CustomerName)
FROM Customers;

Example

Repeat a string 3 times:

SELECT REPEAT("SQL Tutorial", 3);

Definition and Usage

The REPEAT() function repeats a string as many times as specified.

Syntax

REPEAT(string, number)

Parameter Values

Parameter Description
string Required. The string to repeat
number Required. The number of times to repeat the string

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Repeat the text in CustomerName 2 times:

SELECT REPEAT(CustomerName, 2)
FROM Customers;

Example

Repeat the string 0 times:

SELECT REPEAT("SQL Tutorial", 0);

Example

Replace "SQL" with "HTML":

SELECT REPLACE("SQL Tutorial", "SQL", "HTML");

Definition and Usage

The REPLACE() function replaces all occurrences of a substring within a string, with a new substring.

Note: This function performs a case-sensitive replacement.

Syntax

REPLACE(string, substring, new_string)

Parameter Values

Parameter Description
string Required. The original string
substring Required. The substring to be replaced
new_string Required. The new replacement substring

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Replace "X" with "M":

SELECT REPLACE("XYZ FGH XYZ", "X", "M");

Example

Replace "X" with "m":

SELECT REPLACE("XYZ FGH XYZ", "X", "m");

Example

Replace "x" with "m":

SELECT REPLACE("XYZ FGH XYZ", "x", "m");

Example

Reverse a string:

SELECT REVERSE("SQL Tutorial");

Definition and Usage

The REVERSE() function reverses a string and returns the result.

Syntax

REVERSE(string)

Parameter Values

Parameter Description
string Required. The string to reverse

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Reverse the text in CustomerName:

SELECT REVERSE(CustomerName)
FROM Customers;

Example

Extract 4 characters from a string (starting from right):

SELECT RIGHT("SQL Tutorial is cool", 4) AS ExtractString;

Definition and Usage

The RIGHT() function extracts a number of characters from a string (starting from right).

Tip: Also look at the function.

Syntax

RIGHT(string, number_of_chars)

Parameter Values

Parameter Description
string Required. The string to extract from
number_of_chars Required. The number of characters to extract. If this parameter is larger than the number of characters in string, this function will return string

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract 5 characters from the text in the "CustomerName" column (starting from right):

SELECT RIGHT(CustomerName, 5) AS ExtractString
FROM Customers;

Example

Right-pad the string with "ABC", to a total length of 20:

SELECT RPAD("SQL Tutorial", 20, "ABC");

Definition and Usage

The RPAD() function right-pads a string with another string, to a certain length.

Note: Also look at the function.

Syntax

RPAD(string, length, rpad_string)

Parameter Values

Parameter Description
string Required. The original string. If the length of the original string is larger than the length parameter, this function removes the overfloating characters from string
length Required. The length of the string after it has been right-padded
rpad_string Required. The string to right-pad to string

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Right-pad the text in "CustomerName" with "ABC", to a total length of 30:

SELECT RPAD(CustomerName, 30, "ABC") AS RightPadCustomerName
FROM Customers;

Example

Remove trailing spaces from a string:

SELECT RTRIM("SQL Tutorial     ") AS RightTrimmedString;

Definition and Usage

The RTRIM() function removes trailing spaces from a string.

Syntax

RTRIM(string)

Parameter Values

Parameter Description
string Required. The string to remove trailing spaces from

Technical Details

Works in: From MySQL 4.0

Example

Return a string with 10 space characters:

SELECT SPACE(10);

Definition and Usage

The SPACE() function returns a string of the specified number of space characters.

Syntax

SPACE(number)

Parameter Values

Parameter Description
number Required. The number of space characters to return

Technical Details

Works in: From MySQL 4.0

Example

Compare two strings:

SELECT STRCMP("SQL Tutorial", "SQL Tutorial");

Definition and Usage

The STRCMP() function compares two strings.

Syntax

STRCMP(string1, string2)

Parameter Values

Parameter Description
string1, string2 Required. The two strings to be compared

Return Values

  • If string1 = string2, this function returns 0
  • If string1 < string2, this function returns -1
  • If string1 > string2, this function returns 1

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Compare two strings:

SELECT STRCMP("SQL Tutorial", "HTML Tutorial");

Example

Extract a substring from a string (start at position 5, extract 3 characters):

SELECT SUBSTR("SQL Tutorial", 5, 3) AS ExtractString;

Definition and Usage

The SUBSTR() function extracts a substring from a string (starting at any position).

Note: The SUBSTR() and functions equals to the function.

Syntax

SUBSTR(string, start, length)

OR:

SUBSTR(string FROM start FOR length)

Parameter Values

Parameter Description
string Required. The string to extract from
start Required. The start position. Can be both a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string
length Optional. The number of characters to extract. If omitted, the whole string will be returned (from the start position)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract a substring from the text in a column (start at position 2, extract 5 characters):

SELECT SUBSTR(CustomerName, 2, 5) AS ExtractString
FROM Customers;

Example

Extract a substring from a string (start from the end, at position -5, extract 5 characters):

SELECT SUBSTR("SQL Tutorial", -5, 5) AS ExtractString;

Example

Extract a substring from a string (start at position 5, extract 3 characters):

SELECT SUBSTRING("SQL Tutorial", 5, 3) AS ExtractString;

Definition and Usage

The SUBSTRING() function extracts a substring from a string (starting at any position).

Note: The and functions equals to the SUBSTRING() function.

Syntax

SUBSTRING(string, start, length)

OR:

SUBSTRING(string FROM start FOR length)

Parameter Values

Parameter Description
string Required. The string to extract from
start Required. The start position. Can be both a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string
length Optional. The number of characters to extract. If omitted, the whole string will be returned (from the start position)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract a substring from the text in a column (start at position 2, extract 5 characters):

SELECT SUBSTRING(CustomerName, 2, 5) AS ExtractString
FROM Customers;

Example

Extract a substring from a string (start from the end, at position -5, extract 5 characters):

SELECT SUBSTRING("SQL Tutorial", -5, 5) AS ExtractString;

Example

Return a substring of a string before a specified number of delimiter occurs:

SELECT SUBSTRING_INDEX("www.w3schools.com", ".", 1);

Definition and Usage

The SUBSTRING_INDEX() function returns a substring of a string before a specified number of delimiter occurs.

Syntax

SUBSTRING_INDEX(string, delimiter, number)

Parameter Values

Parameter Description
string Required. The original string
delimiter Required. The delimiter to search for
number Required. The number of times to search for the delimiter. Can be both a positive or negative number. If it is a positive number, this function returns all to the left of the delimiter. If it is a negative number, this function returns all to the right of the delimiter.

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a substring of a string before a specified number of delimiter occurs:

SELECT SUBSTRING_INDEX("www.w3schools.com", ".", 2);

Example

Remove leading and trailing spaces from a string:

SELECT TRIM('    SQL Tutorial    ') AS TrimmedString;

Definition and Usage

The TRIM() function removes leading and trailing spaces from a string.

Syntax

TRIM(string)

Parameter Values

Parameter Description
string Required. The string to remove leading and trailing spaces from

Technical Details

Works in: From MySQL 4.0

Example

Convert the text to upper-case:

SELECT UCASE("SQL Tutorial is FUN!");

-


Definition and Usage

The UCASE() function converts a string to upper-case.

Note: This function is equal to the UPPER() function.

Syntax

UCASE(text)

Parameter Values

Parameter

Description

text

Required. The string to convert

Technical Details

Works in:

From MySQL 4.0


More Examples

Example

Convert the text in "CustomerName" to upper-case:

SELECT UCASE(CustomerName) AS UppercaseCustomerName
FROM Customers;

 

Example

Convert the text to upper-case:

SELECT UPPER("SQL Tutorial is FUN!");

Definition and Usage

The UPPER() function converts a string to upper-case.

Note: This function is equal to the function.

Syntax

UPPER(text)

Parameter Values

Parameter Description
text Required. The string to convert

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert the text in "CustomerName" to upper-case:

SELECT UPPER(CustomerName) AS UppercaseCustomerName
FROM Customers;

Example

Return the absolute value of a number:

SELECT ABS(-243.5);

Definition and Usage

The ABS() function returns the absolute (positive) value of a number.

Syntax

ABS(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

Example

Return the arc cosine of a number:

SELECT ACOS(0.25);

Definition and Usage

The ACOS() function returns the arc cosine of a number.

The specified number must be between -1 to 1, otherwise this function returns NULL.

Syntax

ACOS(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the arc cosine of a number:

SELECT ACOS(-0.8);

Example

Return the arc sine of a number:

SELECT ASIN(0.25);

Definition and Usage

The ASIN() function returns the arc sine of a number.

The specified number must be between -1 to 1, otherwise this function returns NULL. 

Syntax

ASIN(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the arc sine of a number:

SELECT ASIN(-0.8);

Example

Return the arc tangent of a number:

SELECT ATAN(2.5);

Definition and Usage

The ATAN() function returns the arc tangent of one or two numbers.

Syntax

ATAN(number)

OR:

ATAN(a, b)

Parameter Values

Parameter Description
number A numeric value
a, b Two numeric values to calculate the arc tangent of

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the arc tangent of two values:

SELECT ATAN(-0.8, 2);

Example

Return the arc tangent of two values:

SELECT ATAN2(0.50, 1);

Definition and Usage

The ATAN2() function returns the arc tangent of two numbers.

Syntax

ATAN2(a, b)

Parameter Values

Parameter Description
a, b Required. Two numeric values to calculate the arc tangent of

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the arc tangent of two values:

SELECT ATAN2(-0.8, 2);

Example

Return the average value for the "Price" column in the "Products" table:

SELECT AVG(Price) AS AveragePrice FROM Products;

Definition and Usage

The AVG() function returns the average value of an expression.

Note: NULL values are ignored. 

Syntax

AVG(expression)

Parameter Values

Parameter Description
expression Required. A numeric value (can be a field or a formula)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Select the records that have a price above the average price:

SELECT * FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

Example

Return the smallest integer value that is greater than or equal to 25.75:

SELECT CEIL(25.75);

Definition and Usage

The CEIL() function returns the smallest integer value that is bigger than or equal to a number.

Note: This function is equal to the function.

Syntax

CEIL(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the smallest integer value that is greater than or equal to 25:

SELECT CEIL(25);

Example

Return the smallest integer value that is greater than or equal to 25.75:

SELECT CEILING(25.75);

Definition and Usage

The CEILING() function returns the smallest integer value that is bigger than or equal to a number.

Note: This function is equal to the function.

Syntax

CEILING(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the smallest integer value that is greater than or equal to 25:

SELECT CEILING(25);

Example

Return the cosine of a number:

SELECT COS(2);

Definition and Usage

The COS() function returns the cosine of a number.

Syntax

COS(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the cosine of a number:

SELECT COS(PI());

Example

Return the cotangent of a number:

SELECT COT(6);

Definition and Usage

The COT() function returns the cotangent of a number.

Syntax

COT(number)

Parameter Values

Parameter Description
number Required. A numeric value. If number is 0, an error or NULL is returned

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the cotangent of a number:

SELECT COT(-2);

Example

Return the number of products in the "Products" table:

SELECT COUNT(ProductID) AS NumberOfProducts FROM Products;

Definition and Usage

The COUNT() function returns the number of records returned by a select query.

Note: NULL values are not counted.

Syntax

COUNT(expression)

Parameter Values

Parameter Description
expression Required. A field or a string value

Technical Details

Works in: From MySQL 4.0

Example

Convert the radian value into degrees:

SELECT DEGREES(1.5);

Definition and Usage

The DEGREES() function converts a value in radians to degrees.

Note: See also the and functions.

Syntax

DEGREES(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert the radian value into degrees:

SELECT DEGREES(PI()*2);

Example

Integer division (10/5):

SELECT 10 DIV 5;

Definition and Usage

The DIV function is used for integer division (x is divided by y). An integer value is returned.

Syntax

x DIV y

Parameter Values

Parameter Description
x Required. A value that will be divided by y
y Required. The divisor

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Integer division (8/3):

SELECT 8 DIV 3;

Example

Return e raised to the power of 1:

SELECT EXP(1);

Definition and Usage

The EXP() function returns e raised to the power of the specified number.

The constant e (2.718281...), is the base of natural logarithms.

Tip: Also look at the and functions.

Syntax

EXP(number)

Parameter Values

Parameter Description
number Required. The power number

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return e raised to the power of 2:

SELECT EXP(2);

Example

Return the largest integer value that is less than or equal to 25.75:

SELECT FLOOR(25.75);

Definition and Usage

The FLOOR() function returns the largest integer value that is smaller than or equal to a number.

Note: Also look at the , , , , and functions.

Syntax

FLOOR(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the largest integer value that is greater than or equal to 25:

SELECT FLOOR(25);

Example

Return the greatest value of the list of arguments:

SELECT GREATEST(3, 12, 34, 8, 25);

Definition and Usage

The GREATEST() function returns the greatest value of the list of arguments.

Note: See also the function.

Syntax

GREATEST(arg1, arg2, arg3, ...)

Parameter Values

Parameter Description
arg1, arg2, arg3, ... Required. The list of arguments to be evaluated

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the greatest value of the list of arguments:

SELECT GREATEST("w3Schools.com", "microsoft.com", "apple.com");

Example

Return the smallest value of the list of arguments:

SELECT LEAST(3, 12, 34, 8, 25);

Definition and Usage

The LEAST() function returns the smallest value of the list of arguments.

Note: See also the function.

Syntax

LEAST(arg1, arg2, arg3, ...)

Parameter Values

Parameter Description
arg1, arg2, arg3, ... Required. The list of arguments to be evaluated

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the smallest value of the list of arguments:

SELECT LEAST("w3Schools.com", "microsoft.com", "apple.com");

Example

Return the natural logarithm of 2:

SELECT LN(2);

Definition and Usage

The LN() function returns the natural logarithm of a number.

Note: See also the and functions.

Syntax

LN(number)

Parameter Values

Parameter Description
number Required. A number. Must be greater than 0

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the natural logarithm of 1:

SELECT LN(1);

Example

Return the natural logarithm of 2:

SELECT LOG(2);

Definition and Usage

The LOG() function returns the natural logarithm of a specified number, or the logarithm of the number to the specified base.

Note: See also the and functions.

Syntax

LOG(number)

OR:

LOG(base, number)

Parameter Values

Parameter Description
number Required. A number. Must be greater than 0
base The base of number. Must be greater than 1

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the natural logarithm of 4 to a specified base (2):

SELECT LOG(2, 4);

Example

Return the base-10 logarithm of 2:

SELECT LOG10(2);

Definition and Usage

The LOG10() function returns the natural logarithm of a number to base-10.

Note: See also the function.

Syntax

LOG10(number)

Parameter Values

Parameter Description
number A number greater than 0

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the base-10 logarithm of 4.5:

SELECT LOG10(4.5);

Example

Return the base-2 logarithm of 6:

SELECT LOG2(6);

Definition and Usage

The LOG2() function returns the natural logarithm of a number to base-2.

Note: See also the function.

Syntax

LOG2(number)

Parameter Values

Parameter Description
number A number. Must be greater than 0

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the base-2 logarithm of 64:

SELECT LOG2(64);

Example

Find the price of the most expensive product in the "Products" table:

SELECT MAX(Price) AS LargestPrice FROM Products;

Definition and Usage

The MAX() function returns the maximum value in a set of values.

Note: See also the function.

Syntax

MAX(expression)

Parameter Values

Parameter Description
expression Required. A numeric value (can be a field or a formula)

Technical Details

Works in: From MySQL 4.0

Example

Find the price of the cheapest product in the "Products" table:

SELECT MIN(Price) AS SmallestPrice FROM Products;

Definition and Usage

The MIN() function returns the minimum value in a set of values.

Note: See also the function.

Syntax

MIN(expression)

Parameter Values

Parameter Description
expression Required. A numeric value (can be a field or a formula)

Technical Details

Works in: From MySQL 4.0

Example

Return the remainder of 18/4:

SELECT MOD(18, 4);

Definition and Usage

The MOD() function returns the remainder of a number divided by another number.

Syntax

MOD(x, y)

OR:

x MOD y

OR:

x % y

Parameter Values

Parameter Description
x Required. A value that will be divided by y
y Required. The divisor

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the remainder of 18/4:

SELECT 18 MOD 4;

Example

Return the remainder of 18/4:

SELECT 18 % 4;

Example

Return the value of PI:

SELECT PI();

Definition and Usage

The PI() function returns the value of PI.

Note: See also the and functions.

Syntax

PI()

Technical Details

Works in: From MySQL 4.0

Example

Return 4 raised to the second power:

SELECT POW(4, 2);

Definition and Usage

The POW() function returns the value of a number raised to the power of another number.

Note: This function is equal to the function.

Syntax

POW(x, y)

Parameter Values

Parameter Description
x Required. A number (the base)
y Required. A number (the exponent)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return 8 raised to the third power:

SELECT POW(8, 3);

Example

Return 4 raised to the second power:

SELECT POWER(4, 2);

Definition and Usage

The POWER() function returns the value of a number raised to the power of another number.

Note: This function is equal to the function.

Syntax

POWER(x, y)

Parameter Values

Parameter Description
x Required. A number (the base)
y Required. A number (the exponent)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return 8 raised to the third power:

SELECT POWER(8, 3);

Example

Convert a degree value into radians:

SELECT RADIANS(180);

Definition and Usage

The RADIANS() function converts a degree value into radians.

Note: See also the and functions.

Syntax

RADIANS(number)

Parameter Values

Parameter Description
number Required. A number in degrees

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert a degree value into radians:

SELECT RADIANS(-45);

Example

Return a random decimal number (no seed value - so it returns a completely random number >= 0 and <1):

SELECT RAND();

Definition and Usage

The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).

Syntax

RAND(seed)

Parameter Values

Parameter Description
seed Optional. If seed is specified, it returns a repeatable sequence of random numbers. If no seed is specified, it returns a completely random number

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a random decimal number (with seed value of 6):

SELECT RAND(6);

Example

Return a random decimal number >= 5 and <10:

SELECT RAND()*(10-5)+5;

Example

Return a random number >= 5 and <=10:

SELECT FLOOR(RAND()*(10-5+1)+5);

Example

Round the number to 2 decimal places:

SELECT ROUND(135.375, 2);

Definition and Usage

The ROUND() function rounds a number to a specified number of decimal places.

Note: See also the , , , and functions.

Syntax

ROUND(number, decimals)

Parameter Values

Parameter Description
number Required. The number to be rounded
decimals Optional. The number of decimal places to round number to. If omitted, it returns the integer (no decimals)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Round the number to 0 decimal places:

SELECT ROUND(345.156, 0);

Example

Round the Price column (to 1 decimal) in the "Products" table:

SELECT ProductName, Price, ROUND(Price, 1) AS RoundedPrice
FROM Products;

Example

Return the sign of a number:

SELECT SIGN(255.5);

Definition and Usage

The SIGN() function returns the sign of a number.

This function will return one of the following:

  • If number > 0, it returns 1
  • If number = 0, it returns 0
  • If number < 0, it returns -1

Syntax

SIGN(number)

Parameter Values

Parameter Description
number Required. The number to return the sign for

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the sign of a number:

SELECT SIGN(-12);

Example

Return the sine of a number:

SELECT SIN(2);

Definition and Usage

The SIN() function returns the sine of a number.

Syntax

SIN(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the sine of a number:

SELECT SIN(-1);

Example

Return the square root of a number:

SELECT SQRT(64);

Definition and Usage

The SQRT() function returns the square root of a number.

Syntax

SQRT(number)

Parameter Values

Parameter Description
number Required. A number to calculate the square root of. Must be greater than 0

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the square root of a number:

SELECT SQRT(13);

Example

Return the sum of the "Quantity" field in the "OrderDetails" table:

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;

Definition and Usage

The SUM() function calculates the sum of a set of values.

Note: NULL values are ignored.

Syntax

SUM(expression)

Parameter Values

Parameter Description
expression Required. A field or a formula

Technical Details

Works in: From MySQL 4.0

Example

Return the tangent of a number:

SELECT TAN(1.75);

Definition and Usage

The TAN() function returns the tangent of a number.

Syntax

TAN(number)

Parameter Values

Parameter Description
number Required. A numeric value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the tangent of a number:

SELECT TAN(-3);

Example

Return a number truncated to 2 decimal places:

SELECT TRUNCATE(135.375, 2);

Definition and Usage

The TRUNCATE() function truncates a number to the specified number of decimal places.

Note: See also the , , , and functions.

Syntax

TRUNCATE(number, decimals)

Parameter Values

Parameter Description
number Required. The number to be truncated
decimals Required. The number of decimal places to truncate to

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a number truncated to 0 decimal places:

SELECT TRUNCATE(345.156, 0);

Example

Add 10 days to a date and return the date:

SELECT ADDDATE("2017-06-15", INTERVAL 10 DAY);

Definition and Usage

The ADDDATE() function adds a time/date interval to a date and then returns the date.

Syntax

ADDDATE(date, INTERVAL value addunit)

OR:

ADDDATE(date, days)

Parameter Values

Parameter Description
date Required.  The date to be modified
days Required. The number of days to add to date
value Required. The value of the time/date interval to add. Both positive and negative values are allowed
addunit Required. The type of interval to add. Can be one of the following values:
  • MICROSECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR
  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • MINUTE_SECOND
  • HOUR_MICROSECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_MICROSECOND
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Add 15 minutes to a date and return the date:

SELECT ADDDATE("2017-06-15 09:34:21", INTERVAL 15 MINUTE);

Example

Subtract 3 hours to a date and return the date:

SELECT ADDDATE("2017-06-15 09:34:21", INTERVAL -3 HOUR);

Example

Subtract 2 months to a date and return the date:

SELECT ADDDATE("2017-06-15", INTERVAL -2 MONTH);

Example

Add 2 seconds to a time and return the datetime:

SELECT ADDTIME("2017-06-15 09:34:21", "2");

Definition and Usage

The ADDTIME() function adds a time interval to a time/datetime and then returns the time/datetime.

Syntax

ADDTIME(datetime, addtime)

Parameter Values

Parameter Description
datetime Required.  The time/datetime to be modified
addtime Required. The time interval to add to datetime. Both positive and negative values are allowed

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Add 5 seconds and 3 microseconds to a time and return the datetime:

SELECT ADDTIME("2017-06-15 09:34:21.000001", "5.000003");

Example

Add 2 hours, 10 minutes, 5 seconds, and 3 microseconds to a time and return the datetime:

SELECT ADDTIME("2017-06-15 09:34:21.000001", "2:10:5.000003");

Example

Add 5 days, 2 hours, 10 minutes, 5 seconds, and 3 microseconds to a time and return the datetime:

SELECT ADDTIME("2017-06-15 09:34:21.000001", "5 2:10:5.000003");

Example

Add 2 hours, 10 minutes, 5 seconds, and 3 microseconds to a time and return the time:

SELECT ADDTIME("09:34:21.000001", "2:10:5.000003");

Example

Return the current date:

SELECT CURDATE();

Definition and Usage

The CURDATE() function returns the current date.

Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric).

Note: This function equals the function.

Syntax

CURDATE()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the current date + 1:

SELECT CURDATE() + 1;

Example

Return the current date:

SELECT CURRENT_DATE();

Definition and Usage

The CURRENT_DATE() function returns the current date.

Note: The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric).

Note: This function equals the function.

Syntax

CURRENT_DATE()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the current date + 1:

SELECT CURRENT_DATE() + 1;

Example

Return current time:

SELECT CURRENT_TIME();

Definition and Usage

The CURRENT_TIME() function returns the current time.

Note: The time is returned as "HH-MM-SS" (string) or as HHMMSS.uuuuuu (numeric).

Note: This function equals the function.

Syntax

CURRENT_TIME()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return current time + 1:

SELECT CURRENT_TIME() + 1;

Example

Return the current date and time:

SELECT CURRENT_TIMESTAMP();

Definition and Usage

The CURRENT_TIMESTAMP() function returns the current date and time.

Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS.uuuuuu (numeric).

Syntax

CURRENT_TIMESTAMP()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the current date and time + 1:

SELECT CURRENT_TIMESTAMP() + 1;

Example

Return current time:

SELECT CURTIME();

Definition and Usage

The CURTIME() function returns the current time.

Note: The time is returned as "HH-MM-SS" (string) or as HHMMSS.uuuuuu (numeric).

Note: This function equals the function.

Syntax

CURTIME()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return current time + 1:

SELECT CURTIME() + 1;

Example

Extract the date part:

SELECT DATE("2017-06-15");

Definition and Usage

The DATE() function extracts the date part from a datetime expression.

Syntax

DATE(expression)

Parameter Values

Parameter Description
expression Required.  A valid date/datetime value. Returns NULL if expression is not a date or a datetime

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract the date part:

SELECT DATE("2017-06-15 09:34:21");

Example

Extract the date part (will return NULL):

SELECT DATE("The date is 2017-06-15");

Example

Extract the date part:

SELECT DATE(OrderDate) FROM Orders;

Example

Return the number of days between two date values:

SELECT DATEDIFF("2017-06-25", "2017-06-15");

Definition and Usage

The DATEDIFF() function returns the number of days between two date values.

Syntax

DATEDIFF(date1, date2)

Parameter Values

Parameter Description
date1, date2 Required. Two dates to calculate the number of days between. (date1 - date2)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the number of days between two date values:

SELECT DATEDIFF("2017-06-25 09:34:21", "2017-06-15 15:25:35");

Example

Return the number of days between two date values:

SELECT DATEDIFF("2017-01-01", "2016-12-24");

Example

Add 10 days to a date and return the date:

SELECT DATE_ADD("2017-06-15", INTERVAL 10 DAY);

Definition and Usage

The DATE_ADD() function adds a time/date interval to a date and then returns the date.

Syntax

DATE_ADD(date, INTERVAL value addunit)

Parameter Values

Parameter Description
date Required. The date to be modified
value Required. The value of the time/date interval to add. Both positive and negative values are allowed
addunit Required. The type of interval to add. Can be one of the following values:
  • MICROSECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR
  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • MINUTE_SECOND
  • HOUR_MICROSECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_MICROSECOND
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Add 15 minutes to a date and return the date:

SELECT DATE_ADD("2017-06-15 09:34:21", INTERVAL 15 MINUTE);

Example

Subtract 3 hours to a date and return the date:

SELECT DATE_ADD("2017-06-15 09:34:21", INTERVAL -3 HOUR);

Example

Subtract 2 months to a date and return the date:

SELECT DATE_ADD("2017-06-15", INTERVAL -2 MONTH);

Example

Format a date:

SELECT DATE_FORMAT("2017-06-15", "%Y");

Definition and Usage

The DATE_FORMAT() function formats a date as specified.

Syntax

DATE_FORMAT(date, format)

Parameter Values

Parameter Description
date Required. The date to be formatted
format Required. The format to use. Can be one or a combination of the following values:
Format Description
%a Abbreviated weekday name (Sun to Sat)
%b Abbreviated month name (Jan to Dec)
%c Numeric month name (0 to 12)
%D Day of the month as a numeric value, followed by suffix (1st, 2nd, 3rd, ...)
%d Day of the month as a numeric value (01 to 31)
%e Day of the month as a numeric value (0 to 31)
%f Microseconds (000000 to 999999)
%H Hour (00 to 23)
%h Hour (00 to 12)
%I Hour (00 to 12)
%i Minutes (00 to 59)
%j Day of the year (001 to 366)
%k Hour (0 to 23)
%l Hour (1 to 12)
%M Month name in full (January to December)
%m Month name as a numeric value (00 to 12)
%p AM or PM
%r Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
%S Seconds (00 to 59)
%s Seconds (00 to 59)
%T Time in 24 hour format (hh:mm:ss)
%U Week where Sunday is the first day of the week (00 to 53)
%u Week where Monday is the first day of the week (00 to 53)
%V Week where Sunday is the first day of the week (01 to 53). Used with %X
%v Week where Monday is the first day of the week (01 to 53). Used with %x
%W Weekday name in full (Sunday to Saturday)
%w Day of the week where Sunday=0 and Saturday=6
%X Year for the week where Sunday is the first day of the week. Used with %V
%x Year for the week where Monday is the first day of the week. Used with %v
%Y Year as a numeric, 4-digit value
%y Year as a numeric, 2-digit value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Format a date:

SELECT DATE_FORMAT("2017-06-15", "%M %d %Y");

Example

Format a date:

SELECT DATE_FORMAT("2017-06-15", "%W %M %e %Y");

Example

Format a date:

SELECT DATE_FORMAT(BirthDate, "%W %M %e %Y") FROM Employees;

Example

Subtract 10 days from a date and return the date:

SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);

Definition and Usage

The DATE_SUB() function subtracts a time/date interval from a date and then returns the date.

Syntax

DATE_SUB(date, INTERVAL value interval)

Parameter Values

Parameter Description
date Required. The date to be modified
value Required. The value of the time/date interval to subtract. Both positive and negative values are allowed
interval Required. The type of interval to subtract. Can be one of the following values:
  • MICROSECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR
  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • MINUTE_SECOND
  • HOUR_MICROSECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_MICROSECOND
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Subtract 15 minutes from a date and return the date:

SELECT DATE_SUB("2017-06-15 09:34:21", INTERVAL 15 MINUTE);

Example

Subtract 3 hours from a date and return the date:

SELECT DATE_SUB("2017-06-15 09:34:21", INTERVAL 3 HOUR);

Example

Add 2 months to a date and return the date:

SELECT DATE_SUB("2017-06-15", INTERVAL -2 MONTH);

Example

Return the day of the month for a date:

SELECT DAY("2017-06-15");

Definition and Usage

The DAY() function returns the day of the month for a given date (a number from 1 to 31).

Note: This function equals the function.

Syntax

DAY(date)

Parameter Values

Parameter Description
date Required. The date to extract the day from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the day of the month for a date:

SELECT DAY("2017-06-15 09:34:21");

Example

Return the day of the month for the current system date:

SELECT DAY(CURDATE());

Example

Return the weekday name for a date:

SELECT DAYNAME("2017-06-15");

Definition and Usage

The DAYNAME() function returns the weekday name for a given date.

Syntax

DAYNAME(date)

Parameter Values

Parameter Description
date Required.  The date to extract the weekday name from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the weekday name for a date:

SELECT DAYNAME("2017-06-15 09:34:21");

Example

Return the weekday name for the current system date:

SELECT DAYNAME(CURDATE());

Example

Return the day of the month for a date:

SELECT DAYOFMONTH("2017-06-15");

Definition and Usage

The DAYOFMONTH() function returns the day of the month for a given date (a number from 1 to 31).

Note: This function equals the function.

Syntax

DAYOFMONTH(date)

Parameter Values

Parameter Description
date Required. The date to extract the day from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the day of the month for a date:

SELECT DAYOFMONTH("2017-06-15 09:34:21");

Example

Return the day of the month for the current system date:

SELECT DAYOFMONTH(CURDATE());

Example

Return the weekday index for a date:

SELECT DAYOFWEEK("2017-06-15");

Definition and Usage

The DAYOFWEEK() function returns the weekday index for a given date (a number from 1 to 7).

Note: 1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday.

Syntax

DAYOFWEEK(date)

Parameter Values

Parameter Description
date Required. The date to return the weekday index from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the weekday index for a date:

SELECT DAYOFWEEK("2017-06-15 09:34:21");

Example

Return the weekday index for the current system date:

SELECT DAYOFWEEK(CURDATE());

Example

Return the day of the year for a date:

SELECT DAYOFYEAR("2017-06-15");

Definition and Usage

The DAYOFYEAR() function returns the day of the year for a given date (a number from 1 to 366).

Syntax

DAYOFYEAR(date)

Parameter Values

Parameter Description
date Required. The date to return the day of the year from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the day of the year for a date:

SELECT DAYOFYEAR("2017-01-01");

Example

Return the day of the year for the current system date:

SELECT DAYOFYEAR(CURDATE());

Example

Extract the month from a date:

SELECT EXTRACT(MONTH FROM "2017-06-15");

Definition and Usage

The EXTRACT() function extracts a part from a given date.

Syntax

EXTRACT(part FROM date)

Parameter Values

Parameter Description
part Required. The part to extract. Can be one of the following:
  • MICROSECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR
  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • MINUTE_SECOND
  • HOUR_MICROSECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_MICROSECOND
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH
date Required. The date to extract a part from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract the week from a date:

SELECT EXTRACT(WEEK FROM "2017-06-15");

Example

Extract the minute from a datetime:

SELECT EXTRACT(MINUTE FROM "2017-06-15 09:34:21");

Example

Extract the year and month from a datetime:

SELECT EXTRACT(YEAR_MONTH FROM "2017-06-15 09:34:21");

Example

Return a date from a numeric representation of the day:

SELECT FROM_DAYS(685467);

Definition and Usage

The FROM_DAYS() function returns a date from a numeric datevalue.

The FROM_DAYS() function is to be used only with dates within the Gregorian calendar.

Note: This function is the opposite of the function.

Syntax

FROM_DAYS(number)

Parameter Values

Parameter Description
number Required.  The numeric day to convert to a date

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a date from a numeric representation of the day:

SELECT FROM_DAYS(780500);

Example

Return the hour part of a datetime:

SELECT HOUR("2017-06-20 09:34:00");

Definition and Usage

The HOUR() function returns the hour part for a given date (from 0 to 838).

Syntax

HOUR(datetime)

Parameter Values

Parameter Description
datetime Required. The datetime value to extract the hour from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the hour part of a datetime: 

SELECT HOUR("838:59:59");

Example

Extract the last day of the month for the given date:

SELECT LAST_DAY("2017-06-20");

Definition and Usage

The LAST_DAY() function extracts the last day of the month for a given date.

Syntax

LAST_DAY(date)

Parameter Values

Parameter Description
date Required. The date to extract the last day of the month from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract the last day of the month for the given date:

SELECT LAST_DAY("2017-02-10 09:34:00");

Example

Return current date and time:

SELECT LOCALTIME();

Definition and Usage

The LOCALTIME() function returns the current date and time.

Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS.uuuuuu (numeric).

Syntax

LOCALTIME()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return current date and time + 1:

SELECT LOCALTIME() + 1;

Example

Return current date and time:

SELECT LOCALTIMESTAMP();

Definition and Usage

The LOCALTIMESTAMP() function returns the current date and time.

Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS.uuuuuu (numeric).

Syntax

LOCALTIMESTAMP()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return current date and time + 1:

SELECT LOCALTIMESTAMP() + 1;

Example

Create and return a date based on  a year and a number of days value:

SELECT MAKEDATE(2017, 3);

Definition and Usage

The MAKEDATE() function creates and returns a date based on a year and a number of days value.

Syntax

MAKEDATE(year, day)

Parameter Values

Parameter Description
year Required. A year (4-digits)
day Required. A number that indicates the day of the year

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Create and return a date based on  a year and a number of days value:

SELECT MAKEDATE(2017, 175);

Example

Create and return a date based on  a year and a number of days value:

SELECT MAKEDATE(2017, 100);

Example

Create and return a date based on  a year and a number of days value:

SELECT MAKEDATE(2017, 366);

Example

Create and return a time value based on an hour, minute, and second value:

SELECT MAKETIME(11, 35, 4);

Definition and Usage

The MAKETIME() function creates and returns a time based on an hour, minute, and second value.

Syntax

MAKETIME(hour, minute, second)

Parameter Values

Parameter Description
hour Required. The hour value
minute Required. The minute value
second Required. The seconds value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Create and return a time value based on an hour, minute, and second value:

SELECT MAKETIME(16, 1, 0);

Example

Create and return a time value based on an hour, minute, and second value:

SELECT MAKETIME(21, 59, 59);

Example

Create and return a time value based on an hour, minute, and second value:

SELECT MAKETIME(838, 59, 59);

Example

Return the microsecond part of a datetime:

SELECT MICROSECOND("2017-06-20 09:34:00.000023");

Definition and Usage

The MICROSECOND() function returns the microsecond part of a time/datetime (from 0 to 999999).

Syntax

MICROSECOND(datetime)

Parameter Values

Parameter Description
datetime Required. The time or datetime to extract the microsecond from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the microsecond part of a time value: 

SELECT MICROSECOND("23:59:59.000045");

Example

Return the minute part of a datetime value:

SELECT MINUTE("2017-06-20 09:34:00");

Definition and Usage

The MINUTE() function returns the minute part of a time/datetime (from 0 to 59).

Syntax

MINUTE(datetime)

Parameter Values

Parameter Description
datetime Required. The time or datetime extract the minute from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the minute part of a time value: 

SELECT MINUTE("23:59:59");

Example

Return the month part of a date:

SELECT MONTH("2017-06-15");

Definition and Usage

The MONTH() function returns the month part for a given date (a number from 1 to 12).

Syntax

MONTH(date)

Parameter Values

Parameter Description
date Required. The date or datetime to extract the month from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the month part of a date:

SELECT MONTH("2017-06-15 09:34:21");

Example

Return the month part of the current system date:

SELECT MONTH(CURDATE());

Example

Return the name of the month for a date:

SELECT MONTHNAME("2017-06-15");

Definition and Usage

The MONTHNAME() function returns the name of the month for a given date.

Syntax

MONTHNAME(date)

Parameter Values

Parameter Description
date Required. The date or datetime value to extract the month name from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the name of the month for a date:

SELECT MONTHNAME("2017-06-15 09:34:21");

Example

Return the name of the month for the current system date:

SELECT MONTHNAME(CURDATE());

Example

Return current date and time:

SELECT NOW();

Definition and Usage

The NOW() function returns the current date and time.

Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS.uuuuuu (numeric).

Syntax

NOW()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return current date and time + 1:

SELECT NOW() + 1;

Example

Add a specified number of months to a period:

SELECT PERIOD_ADD(201703, 5);

Definition and Usage

The PERIOD_ADD() function adds a specified number of months to a period.

The PERIOD_ADD() function will return the result formatted as YYYYMM.

Syntax

PERIOD_ADD(period, number)

Parameter Values

Parameter Description
period Required. A period. Format: YYMM or YYYYMM
number Required. The number of months to add to period. Both positive and negative values are allowed

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Add a specified number of months to a period:

SELECT PERIOD_ADD(201703, 15);

Example

Add a specified number of months to a period:

SELECT PERIOD_ADD(201703, -2);

Example

Return the difference between two periods:

SELECT PERIOD_DIFF(201710, 201703);

Definition and Usage

The PERIOD_DIFF() function returns the difference between two periods. The result will be in months.

Note: period1 and period2 should be in the same format.

Syntax

PERIOD_DIFF(period1, period2)

Parameter Values

Parameter Description
period1 Required. A period. Format: YYMM or YYYYMM
period2 Required. Another period. Format: YYMM or YYYYMM

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the difference between two periods:

SELECT PERIOD_DIFF(201703, 201803);

Example

Return the difference between two periods:

SELECT PERIOD_DIFF(1703, 1612);

Example

Return the quarter of the year for the date:

SELECT QUARTER("2017-06-15");

Definition and Usage

The QUARTER() function returns the quarter of the year for a given date value (a number from 1 to 4).

  • January-March returns 1
  • April-June returns 2
  • July-Sep returns 3
  • Oct-Dec returns 4

Syntax

QUARTER(date)

Parameter Values

Parameter Description
date Required. The date or datetime to extract the quarter from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the quarter of the year for the date:

SELECT QUARTER("2017-01-01 09:34:21");

Example

Return the quarter of the year for the date:

SELECT QUARTER(CURDATE());

Example

Return the seconds part of a datetime value:

SELECT SECOND("2017-06-20 09:34:00.000023");

Definition and Usage

The SECOND() function returns the seconds part of a time/datetime (from 0 to 59).

Syntax

SECOND(datetime)

Parameter Values

Parameter Description
datetime Required. The time or datetime to extract the second from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the seconds part of a time value: 

SELECT SECOND("23:59:59");

Example

Return a time value based on a specified seconds value:

SELECT SEC_TO_TIME(1);

Definition and Usage

The SEC_TO_TIME() function returns a time value (in format HH:MM:SS) based on the specified seconds.

Syntax

SEC_TO_TIME(seconds)

Parameter Values

Parameter Description
seconds Required. The number of seconds. Both positive or negative values are allowed

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a time value based on a specified seconds value: 

SELECT SEC_TO_TIME(-6897);

Example

Return a date based on a string and a format:

SELECT STR_TO_DATE("August 10 2017", "%M %d %Y");

Definition and Usage

The STR_TO_DATE() function returns a date based on a string and a format.

Syntax

STR_TO_DATE(string, format)

Parameter Values

Parameter Description
string Required. The string to be formatted to a date
format Required. The format to use. Can be one or a combination of the following values:
Format Description
%a Abbreviated weekday name (Sun to Sat)
%b Abbreviated month name (Jan to Dec)
%c Numeric month name (0 to 12)
%D Day of the month as a numeric value, followed by suffix (1st, 2nd, 3rd, ...)
%d Day of the month as a numeric value (01 to 31)
%e Day of the month as a numeric value (0 to 31)
%f Microseconds (000000 to 999999)
%H Hour (00 to 23)
%h Hour (00 to 12)
%I Hour (00 to 12)
%i Minutes (00 to 59)
%j Day of the year (001 to 366)
%k Hour (0 to 23)
%l Hour (1 to 12)
%M Month name in full (January to December)
%m Month name as a numeric value (01 to 12)
%p AM or PM
%r Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
%S Seconds (00 to 59)
%s Seconds (00 to 59)
%T Time in 24 hour format (hh:mm:ss)
%U Week where Sunday is the first day of the week (00 to 53)
%u Week where Monday is the first day of the week (00 to 53)
%V Week where Sunday is the first day of the week (01 to 53). Used with %X
%v Week where Monday is the first day of the week (01 to 53). Used with %X
%W Weekday name in full (Sunday to Saturday)
%w Day of the week where Sunday=0 and Saturday=6
%X Year for the week where Sunday is the first day of the week. Used with %V
%x Year for the week where Monday is the first day of the week. Used with %V
%Y Year as a numeric, 4-digit value
%y Year as a numeric, 2-digit value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a date based on a string and a format:

SELECT STR_TO_DATE("August,5,2017", "%M %e %Y");

Example

Return a date based on a string and a format:

SELECT STR_TO_DATE("Monday, August 14, 2017", "%W %M %e %Y");

Example

Return a date based on a string and a format:

SELECT STR_TO_DATE("2017,8,14 10,40,10", "%Y,%m,%d %h,%i,%s");

Example

Subtract 10 days from a date and return the date:

SELECT SUBDATE("2017-06-15", INTERVAL 10 DAY);

Definition and Usage

The SUBDATE() function subtracts a time/date interval from a date and then returns the date.

Syntax

SUBDATE(date, INTERVAL value unit)

OR:

SUBDATE(date, days)

Parameter Values

Parameter Description
date Required. The original date
days Required. The number of days to subtract from date
value Required. The value of the time/date interval to subtract. Both positive and negative values are allowed
unit Required. The type of interval. Can be one of the following values:
  • MICROSECOND
  • SECOND
  • MINUTE
  • HOUR
  • DAY
  • WEEK
  • MONTH
  • QUARTER
  • YEAR
  • SECOND_MICROSECOND
  • MINUTE_MICROSECOND
  • MINUTE_SECOND
  • HOUR_MICROSECOND
  • HOUR_SECOND
  • HOUR_MINUTE
  • DAY_MICROSECOND
  • DAY_SECOND
  • DAY_MINUTE
  • DAY_HOUR
  • YEAR_MONTH

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Subtract 15 minutes from a date and return the date:

SELECT SUBDATE("2017-06-15 09:34:21", INTERVAL 15 MINUTE);

Example

Subtract 3 hours from a date and return the date:

SELECT SUBDATE("2017-06-15 09:34:21", INTERVAL 3 HOUR);

Example

Add 2 months to a date and return the date:

SELECT SUBDATE("2017-06-15", INTERVAL -2 MONTH);

Example

Subtract 5.000001 seconds and return the datetime:

SELECT SUBTIME("2017-06-15 10:24:21.000004", "5.000001");

Definition and Usage

The SUBTIME() function subtracts time from a time/datetime expression and then returns the new time/datetime.

Syntax

SUBTIME(datetime, time_interval)

Parameter Values

Parameter Description
datetime Required. The time or datetime to be modified
time_interval Required. The time interval to subtract from datetime. Both positive and negative values are allowed

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Subtract 3 hours, 2 minutes, 5.000001 seconds and return the datetime:

SELECT SUBTIME("2017-06-15 10:24:21.000004", "3:2:5.000001");

Example

Subtract 5 seconds and return the time:

SELECT SUBTIME("10:24:21", "5");

Example

Subtract 3 minutes and return the time:

SELECT SUBTIME("10:24:21", "300");

Example

Add 3 hours, 2 minutes, and 5 seconds, and return the time:

SELECT SUBTIME("10:24:21", "-3:2:5");

Example

Return the current date and time:

SELECT SYSDATE();

Definition and Usage

The SYSDATE() function returns the current date and time.

Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS (numeric).

Syntax

SYSDATE()

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the current date and time + 1:

SELECT SYSDATE() + 1;

Example

Extract the time part from a time expression:

SELECT TIME("19:30:10");

Definition and Usage

The TIME() function extracts the time part from a given time/datetime.

Note: This function returns "00:00:00" if expression is not a datetime/time, or NULL if expression is NULL.

Syntax

TIME(expression)

Parameter Values

Parameter Description
expression Required. The time/datetime to extract the time from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Extract the time part from the datetime expression:

SELECT TIME("2017-08-15 19:30:10");

Example

Extract the time part from the datetime expression:

SELECT TIME("2017-08-15 19:30:10.000001");

Example

Extract the time part from NULL:

SELECT TIME(NULL);

Example

Format a time:

SELECT TIME_FORMAT("19:30:10", "%H %i %s");

Definition and Usage

The TIME_FORMAT() function formats a time by a specified format.

Syntax

TIME_FORMAT(time, format)

Parameter Values

Parameter Description
time Required. The time to be formatted
format Required. The format to use. Can be one or a combination of the following:
Format Description
%f Microseconds (000000 to 999999)
%H Hour (00 to 23)
%h Hour (00 to 12)
%I Hour (00 to 12)
%i Minutes (00 to 59)
%p AM or PM
%r Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
%S Seconds (00 to 59)
%s Seconds (00 to 59)
%T Time in 24 hour format (hh:mm:ss)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Format a time:

SELECT TIME_FORMAT("19:30:10", "%h %i %s %p");

Example

Format a time:

SELECT TIME_FORMAT("19:30:10", "%r");

Example

Format a time:

SELECT TIME_FORMAT("19:30:10", "%T");

Example

Convert a time value into seconds:

SELECT TIME_TO_SEC("19:30:10");

Definition and Usage

The TIME_TO_SEC() function converts a time value into seconds.

Syntax

TIME_TO_SEC(time)

Parameter Values

Parameter Description
time Required. The time value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert a time value into seconds:

SELECT TIME_TO_SEC("00:00:05");

Example

Convert a time value into seconds:

SELECT TIME_TO_SEC("03:30:00.999999");

Example

Convert a time value into seconds:

SELECT TIME_TO_SEC("-03:30:00");

Example

Return the difference between two time expressions:

SELECT TIMEDIFF("13:10:11", "13:10:10");

Definition and Usage

The TIMEDIFF() function returns the difference between two time/datetime expressions.

Note: time1 and time2 should be in the same format, and the calculation is time1 - time2.

Syntax

TIMEDIFF(time1, time2)

Parameter Values

Parameter Description
time1 Required. A time value
time2 Required. Another time value

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the difference between two datetime expressions:

SELECT TIMEDIFF("2017-06-25 13:10:11", "2017-06-15 13:10:10");

Example

Return a datetime value based on the arguments:

SELECT TIMESTAMP("2017-07-23",  "13:10:11");

Definition and Usage

The TIMESTAMP() function returns a datetime value based on a date or datetime value.

Note: If there are specified two arguments with this function, it first adds the second argument to the first, and then returns a datetime value.

Syntax

TIMESTAMP(expression, time)

Parameter Values

Parameter Description
expression Required. A date or datetime value
time Optional. A time value to add to expression

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a datetime value based on the arguments:

SELECT TIMESTAMP("2017-07-23");

Example

Return the number of days between the date and year 0:

SELECT TO_DAYS("2017-06-20");

Definition and Usage

The TO_DAYS() function returns the number of days between a date and year 0 (date "0000-00-00").

The TO_DAYS() function can be used only with dates within the Gregorian calendar.

Note: This function is the opposite of the function.

Syntax

TO_DAYS(date)

Parameter Values

Parameter Description
date Required. The given date

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the number of days between the date and year 0:

SELECT TO_DAYS("2017-06-20 09:34:00");

Example

Return the week number for a date:

SELECT WEEK("2017-06-15");

Definition and Usage

The WEEK() function returns the week number for a given date (a number from 0 to 53).

Syntax

WEEK(date, firstdayofweek)

Parameter Values

Parameter Description
date Required.  The date or datetime to extract the week number form
firstdayofweek

Optional. Specifies what day the week starts on. Can be one of the following:

  • 0 - First day of week is Sunday
  • 1 - First day of week is Monday and the first week of the year has more than 3 days
  • 2 - First day of week is Sunday
  • 3 - First day of week is Monday and the first week of the year has more than 3 days
  • 4 - First day of week is Sunday and the first week of the year has more than 3 days
  • 5 - First day of week is Monday
  • 6 - First day of week is Sunday and the first week of the year has more than 3 days
  • 7 - First day of week is Monday

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the week number for a date:

SELECT WEEK("2017-10-25");

Example

Return the week number for the current system date:

SELECT WEEK(CURDATE());

Example

Return the weekday number for a date:

SELECT WEEKDAY("2017-06-15");

Definition and Usage

The WEEKDAY() function returns the weekday number for a given date.

Note: 0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday, 4 = Friday, 5 = Saturday, 6 = Sunday.

Syntax

WEEKDAY(date)

Parameter Values

Parameter Description
date Required.  The date or datetime to extract the weekday number from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the weekday number for a date:

SELECT WEEKDAY("2017-01-01");

Example

Return the weekday number for the current system date:

SELECT WEEKDAY(CURDATE());

Example

Return the week number for a date:

SELECT WEEKOFYEAR("2017-06-15");

Definition and Usage

The WEEKOFYEAR() function returns the week number for a given date (a number from 1 to 53).

Note: This function assumes that the first day of the week is Monday and the first week of the year has more than 3 days.

Tip: Also look at the function.

Syntax

WEEKOFYEAR(date)

Parameter Values

Parameter Description
date Required.  The date or datetime to extract the week number from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the week number for a date:

SELECT WEEKOFYEAR("2017-01-01");

Example

Return the week number for the current system date:

SELECT WEEKOFYEAR(CURDATE());

Example

Return the year part of a date:

SELECT YEAR("2017-06-15");

Definition and Usage

The YEAR() function returns the year part for a given date (a number from 1000 to 9999).

Syntax

YEAR(date)

Parameter Values

Parameter Description
date Required.  The date/datetime to extract the year from

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the year part of a date:

SELECT YEAR("2017-06-15 09:34:21");

Example

Return the year part of the current system date:

SELECT YEAR(CURDATE());

Example

Return the year and week number for a date:

SELECT YEARWEEK("2017-06-15");

Definition and Usage

The YEARWEEK() function returns the year and week number (a number from 0 to 53) for a given date.

Syntax

YEARWEEK(date, firstdayofweek)

Parameter Values

Parameter Description
date Required.  The date or datetime value to extract the year and week number from
firstdayofweek

Optional. Specifies what day the week starts on. Can be one of the following:

  • 0 - First day of week is Sunday
  • 1 - First day of week is Monday and the first week has more than 3 days
  • 2 - First day of week is Sunday
  • 3 - First day of week is Monday and the first week has more than 3 days
  • 4 - First day of week is Sunday and the first week has more than 3 days
  • 5 - First day of week is Monday
  • 6 - First day of week is Sunday and the first week has more than 3 days
  • 7 - First day of week is Monday

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the year and week number for a date:

SELECT YEARWEEK("2017-10-25");

Example

Return the year and week number for the current system date:

SELECT YEARWEEK(CURDATE());

Example

Return a binary representation of 15:

SELECT BIN(15);

Definition and Usage

The BIN() function returns a binary representation of a number, as a string value.

Syntax

BIN(number)

Parameter Values

Parameter Description
number Required. A number

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return a binary representation of 111:

SELECT BIN(111);

Example

Return a binary representation of 8:

SELECT BIN(8);

Example

Convert a value to a binary string:

SELECT BINARY "W3Schools.com";

Definition and Usage

The BINARY function converts a value to a binary string.

This function is equivalent to using .

Syntax

BINARY value

Parameter Values

Parameter Description
value Required. The value to convert

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Here MySQL performs a character-by-character comparison of  "HELLO" and "hello" and return 1 (because on a character-by-character basis, they are equivalent):

SELECT "HELLO" = "hello";

Example

Here MySQL performs a byte-by-byte comparison of  "HELLO" and "hello" and return 0 (because on a byte-by-byte basis, they are NOT equivalent):

SELECT BINARY "HELLO" = "hello";

Example

Go through conditions and return a value when the first condition is met:

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN "The quantity is greater than 30"
    WHEN Quantity = 30 THEN "The quantity is 30"
    ELSE "The quantity is under 30"
END
FROM OrderDetails;

Definition and Usage

The CASE statement goes through conditions and return a value when the first condition is met (like an IF-THEN-ELSE statement). So, once a condition is true, it will stop reading and return the result.

If no conditions are true, it will return the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.

Syntax

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;

Parameter Values

Parameter Description
condition1, condition2, ...conditionN Required. The conditions. These are evaluated in the same order as they are listed
result1, result2, ...resultN Required. The value to return once a condition is true

Technical Details

Works in: From MySQL 4.0

More Examples

The following SQL will order the customers by City. However, if City is NULL, then order by Country:

Example

SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);

Example

Convert a value to a DATE datatype:

SELECT CAST("2017-08-29" AS DATE);

Definition and Usage

The CAST() function converts a value (of any type) into the specified datatype.

Tip: See also the function.

Syntax

CAST(value AS datatype)

Parameter Values

Parameter Description
value Required. The value to convert
datatype Required. The datatype to convert to. Can be one of the following:
Value Description
DATE Converts value to DATE. Format: "YYYY-MM-DD"
DATETIME Converts value to DATETIME. Format: "YYYY-MM-DD HH:MM:SS"
DECIMAL Converts value to DECIMAL. Use the optional M and D parameters to specify the maximum number of digits (M) and the number of digits following the decimal point (D).
TIME Converts value to TIME. Format: "HH:MM:SS"
CHAR Converts value to CHAR (a fixed length string)
NCHAR Converts value to NCHAR (like CHAR, but produces a string with the national character set)
SIGNED Converts value to SIGNED (a signed 64-bit integer)
UNSIGNED Converts value to UNSIGNED (an unsigned 64-bit integer)
BINARY Converts value to BINARY (a binary string)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert a value to a CHAR datatype:

SELECT CAST(150 AS CHAR);

Example

Convert a value to a TIME datatype:

SELECT CAST("14:06:10" AS TIME);

Example

Convert a value to a SIGNED datatype:

SELECT CAST(5-10 AS SIGNED);

Example

Return the first non-null value in a list:

SELECT COALESCE(NULL, NULL, NULL, 'W3Schools.com', NULL, 'Example.com');

Definition and Usage

The COALESCE() function returns the first non-null value in a list.

Syntax

COALESCE(val1, val2, ...., val_n)

Parameter Values

Parameter Description
val1, val2, val_n Required. The values to test

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the first non-null value in a list:

SELECT COALESCE(NULL, 1, 2, 'W3Schools.com');

Example

Return the unique connection ID for the current connection:

SELECT CONNECTION_ID();

Definition and Usage

The CONNECTION_ID() function returns the unique connection ID for the current connection.

Syntax

CONNECTION_ID()

Technical Details

Works in: From MySQL 4.0

Example

Convert a number from numeric base system 10 to numeric base system 2:

SELECT CONV(15, 10, 2);

Definition and Usage

The CONV() function converts a number from one numeric base system to another, and returns the result as a string value.

Note: This function returns NULL if any of the parameters are NULL.

Tip: Also look at the function.

Syntax

CONV(number, from_base, to_base)

Parameter Values

Parameter Description
number Required. A number
from_base The numeric base system of number (a number between 2 and 36)
to_base The numeric base system to convert to (a number between 2 and 36 or -2 and -36)

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert a number from numeric base system 2 to numeric base system 10:

SELECT CONV(1111, 2, 10);

Example

Convert a number from numeric base system 10 to numeric base system 16:

SELECT CONV(88, 10, 16);

Example

Convert a value to a DATE datatype:

SELECT CONVERT("2017-08-29", DATE);

Definition and Usage

The CONVERT() function converts a value into the specified datatype or character set.

Tip: Also look at the function.

Syntax

CONVERT(value, type)

OR:

CONVERT(value USING charset)

Parameter Values

Parameter Description
value Required. The value to convert
type Required. The datatype to convert to. Can be one of the following:
Value Description
DATE Converts value to DATE. Format: "YYYY-MM-DD"
DATETIME Converts value to DATETIME. Format: "YYYY-MM-DD HH:MM:SS"
DECIMAL Converts value to DECIMAL. Use the optional M and D parameters to specify the maximum number of digits (M) and the number of digits following the decimal point (D).
TIME Converts value to TIME. Format: "HH:MM:SS"
CHAR Converts value to CHAR (a fixed length string)
NCHAR Converts value to NCHAR (like CHAR, but produces a string with the national character set)
SIGNED Converts value to SIGNED (a signed 64-bit integer)
UNSIGNED Converts value to UNSIGNED (an unsigned 64-bit integer)
BINARY Converts value to BINARY (a binary string)
charset Required. The character set to convert to

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Convert a value to a CHAR datatype:

SELECT CONVERT(150, CHAR);

Example

Convert a value to a TIME datatype:

SELECT CONVERT("14:06:10", TIME);

Example

Convert a value to LATIN1 character set:

SELECT CONVERT("W3Schools.com" USING latin1);

Example

Return the user name and host name for the MySQL account:

SELECT CURRENT_USER();

Definition and Usage

The CURRENT_USER() function returns the user name and host name for the MySQL account that the server used to authenticate the current client.

The result is returned as a string in the UTF8 character set.

Tip: See also the function.

Syntax

CURRENT_USER()

Technical Details

Works in: From MySQL 4.0

Example

Return the name of the current (default) database:

SELECT DATABASE();

Definition and Usage

The DATABASE() function returns the name of the current database.

If there is no current database, this function returns NULL or "".

Syntax

DATABASE()

Technical Details

Works in: From MySQL 4.0

Example

Return "YES" if the condition is TRUE, or "NO" if the condition is FALSE:

SELECT IF(500<1000, "YES", "NO");

Definition and Usage

The IF() function returns a value if a condition is TRUE, or another value if a condition is FALSE.

Syntax

IF(condition, value_if_true, value_if_false)

Parameter Values

Parameter Description
condition Required. The value to test
value_if_true Required. The value to return if condition is TRUE
value_if_false Required. The value to return if condition is FALSE

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return 5 if the condition is TRUE, or 10 if the condition is FALSE:

SELECT IF(500<1000, 5, 10);

Example

Test whether two strings are the same and return "YES" if they are, or "NO" if not:

SELECT IF(STRCMP("hello","bye") = 0, "YES", "NO");

Example

Return "MORE" if the condition is TRUE, or "LESS" if the condition is FALSE:

SELECT OrderID, Quantity, IF(Quantity>10, "MORE", "LESS")
FROM OrderDetails;

Example

Return the specified value IF the expression is NULL, otherwise return the expression:

SELECT IFNULL(NULL, "W3Schools.com");

Definition and Usage

The IFNULL() function returns a specified value if the expression is NULL.

If the expression is NOT NULL, this function returns the expression.

Syntax

IFNULL(expression, alt_value)

Parameter Values

Parameter Description
expression Required. The expression to test whether is NULL
alt_value Required. The value to return if expression is NULL

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Return the specified value IF the expression is NULL, otherwise return the expression:

SELECT IFNULL("Hello", "W3Schools.com");

Example

Return the specified value IF the expression is NULL, otherwise return the expression:

SELECT IFNULL(NULL, 500);

Example

Test whether an expression is NULL:

SELECT ISNULL(NULL);

Definition and Usage

The ISNULL() function returns 1 or 0 depending on whether an expression is NULL.

If expression is NULL, this function returns 1. Otherwise, it returns 0.

Syntax

ISNULL(expression)

Parameter Values

Parameter Description
expression Required. The value to test

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Test whether an expression is NULL:

SELECT ISNULL("");

Example

Test whether an expression is NULL:

SELECT ISNULL(350);

Example

Test whether an expression is NULL:

SELECT ISNULL("Hello world!");

Example

Return the AUTO_INCREMENT id of the last row that has been inserted or updated in a table:

SELECT LAST_INSERT_ID();

Definition and Usage

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

Syntax

LAST_INSERT_ID(expression)

Parameter Values

Parameter Description
expression Optional. An expression

Technical Details

Works in: From MySQL 4.0

Example

Compare two expressions:

SELECT NULLIF(25, 25);

Definition and Usage

The NULLIF() function compares two expressions and returns NULL if they are equal. Otherwise, the first expression is returned.

Syntax

NULLIF(expr1, expr2)

Parameter Values

Parameter Description
expr1, expr2 Required. The two expressions to be compared

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Compare two expressions:

SELECT NULLIF(25, "Hello");

Example

Compare two expressions:

SELECT NULLIF("Hello", "world");

Example

Compare two expressions:

SELECT NULLIF("2017-08-25", "2017-08-25");

Example

Return the current user name and host name for the MySQL connection:

SELECT SESSION_USER();

Definition and Usage

The SESSION_USER() function returns the current user name and host name for the MySQL connection.

Note: This function is equal to the and the function.

Syntax

SESSION_USER()

Technical Details

Works in: From MySQL 4.0

Example

Return the current user name and host name for the MySQL connection:

SELECT SYSTEM_USER();

Definition and Usage

The SYSTEM_USER() function returns the current user name and host name for the MySQL connection.

Note: This function is equal to the function and the function.

Syntax

SYSTEM_USER()

Technical Details

Works in: From MySQL 4.0

Example

Return the current user name and host name for the MySQL connection:

SELECT USER();

Definition and Usage

The USER() function returns the current user name and host name for the MySQL connection.

Note: This function is equal to the function and the function.

Tip: Also look at the function.

Syntax

USER()

Technical Details

Works in: From MySQL 4.0

Example

Return the current version of the MySQL database:

SELECT VERSION();

Definition and Usage

The VERSION() function returns the current version of the MySQL database, as a string.

Syntax

VERSION()

Technical Details

Works in: From MySQL 4.0

MySQL Examples


MySQL SELECT


MySQL WHERE


MySQL AND, OR and NOT


MySQL ORDER BY



MySQL NULL Values


MySQL LIMIT


MySQL MIN() and MAX()


MySQL COUNT(), AVG() and SUM()


MySQL LIKE


MySQL Wildcards


MySQL IN


MySQL BETWEEN


MySQL Aliases


MySQL Joins


MySQL UNION


MySQL GROUP BY


MySQL HAVING


MySQL EXISTS


MySQL ANY and ALL


MySQL CASE


MySQL Comments


MySQL Database

MySQL Database tutorials can be found here:



MySQL Online Editor (Compiler)


MySQL Editor

With our online MySQL editor, you can edit SQL statements, and view the result in your browser.


Example

SELECT * FROM Customers;
ID Company Contact Country
1 Alfreds Futterkiste Maria Anders Germany
2 Centro comercial Moctezuma Francisco Chang Mexico
3 Ernst Handel Roland Mendel Austria

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


Publish Your Code

If you want to create your own website, or web applications with a SQL Database, check out .

is a website-building tool that enables you to create and share your website.

In addition to a server, you get a SQL Database where you can store and access your data.

It's easy to use and doesn't require any setup.

The code editor is packed with features to help you achieve more:

  • Templates: Start from scratch or use a template
  • Cloud-based: no installations required. You only need your browser
  • Terminal & Log: debug and troubleshoot your code easily
  • File Navigator: switch between files inside the code editor
  • And much more!

Learn Faster

Practice is key to mastering coding, and the best way to put your SQL knowledge into practice is by getting practical with code.

Use to build, test and deploy code.

The code editor lets you write and practice different types of computer languages.

New languages are added all the time:

Languages

If you don't know SQL, we suggest that you read our from scratch.


Easy Package Management

Get an overview of your packages and easily add or delete frameworks and libraries. Then, with just one click, you can make changes to your packages without manual installation.


Build Powerful Websites

You can use the code editor in to build frontend or full-stack websites from scratch.

Or you can use the 60+ templates available and save time:

Photographer website template
Blog website template
Webshop template
Tutor website template

Create your Spaces account today and explore them all!


Share Your Website With The World

Host and publish your websites in no time with .

W3Schools subdomain and SSL certificate are included for free with . An SSL certificate makes your website safe and secure. It also helps people trust your website and makes it easier to find it online.

Want a custom domain for your website?

You can buy a domain or transfer an existing one and connect it to your space.


How Does It Work?

Get started in a few clicks with .



MySQL Quiz


You can test your MySQL skills with W3Schools' Quiz.


The Test

The test contains 25 questions and there is no time limit.

The test is not official, it's just a nice way to see how much you know, or don't know, about MySQL and SQL.

Count Your Score

You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 25 points.

Start the Quiz

Good luck!

If you don't know MySQL, we suggest that you read our from scratch.


MySQL Exercises


You can test your MySQL skills with W3Schools' Exercises.


Exercises

We have gathered a variety of MySQL exercises (with answers) for each MySQL Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start MySQL Exercises

Good luck!

If you don't know MySQL, we suggest that you read our from scratch.


W3Schools MySQL Certificate


w3schools CERTIFIED . 2023   

W3Schools offers an Online Certification Program.

The perfect solution for busy professionals who need to balance work, family, and career building.

More than 50 000 certificates already issued!


w3schools CERTIFIED . 2023

W3Schools offers an Online Certification Program.

The perfect solution for busy professionals who need to balance work, family, and career building.

More than 50 000 certificates already issued!

Document your skills
Improve your career
Study at your own pace
Save time and money
Known brand
Trusted by top companies

Who Should Consider Getting Certified?

Any student or professional within the digital industry.

Certifications are valuable assets to gain trust and demonstrate knowledge to your clients, current or future employers on a ever increasing competitive market.

W3Schools is Trusted by Top Companies

W3Schools has over two decades of experience with teaching coding online.

Our certificates are recognized and valued by companies looking to employ skilled developers.

Save Time and Money

Show the world your coding skills by getting a certification.

The prices is a small fraction compared to the price of traditional education.

Document and validate your competence by getting certified!

Exam overview

Fee: 95 USD

Number of questions: 70

Requirement to pass: 75% correct answers

Time limit: 70 minutes

Number of attempts to pass: Two

Exam deadline: None

Certification Expiration: None

Format: Online, multiple choice


Advance Faster in Your Career

Getting a certificate proves your commitment to upgrading your skills.

The certificate can be added as credentials to your CV, Resume, LinkedIn profile, and so on.

It gives you the credibility needed for more responsibilities, larger projects, and a higher salary.

Knowledge is power, especially in the current job market.

Documentation of your skills enables you to advance your career or helps you to start a new one.


How Does It Work?

  • Study for free at W3Schools.com
  • Study at your own speed
  • Test your skills with W3Schools online quizzes
  • Apply for your certificate by paying an exam fee
  • Take your exam online, at any time, and from any location

Get Your Certificate and Share It With The World

Example certificate:

Each certificate gets a unique link that can be shared with others.

Validate your certification with the link or QR code.

Check how it looks like in this .

Share your certificate on LinkedIn in the Certifications section in just one click!


Document Your Skills

Getting a certificate proves your commitment to upgrade your skills, gives you the credibility needed for more responsibilities, larger projects, and a higher salary.



Looking to add multiple users?

Are you an educator, manager or business owner looking for courses or certifications?

We are working with schools, companies and organizations from all over the world.




Login
ADS CODE