SlideShare a Scribd company logo
Introduction to SQL<br />SQL is a standard language for accessing and manipulating databases.<br />What is SQL?<br />SQL stands for Structured Query Language<br />SQL lets you access and manipulate databases<br />SQL is an ANSI (American National Standards Institute) standard<br />What Can SQL do?<br />SQL can execute queries against a database<br />SQL can retrieve data from a database<br />SQL can insert records in a database<br />SQL can update records in a database<br />SQL can delete records from a database<br />SQL can create new databases<br />SQL can create new tables in a database<br />SQL can create stored procedures in a database<br />SQL can create views in a database<br />SQL can set permissions on tables, procedures, and views<br />SQL is a Standard - BUT....<br />Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language.<br />However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.<br />Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!<br />Using SQL in Your Web Site<br />To build a web site that shows some data from a database, you will need the following:<br />An RDBMS database program (i.e. MS Access, SQL Server, MySQL)<br />A server-side scripting language, like PHP or ASP<br />SQL<br />HTML / CSS<br />RDBMS<br />RDBMS stands for Relational Database Management System.<br />RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.<br />The data in RDBMS is stored in database objects called tables.<br />A table is a collection of related data entries and it consists of columns and rows.<br />SQL Syntax<br />« PreviousNext Chapter »<br />Database Tables<br />A database most often contains one or more tables. Each table is identified by a name (e.g. \"
Customers\"
 or \"
Orders\"
). Tables contain records (rows) with data.<br />Below is an example of a table called \"
Persons\"
:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The table above contains three records (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City).<br />SQL Statements<br />Most of the actions you need to perform on a database are done with SQL statements.<br />The following SQL statement will select all the records in the \"
Persons\"
 table:<br />SELECT * FROM Persons<br />In this tutorial we will teach you all about the different SQL statements.<br />Keep in Mind That...<br />SQL is not case sensitive<br />Semicolon after SQL Statements?<br />Some database systems require a semicolon at the end of each SQL statement.<br />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.<br />We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.<br />SQL DML and DDL<br />SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).<br />The query and update commands form the DML part of SQL:<br />SELECT - extracts data from a database<br />UPDATE - updates data in a database<br />DELETE - deletes data from a database<br />INSERT INTO - inserts new data into a database<br />The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are:<br />CREATE DATABASE - creates a new database<br />ALTER DATABASE - modifies a database<br />CREATE TABLE - creates a new table<br />ALTER TABLE - modifies a table<br />DROP TABLE - deletes a table<br />CREATE INDEX - creates an index (search key)<br />DROP INDEX - deletes an index <br />« PreviousNext Chapter »<br />SQL SELECT Statement<br />« PreviousNext Chapter »<br />This chapter will explain the SELECT and the SELECT * statements.<br />The SQL SELECT Statement<br />The SELECT statement is used to select data from a database.<br />The result is stored in a result table, called the result-set.<br />SQL SELECT Syntax<br />SELECT column_name(s)FROM table_name<br />and<br />SELECT * FROM table_name<br />Note: SQL is not case sensitive. SELECT is the same as select.<br />An SQL SELECT Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the content of the columns named \"
LastName\"
 and \"
FirstName\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT LastName,FirstName FROM Persons<br />The result-set will look like this:<br />LastNameFirstNameHansenOlaSvendsonTovePettersenKari<br />SELECT * Example<br />Now we want to select all the columns from the \"
Persons\"
 table.<br />We use the following SELECT statement: <br />SELECT * FROM Persons<br />Tip: The asterisk (*) is a quick way of selecting all columns!<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Navigation in a Result-set<br />Most database software systems allow navigation in the result-set with programming functions, like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.<br />Programming functions like these are not a part of this tutorial. To learn about accessing data with function calls, please visit our ADO tutorial or our PHP tutorial.<br />« PreviousNext Chapter »<br />SQL SELECT DISTINCT Statement<br />« PreviousNext Chapter »<br />This chapter will explain the SELECT DISTINCT statement.<br />The SQL SELECT DISTINCT Statement<br />In a table, some of the columns may contain duplicate values. This is not a problem; however, sometimes you will want to list only the different (distinct) values in a table.<br />The DISTINCT keyword can be used to return only distinct (different) values.<br />SQL SELECT DISTINCT Syntax<br />SELECT DISTINCT column_name(s)FROM table_name<br />SELECT DISTINCT Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select only the distinct values from the column named \"
City\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT DISTINCT City FROM Persons<br />The result-set will look like this:<br />CitySandnesStavanger<br />« PreviousNext Chapter »<br />SQL WHERE Clause<br />« PreviousNext Chapter »<br />The WHERE clause is used to filter records.<br />The WHERE Clause <br />The WHERE clause is used to extract only those records that fulfill a specified criterion.<br />SQL WHERE Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_name operator value<br />WHERE Clause Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select only the persons living in the city \"
Sandnes\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City='Sandnes'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Quotes Around Text Fields<br />SQL uses single quotes around text values (most database systems will also accept double quotes).<br />Although, numeric values should not be enclosed in quotes.<br />For text values:<br />This is correct:SELECT * FROM Persons WHERE FirstName='Tove'This is wrong:SELECT * FROM Persons WHERE FirstName=Tove<br />For numeric values:<br />This is correct:SELECT * FROM Persons WHERE Year=1965This is wrong:SELECT * FROM Persons WHERE Year='1965'<br />Operators Allowed in the WHERE Clause<br />With the WHERE clause, the following operators can be used:<br />OperatorDescription=Equal<>Not equal>Greater than<Less than>=Greater than or equal<=Less than or equalBETWEENBetween an inclusive rangeLIKESearch for a patternINIf you know the exact value you want to return for at least one of the columns<br />Note: In some versions of SQL the <> operator may be written as !=<br />« PreviousNext Chapter »<br />SQL AND & OR Operators<br />« PreviousNext Chapter »<br />The AND & OR operators are used to filter records based on more than one condition.<br />The AND & OR Operators<br />The AND operator displays a record if both the first condition and the second condition is true.<br />The OR operator displays a record if either the first condition or the second condition is true.<br />AND Operator Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select only the persons with the first name equal to \"
Tove\"
 AND the last name equal to \"
Svendson\"
:<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE FirstName='Tove'AND LastName='Svendson'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes<br />OR Operator Example<br />Now we want to select only the persons with the first name equal to \"
Tove\"
 OR the first name equal to \"
Ola\"
:<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE FirstName='Tove'OR FirstName='Ola'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Combining AND & OR<br />You can also combine AND and OR (use parenthesis to form complex expressions).<br />Now we want to select only the persons with the last name equal to \"
Svendson\"
 AND the first name equal to \"
Tove\"
 OR to \"
Ola\"
:<br />We use the following SELECT statement:<br />SELECT * FROM Persons WHERELastName='Svendson'AND (FirstName='Tove' OR FirstName='Ola')<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes<br />« PreviousNext Chapter »<br />SQL ORDER BY Keyword<br />« PreviousNext Chapter »<br />The ORDER BY keyword is used to sort the result-set.<br />The ORDER BY Keyword<br />The ORDER BY keyword is used to sort the result-set by a specified column.<br />The ORDER BY keyword sort the records in ascending order by default.<br />If you want to sort the records in a descending order, you can use the DESC keyword.<br />SQL ORDER BY Syntax<br />SELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESC<br />ORDER BY Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23Stavanger<br />Now we want to select all the persons from the table above, however, we want to sort the persons by their last name.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsORDER BY LastName<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes4NilsenTomVingvn 23Stavanger3PettersenKariStorgt 20Stavanger2SvendsonToveBorgvn 23Sandnes<br />ORDER BY DESC Example<br />Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsORDER BY LastName DESC<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23Stavanger1HansenOlaTimoteivn 10Sandnes<br />« PreviousNext Chapter »<br />Your browser does not support inline frames or is currently configured not to display inline frames. <br />SQL INSERT INTO Statement<br />« PreviousNext Chapter »<br />The INSERT INTO statement is used to insert new records in a table.<br />The INSERT INTO Statement<br />The INSERT INTO statement is used to insert a new row in a table.<br />SQL INSERT INTO Syntax<br />It is possible to write the INSERT INTO statement in two forms. <br />The first form doesn't specify the column names where the data will be inserted, only their values:<br />INSERT INTO table_nameVALUES (value1, value2, value3,...)<br />The second form specifies both the column names and the values to be inserted:<br />INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)<br />SQL INSERT INTO Example<br />We have the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to insert a new row in the \"
Persons\"
 table.<br />We use the following SQL statement:<br />INSERT INTO PersonsVALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')<br />The \"
Persons\"
 table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger<br />Insert Data Only in Specified Columns<br />It is also possible to only add data in specific columns.<br />The following SQL statement will add a new row, but only add data in the \"
P_Id\"
, \"
LastName\"
 and the \"
FirstName\"
 columns:<br />INSERT INTO Persons (P_Id, LastName, FirstName)VALUES (5, 'Tjessem', 'Jakob')<br />The \"
Persons\"
 table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakob  <br />« PreviousNext Chapter »<br />SQL UPDATE Statement<br />« PreviousNext Chapter »<br />The UPDATE statement is used to update records in a table.<br />The UPDATE Statement<br />The UPDATE statement is used to update existing records in a table.<br />SQL UPDATE Syntax<br />UPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value<br />Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!<br />SQL UPDATE Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakob  <br />Now we want to update the person \"
Tjessem, Jakob\"
 in the \"
Persons\"
 table.<br />We use the following SQL statement:<br />UPDATE PersonsSET Address='Nissestien 67', City='Sandnes'WHERE LastName='Tjessem' AND FirstName='Jakob'<br />The \"
Persons\"
 table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakobNissestien 67Sandnes<br />SQL UPDATE Warning<br />Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:<br />UPDATE PersonsSET Address='Nissestien 67', City='Sandnes'<br />The \"
Persons\"
 table would have looked like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaNissestien 67Sandnes2SvendsonToveNissestien 67Sandnes3PettersenKariNissestien 67Sandnes4NilsenJohanNissestien 67Sandnes5TjessemJakobNissestien 67Sandnes<br />« PreviousNext Chapter »<br />SQL DELETE Statement<br />« PreviousNext Chapter »<br />The DELETE statement is used to delete records in a table.<br />The DELETE Statement<br />The DELETE statement is used to delete rows in a table.<br />SQL DELETE Syntax<br />DELETE FROM table_nameWHERE some_column=some_value<br />Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!<br />SQL DELETE Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakobNissestien 67Sandnes<br />Now we want to delete the person \"
Tjessem, Jakob\"
 in the \"
Persons\"
 table.<br />We use the following SQL statement:<br />DELETE FROM PersonsWHERE LastName='Tjessem' AND FirstName='Jakob'<br />The \"
Persons\"
 table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger<br />Delete All Rows<br />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:<br />DELETE FROM table_nameorDELETE * FROM table_name<br />Note: Be very careful when deleting records. You cannot undo this statement!<br />« PreviousNext Chapter »<br />SQL Try It<br />« PreviousNext Chapter »<br />Test your SQL Skills<br />On this page you can test your SQL skills.<br />We will use the Customers table in the Northwind database:<br />CompanyNameContactNameAddressCityAlfreds Futterkiste Maria Anders Obere Str. 57 Berlin Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. Ernst Handel Roland Mendel Kirchgasse 6 Graz FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona Island Trading Helen Bennett Garden House Crowther Way Cowes Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo North/South Simon Crowther South House 300 Queensbridge London Paris spécialités Marie Bertrand 265, boulevard Charonne Paris Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque Simons bistro Jytte Petersen Vinbæltet 34 København The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland Vaffeljernet Palle Ibsen Smagsløget 45 Århus Wolski Zajazd Zbyszek Piestrzeniewicz ul. Filtrowa 68 Warszawa <br />To preserve space, the table above is a subset of the Customers table used in the example below.<br />Try it Yourself<br />To see how SQL works, you can copy the SQL statements below and paste them into the textarea, or you can make your own SQL statements.<br />SELECT * FROM customers<br />SELECT CompanyName, ContactName FROM customers<br />SELECT * FROM customers WHERE companyname LIKE 'a%'<br />SELECT CompanyName, ContactNameFROM customersWHERE CompanyName > 'a'<br />When using SQL on text data, \"
alfred\"
 is greater than \"
a\"
 (like in a dictionary).<br />SELECT CompanyName, ContactNameFROM customersWHERE CompanyName > 'g'AND ContactName > 'g'<br />Top of Form<br />Bottom of Form<br />« PreviousNext Chapter »<br />SQL TOP Clause« PreviousNext Chapter »The TOP ClauseThe TOP clause is used to specify the number of records to return.The TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance.Note: Not all database systems support the TOP clause.SQL Server SyntaxSELECT TOP number|percent column_name(s)FROM table_nameSQL SELECT TOP Equivalent in MySQL and OracleMySQL SyntaxSELECT column_name(s)FROM table_nameLIMIT numberExampleSELECT *FROM PersonsLIMIT 5Oracle SyntaxSELECT column_name(s)FROM table_nameWHERE ROWNUM <= numberExampleSELECT *FROM PersonsWHERE ROWNUM <=5SQL TOP ExampleThe \"
Persons\"
 table:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23StavangerNow we want to select only the two first records in the table above.We use the following SELECT statement:SELECT TOP 2 * FROM PersonsThe result-set will look like this:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23SandnesSQL TOP PERCENT ExampleThe \"
Persons\"
 table:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23StavangerNow we want to select only 50% of the records in the table above.We use the following SELECT statement:SELECT TOP 50 PERCENT * FROM PersonsThe result-set will look like this:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes« PreviousNext Chapter »<br />SQL LIKE Operator<br />« PreviousNext Chapter »<br />The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.<br />The LIKE Operator<br />The LIKE operator is used to search for a specified pattern in a column.<br />SQL LIKE Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern<br />LIKE Operator Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the persons living in a city that starts with \"
s\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE 's%'<br />The \"
%\"
 sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Next, we want to select the persons living in a city that ends with an \"
s\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE '%s'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Next, we want to select the persons living in a city that contains the pattern \"
tav\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE '%tav%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity3PettersenKariStorgt 20Stavanger<br />It is also possible to select the persons living in a city that NOT contains the pattern \"
tav\"
 from the \"
Persons\"
 table, by using the NOT keyword.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City NOT LIKE '%tav%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />« PreviousNext Chapter »<br />SQL Wildcards<br />« PreviousNext Chapter »<br />SQL wildcards can be used when searching for data in a database.<br />SQL Wildcards <br />SQL wildcards can substitute for one or more characters when searching for data in a database.<br />SQL wildcards must be used with the SQL LIKE operator.<br />With SQL, the following wildcards can be used:<br />WildcardDescription%A substitute for zero or more characters _A substitute for exactly one character[charlist]Any single character in charlist[^charlist] or[!charlist]Any single character not in charlist<br />SQL Wildcard Examples<br />We have the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Using the % Wildcard<br />Now we want to select the persons living in a city that starts with \"
sa\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE 'sa%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Next, we want to select the persons living in a city that contains the pattern \"
nes\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE '%nes%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Using the _ Wildcard<br />Now we want to select the persons with a first name that starts with any character, followed by \"
la\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE FirstName LIKE '_la'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes<br />Next, we want to select the persons with a last name that starts with \"
S\"
, followed by any character, followed by \"
end\"
, followed by any character, followed by \"
on\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName LIKE 'S_end_on'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes<br />Using the [charlist] Wildcard<br />Now we want to select the persons with a last name that starts with \"
b\"
 or \"
s\"
 or \"
p\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName LIKE '[bsp]%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Next, we want to select the persons with a last name that do not start with \"
b\"
 or \"
s\"
 or \"
p\"
 from the \"
Persons\"
 table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName LIKE '[!bsp]%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes<br />« PreviousNext Chapter »<br />SQL IN Operator<br />« PreviousNext Chapter »<br />The IN Operator<br />The IN operator allows you to specify multiple values in a WHERE clause.<br />SQL IN Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_name IN (value1,value2,...)<br />IN Operator Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the persons with a last name equal to \"
Hansen\"
 or \"
Pettersen\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName IN ('Hansen','Pettersen')<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes3PettersenKariStorgt 20Stavanger<br />« PreviousNext Chapter »<br />SQL BETWEEN Operator<br />« PreviousNext Chapter »<br />The BETWEEN operator is used in a WHERE clause to select a range of data between two values.<br />The BETWEEN Operator<br />The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.<br />SQL BETWEEN Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_nameBETWEEN value1 AND value2<br />BETWEEN Operator Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the persons with a last name alphabetically between \"
Hansen\"
 and \"
Pettersen\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastNameBETWEEN 'Hansen' AND 'Pettersen'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes<br />Note: The BETWEEN operator is treated differently in different databases.<br />In some databases, persons with the LastName of \"
Hansen\"
 or \"
Pettersen\"
 will not be listed, because the BETWEEN operator only selects fields that are between and excluding the test values).<br />In other databases, persons with the LastName of \"
Hansen\"
 or \"
Pettersen\"
 will be listed, because the BETWEEN operator selects fields that are between and including the test values).<br />And in other databases, persons with the LastName of \"
Hansen\"
 will be listed, but \"
Pettersen\"
 will not be listed (like the example above), because the BETWEEN operator selects fields between the test values, including the first test value and excluding the last test value.<br />Therefore: Check how your database treats the BETWEEN operator.<br />Example 2<br />To display the persons outside the range in the previous example, use NOT BETWEEN:<br />SELECT * FROM PersonsWHERE LastNameNOT BETWEEN 'Hansen' AND 'Pettersen'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />« PreviousNext Chapter »<br />SQL Alias<br />« PreviousNext Chapter »<br />With SQL, an alias name can be given to a table or to a column.<br />SQL Alias<br />You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.<br />An alias name could be anything, but usually it is short.<br />SQL Alias Syntax for Tables<br />SELECT column_name(s)FROM table_nameAS alias_name<br />SQL Alias Syntax for Columns<br />SELECT column_name AS alias_nameFROM table_name<br />Alias Example<br />Assume we have a table called \"
Persons\"
 and another table called \"
Product_Orders\"
. We will give the table aliases of \"
p\"
 and \"
po\"
 respectively.<br />Now we want to list all the orders that \"
Ola Hansen\"
 is responsible for.<br />We use the following SELECT statement:<br />SELECT po.OrderID, p.LastName, p.FirstNameFROM Persons AS p,Product_Orders AS poWHERE p.LastName='Hansen' AND p.FirstName='Ola'<br />The same SELECT statement without aliases:<br />SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstNameFROM Persons,Product_OrdersWHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'<br />As you'll see from the two SELECT statements above; aliases can make queries easier to both write and to read.<br />« PreviousNext Chapter »<br />SQL Joins<br />« PreviousNext Chapter »<br />SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.<br />SQL JOIN<br />The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.<br />Tables in a database are often related to each other with keys.<br />A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.<br />Look at the \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Note that the \"
P_Id\"
 column is the primary key in the \"
Persons\"
 table. This means that no two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.<br />Next, we have the \"
Orders\"
 table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Note that the \"
O_Id\"
 column is the primary key in the \"
Orders\"
 table and that the \"
P_Id\"
 column refers to the persons in the \"
Persons\"
 table without using their names.<br />Notice that the relationship between the two tables above is the \"
P_Id\"
 column.<br />Different SQL JOINs<br />Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.<br />JOIN: Return rows when there is at least one match in both tables<br />LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table<br />RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table<br />FULL JOIN: Return rows when there is a match in one of the tables<br />« PreviousNext Chapter »<br />SQL INNER JOIN Keyword<br />« PreviousNext Chapter »<br />SQL INNER JOIN Keyword<br />The INNER JOIN keyword return rows when there is at least one match in both tables.<br />SQL INNER JOIN Syntax<br />SELECT column_name(s)FROM table_name1INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />PS: INNER JOIN is the same as JOIN.<br />SQL INNER JOIN Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \"
Orders\"
 table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the persons with any orders.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678<br />The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in \"
Persons\"
 that do not have matches in \"
Orders\"
, those rows will NOT be listed.<br />« PreviousNext Chapter »<br />SQL LEFT JOIN Keyword<br />« PreviousNext Chapter »<br />SQL LEFT JOIN Keyword<br />The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).<br />SQL LEFT JOIN Syntax<br />SELECT column_name(s)FROM table_name1LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.<br />SQL LEFT JOIN Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \"
Orders\"
 table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the persons and their orders - if any, from the tables above.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsLEFT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678SvendsonTove <br />The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in the right table (Orders).<br />« Previous<br />SQL RIGHT JOIN Keyword<br />« PreviousNext Chapter »<br />SQL RIGHT JOIN Keyword<br />The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).<br />SQL RIGHT JOIN Syntax<br />SELECT column_name(s)FROM table_name1RIGHT JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.<br />SQL RIGHT JOIN Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \"
Orders\"
 table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the orders with containing persons - if any, from the tables above.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsRIGHT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678  34764<br />The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Persons).<br />« PreviousNext Chapter »<br />SQL FULL JOIN Keyword<br />« PreviousNext Chapter »<br />SQL FULL JOIN Keyword<br />The FULL JOIN keyword return rows when there is a match in one of the tables.<br />SQL FULL JOIN Syntax<br />SELECT column_name(s)FROM table_name1FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />SQL FULL JOIN Example<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \"
Orders\"
 table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the persons and their orders, and all the orders with their persons.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsFULL JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678SvendsonTove   34764<br />The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are rows in \"
Persons\"
 that do not have matches in \"
Orders\"
, or if there are rows in \"
Orders\"
 that do not have matches in \"
Persons\"
, those rows will be listed as well.<br />« PreviousNext Chapter »<br />SQL UNION Operator<br />« PreviousNext Chapter »<br />The SQL UNION operator combines two or more SELECT statements.<br />The SQL UNION Operator<br />The UNION operator is used to combine the result-set of two or more SELECT statements.<br />Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.<br />SQL UNION Syntax<br />SELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2<br />Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.<br />SQL UNION ALL Syntax<br />SELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2<br />PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.<br />SQL UNION Example<br />Look at the following tables:<br />\"
Employees_Norway\"
:<br />E_IDE_Name01Hansen, Ola02Svendson, Tove03Svendson, Stephen04Pettersen, Kari<br />\"
Employees_USA\"
:<br />E_IDE_Name01Turner, Sally02Kent, Clark03Svendson, Stephen04Scott, Stephen<br />Now we want to list all the different employees in Norway and USA.<br />We use the following SELECT statement:<br />SELECT E_Name FROM Employees_NorwayUNIONSELECT E_Name FROM Employees_USA<br />The result-set will look like this:<br />E_NameHansen, OlaSvendson, ToveSvendson, StephenPettersen, KariTurner, SallyKent, ClarkScott, Stephen<br />Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.<br />SQL UNION ALL Example<br />Now we want to list all employees in Norway and USA:<br />SELECT E_Name FROM Employees_NorwayUNION ALLSELECT E_Name FROM Employees_USA<br />Result<br />E_NameHansen, OlaSvendson, ToveSvendson, StephenPettersen, KariTurner, SallyKent, ClarkSvendson, StephenScott, Stephen<br />« PreviousNext Chapter »<br />SQL SELECT INTO Statement<br />« PreviousNext Chapter »<br />The SQL SELECT INTO statement can be used to create backup copies of tables.<br />The SQL SELECT INTO Statement<br />The SELECT INTO statement selects data from one table and inserts it into a different table. <br />The SELECT INTO statement is most often used to create backup copies of tables.<br />SQL SELECT INTO Syntax<br />We can select all columns into the new table:<br />SELECT *INTO new_table_name [IN externaldatabase]FROM old_tablename<br />Or we can select only the columns we want into the new table:<br />SELECT column_name(s)INTO new_table_name [IN externaldatabase]FROM old_tablename<br />SQL SELECT INTO Example<br />Make a Backup Copy - Now we want to make an exact copy of the data in our \"
Persons\"
 table.<br />We use the following SQL statement:<br />SELECT *INTO Persons_BackupFROM Persons<br />We can also use the IN clause to copy the table into another database:<br />SELECT *INTO Persons_Backup IN 'Backup.mdb'FROM Persons<br />We can also copy only a few fields into the new table:<br />SELECT LastName,FirstNameINTO Persons_BackupFROM Persons<br />SQL SELECT INTO - With a WHERE Clause<br />We can also add a WHERE clause.<br />The following SQL statement creates a \"
Persons_Backup\"
 table with only the persons who lives in the city \"
Sandnes\"
:<br />SELECT LastName,FirstnameINTO Persons_BackupFROM PersonsWHERE City='Sandnes'<br />SQL SELECT INTO - Joined Tables<br />Selecting data from more than one table is also possible.<br />The following example creates a \"
Persons_Order_Backup\"
 table contains data from the two tables \"
Persons\"
 and \"
Orders\"
:<br />SELECT Persons.LastName,Orders.OrderNoINTO Persons_Order_BackupFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_Id<br />« PreviousNext Chapter »<br />SQL CREATE DATABASE Statement<br />« PreviousNext Chapter »<br />The CREATE DATABASE Statement<br />The CREATE DATABASE statement is used to create a database.<br />SQL CREATE DATABASE Syntax<br />CREATE DATABASE database_name<br />CREATE DATABASE Example<br />Now we want to create a database called \"
my_db\"
.<br />We use the following CREATE DATABASE statement:<br />CREATE DATABASE my_db<br />Database tables can be added with the CREATE TABLE statement.<br />« PreviousNext Chapter »<br />SQL CREATE TABLE Statement<br />« PreviousNext Chapter »<br />The CREATE TABLE Statement<br />The CREATE TABLE statement is used to create a table in a database.<br />SQL CREATE TABLE Syntax<br />CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,....)<br />The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.<br />CREATE TABLE Example<br />Now we want to create a table called \"
Persons\"
 that contains five columns: P_Id, LastName, FirstName, Address, and City.<br />We use the following CREATE TABLE statement:<br />CREATE TABLE Persons(P_Id int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255))<br />The P_Id column is of type int and will hold a number. The LastName, FirstName, Address, and City columns are of type varchar with a maximum length of 255 characters.<br />The empty \"
Persons\"
 table will now look like this:<br />P_IdLastNameFirstNameAddressCity     <br />The empty table can be filled with data with the INSERT INTO statement.<br />« PreviousNext Chapter »<br />SQL Constraints<br />« PreviousNext Chapter »<br />SQL Constraints<br />Constraints are used to limit the type of data that can go into a table.<br />Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).<br />We will focus on the following constraints:<br />NOT NULL<br />UNIQUE<br />PRIMARY KEY<br />FOREIGN KEY<br />CHECK<br />DEFAULT<br />The next chapters will describe each constraint in details.<br />« PreviousNext Chapter »<br />SQL NOT NULL Constraint<br />« PreviousNext Chapter »<br />By default, a table column can hold NULL values.<br />SQL NOT NULL Constraint<br />The NOT NULL constraint enforces a column to NOT accept NULL values.<br />The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.<br />The following SQL enforces the \"
P_Id\"
 column and the \"
LastName\"
 column to not accept NULL values:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />« PreviousNext Chapter »<br />SQL UNIQUE Constraint<br />« PreviousNext Chapter »<br />SQL UNIQUE Constraint<br />The UNIQUE constraint uniquely identifies each record in a database table.<br />The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.<br />A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.<br />Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.<br />SQL UNIQUE Constraint on CREATE TABLE<br />The following SQL creates a UNIQUE constraint on the \"
P_Id\"
 column when the \"
Persons\"
 table is created:<br />MySQL:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),UNIQUE (P_Id))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL UNIQUE,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName))<br />SQL UNIQUE Constraint on ALTER TABLE<br />To create a UNIQUE constraint on the \"
P_Id\"
 column when the table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD UNIQUE (P_Id)<br />To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)<br />To DROP a UNIQUE Constraint<br />To drop a UNIQUE constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsDROP INDEX uc_PersonID<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsDROP CONSTRAINT uc_PersonID<br />« PreviousNext Chapter <br />SQL PRIMARY KEY Constraint<br />« PreviousNext Chapter »<br />SQL PRIMARY KEY Constraint<br />The PRIMARY KEY constraint uniquely identifies each record in a database table.<br />Primary keys must contain unique values.<br />A primary key column cannot contain NULL values.<br />Each table should have a primary key, and each table can have only ONE primary key.<br />SQL PRIMARY KEY Constraint on CREATE TABLE<br />The following SQL creates a PRIMARY KEY on the \"
P_Id\"
 column when the \"
Persons\"
 table is created:<br />MySQL:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName))<br />SQL PRIMARY KEY Constraint on ALTER TABLE<br />To create a PRIMARY KEY constraint on the \"
P_Id\"
 column when the table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD PRIMARY KEY (P_Id)<br />To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)<br />Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).<br />To DROP a PRIMARY KEY Constraint<br />To drop a PRIMARY KEY constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsDROP PRIMARY KEY<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID<br />« PreviousNext Chapter »<br />SQL FOREIGN KEY Constraint<br />« PreviousNext Chapter »<br />SQL FOREIGN KEY Constraint<br />A FOREIGN KEY in one table points to a PRIMARY KEY in another table.<br />Let's illustrate the foreign key with an example. Look at the following two tables:<br />The \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \"
Orders\"
 table:<br />O_IdOrderNoP_Id1778953244678332245624245621<br />Note that the \"
P_Id\"
 column in the \"
Orders\"
 table points to the \"
P_Id\"
 column in the \"
Persons\"
 table.<br />The \"
P_Id\"
 column in the \"
Persons\"
 table is the PRIMARY KEY in the \"
Persons\"
 table.<br />The \"
P_Id\"
 column in the \"
Orders\"
 table is a FOREIGN KEY in the \"
Orders\"
 table.<br />The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.<br />The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.<br />SQL FOREIGN KEY Constraint on CREATE TABLE<br />The following SQL creates a FOREIGN KEY on the \"
P_Id\"
 column when the \"
Orders\"
 table is created:<br />MySQL:<br />CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,PRIMARY KEY (O_Id),FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Orders(O_Id int NOT NULL PRIMARY KEY,OrderNo int NOT NULL,P_Id int FOREIGN KEY REFERENCES Persons(P_Id))<br />To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,PRIMARY KEY (O_Id),CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)REFERENCES Persons(P_Id))<br />SQL FOREIGN KEY Constraint on ALTER TABLE<br />To create a FOREIGN KEY constraint on the \"
P_Id\"
 column when the \"
Orders\"
 table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE OrdersADD FOREIGN KEY (P_Id)REFERENCES Persons(P_Id)<br />To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE OrdersADD CONSTRAINT fk_PerOrdersFOREIGN KEY (P_Id)REFERENCES Persons(P_Id)<br />To DROP a FOREIGN KEY Constraint<br />To drop a FOREIGN KEY constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE OrdersDROP FOREIGN KEY fk_PerOrders<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE OrdersDROP CONSTRAINT fk_PerOrders<br />« PreviousNext Chapter »<br />SQL CHECK Constraint<br />« PreviousNext Chapter »<br />SQL CHECK Constraint<br />The CHECK constraint is used to limit the value range that can be placed in a column.<br />If you define a CHECK constraint on a single column it allows only certain values for this column.<br />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.<br />SQL CHECK Constraint on CREATE TABLE<br />The following SQL creates a CHECK constraint on the \"
P_Id\"
 column when the \"
Persons\"
 table is created. The CHECK constraint specifies that the column \"
P_Id\"
 must only include integers greater than 0.<br />My SQL:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CHECK (P_Id>0))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes'))<br />SQL CHECK Constraint on ALTER TABLE<br />To create a CHECK constraint on the \"
P_Id\"
 column when the table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CHECK (P_Id>0)<br />To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')<br />To DROP a CHECK Constraint<br />To drop a CHECK constraint, use the following SQL:<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsDROP CONSTRAINT chk_Person<br />« PreviousNext Chapter »<br />SQL DEFAULT Constraint<br />« PreviousNext Chapter »<br />SQL DEFAULT Constraint<br />The DEFAULT constraint is used to insert a default value into a column.<br />The default value will be added to all new records, if no other value is specified.<br />SQL DEFAULT Constraint on CREATE TABLE<br />The following SQL creates a DEFAULT constraint on the \"
City\"
 column when the \"
Persons\"
 table is created:<br />My SQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255) DEFAULT 'Sandnes')<br />The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():<br />CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,OrderDate date DEFAULT GETDATE())<br />SQL DEFAULT Constraint on ALTER TABLE<br />To create a DEFAULT constraint on the \"
City\"
 column when the table is already created, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsALTER City SET DEFAULT 'SANDNES'<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsALTER COLUMN City SET DEFAULT 'SANDNES'<br />To DROP a DEFAULT Constraint<br />To drop a DEFAULT constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsALTER City DROP DEFAULT<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsALTER COLUMN City DROP DEFAULT<br />« PreviousNext Chapter »<br />SQL CREATE INDEX Statement<br />« PreviousNext Chapter »<br />The CREATE INDEX statement is used to create indexes in tables.<br />Indexes allow the database application to find data fast; without reading the whole table.<br />Indexes<br />An index can be created in a table to find data more quickly and efficiently.<br />The users cannot see the indexes, they are just used to speed up searches/queries.<br />Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.<br />SQL CREATE INDEX Syntax<br />Creates an index on a table. Duplicate values are allowed:<br />CREATE INDEX index_nameON table_name (column_name)<br />SQL CREATE UNIQUE INDEX Syntax<br />Creates a unique index on a table. Duplicate values are not allowed:<br />CREATE UNIQUE INDEX index_nameON table_name (column_name)<br />Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.<br />CREATE INDEX Example<br />The SQL statement below creates an index named \"
PIndex\"
 on the \"
LastName\"
 column in the \"
Persons\"
 table:<br />CREATE INDEX PIndexON Persons (LastName)<br />If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:<br />CREATE INDEX PIndexON Persons (LastName, FirstName)<br />« PreviousNext Chapter <br />SQL DROP INDEX, DROP TABLE, and DROP DATABASE<br />« PreviousNext Chapter »<br />Indexes, tables, and databases can easily be deleted/removed with the DROP statement.<br />The DROP INDEX Statement<br />The DROP INDEX statement is used to delete an index in a table.<br />DROP INDEX Syntax for MS Access:<br />DROP INDEX index_name ON table_name<br />DROP INDEX Syntax for MS SQL Server:<br />DROP INDEX table_name.index_name<br />DROP INDEX Syntax for DB2/Oracle:<br />DROP INDEX index_name<br />DROP INDEX Syntax for MySQL:<br />ALTER TABLE table_name DROP INDEX index_name<br />The DROP TABLE Statement<br />The DROP TABLE statement is used to delete a table.<br />DROP TABLE table_name<br />The DROP DATABASE Statement<br />The DROP DATABASE statement is used to delete a database.<br />DROP DATABASE database_name<br />The TRUNCATE TABLE Statement<br />What if we only want to delete the data inside the table, and not the table itself?<br />Then, use the TRUNCATE TABLE statement:<br />TRUNCATE TABLE table_name<br />« PreviousNext Chapter »<br />SQL ALTER TABLE Statement<br />« PreviousNext Chapter »<br />The ALTER TABLE Statement<br />The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.<br />SQL ALTER TABLE Syntax<br />To add a column in a table, use the following syntax:<br />ALTER TABLE table_nameADD column_name datatype<br />To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):<br />ALTER TABLE table_nameDROP COLUMN column_name<br />To change the data type of a column in a table, use the following syntax:<br />ALTER TABLE table_nameALTER COLUMN column_name datatype<br />SQL ALTER TABLE Example<br />Look at the \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to add a column named \"
DateOfBirth\"
 in the \"
Persons\"
 table.<br />We use the following SQL statement:<br />ALTER TABLE PersonsADD DateOfBirth date<br />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 MS Access, MySQL, and SQL Server, go to our complete Data Types reference.<br />The \"
Persons\"
 table will now like this:<br />P_IdLastNameFirstNameAddressCityDateOfBirth1HansenOlaTimoteivn 10Sandnes 2SvendsonToveBorgvn 23Sandnes 3PettersenKariStorgt 20Stavanger <br />Change Data Type Example<br />Now we want to change the data type of the column named \"
DateOfBirth\"
 in the \"
Persons\"
 table.<br />We use the following SQL statement:<br />ALTER TABLE PersonsALTER COLUMN DateOfBirth year<br />Notice that the \"
DateOfBirth\"
 column is now of type year and is going to hold a year in a two-digit or four-digit format.<br />DROP COLUMN Example<br />Next, we want to delete the column named \"
DateOfBirth\"
 in the \"
Persons\"
 table.<br />We use the following SQL statement:<br />ALTER TABLE PersonsDROP COLUMN DateOfBirth<br />The \"
Persons\"
 table will now like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />« PreviousNext Chapter <br />SQL AUTO INCREMENT Field<br />« PreviousNext Chapter »<br />Auto-increment allows a unique number to be generated when a new record is inserted into a table.<br />AUTO INCREMENT a Field<br />Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.<br />We would like to create an auto-increment field in a table.<br />Syntax for MySQL<br />The following SQL statement defines the \"
P_Id\"
 column to be an auto-increment primary key field in the \"
Persons\"
 table:<br />CREATE TABLE Persons(P_Id int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))<br />MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.<br />By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.<br />To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:<br />ALTER TABLE Persons AUTO_INCREMENT=100<br />To insert a new record into the \"
Persons\"
 table, we will not have to specify a value for the \"
P_Id\"
 column (a unique value will be added automatically):<br />INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')<br />The SQL statement above would insert a new record into the \"
Persons\"
 table. The \"
P_Id\"
 column would be assigned a unique value. The \"
FirstName\"
 column would be set to \"
Lars\"
 and the \"
LastName\"
 column would be set to \"
Monsen\"
.<br />Syntax for SQL Server<br />The following SQL statement defines the \"
P_Id\"
 column to be an auto-increment primary key field in the \"
Persons\"
 table:<br />CREATE TABLE Persons(P_Id int PRIMARY KEY IDENTITY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. <br />By default, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.<br />To specify that the \"
P_Id\"
 column should start at value 10 and increment by 5, change the identity to IDENTITY(10,5).<br />To insert a new record into the \"
Persons\"
 table, we will not have to specify a value for the \"
P_Id\"
 column (a unique value will be added automatically):<br />INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')<br />The SQL statement above would insert a new record into the \"
Persons\"
 table. The \"
P_Id\"
 column would be assigned a unique value. The \"
FirstName\"
 column would be set to \"
Lars\"
 and the \"
LastName\"
 column would be set to \"
Monsen\"
.<br />Syntax for Access<br />The following SQL statement defines the \"
P_Id\"
 column to be an auto-increment primary key field in the \"
Persons\"
 table:<br />CREATE TABLE Persons(P_Id PRIMARY KEY AUTOINCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature. <br />By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record.<br />To specify that the \"
P_Id\"
 column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10,5).<br />To insert a new record into the \"
Persons\"
 table, we will not have to specify a value for the \"
P_Id\"
 column (a unique value will be added automatically):<br />INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')<br />The SQL statement above would insert a new record into the \"
Persons\"
 table. The \"
P_Id\"
 column would be assigned a unique value. The \"
FirstName\"
 column would be set to \"
Lars\"
 and the \"
LastName\"
 column would be set to \"
Monsen\"
.<br />Syntax for Oracle<br />In Oracle the code is a little bit more tricky.<br />You will have to create an auto-increment field with the sequence object (this object generates a number sequence).<br />Use the following CREATE SEQUENCE syntax:<br />CREATE SEQUENCE seq_personMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10<br />The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.<br />To insert a new record into the \"
Persons\"
 table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):<br />INSERT INTO Persons (P_Id,FirstName,LastName)VALUES (seq_person.nextval,'Lars','Monsen')<br />The SQL statement above would insert a new record into the \"
Persons\"
 table. The \"
P_Id\"
 column would be assigned the next number from the seq_person sequence. The \"
FirstName\"
 column would be set to \"
Lars\"
 and the \"
LastName\"
 column would be set to \"
Monsen\"
.<br />« PreviousNext Chapter <br />SQL Views<br />« PreviousNext Chapter »<br />A view is a virtual table.<br />This chapter shows how to create, update, and delete a view. <br />SQL CREATE VIEW Statement<br />In SQL, a view is a virtual table based on the result-set of an SQL statement.<br />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.<br />You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.<br />SQL CREATE VIEW Syntax<br />CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition<br />Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.<br />SQL CREATE VIEW Examples<br />If you have the Northwind database you can see that it has several views installed by default.<br />The view \"
Current Product List\"
 lists all active products (products that are not discontinued) from the \"
Products\"
 table. The view is created with the following SQL:<br />CREATE VIEW [Current Product List] ASSELECT ProductID,ProductNameFROM ProductsWHERE Discontinued=No<br />We can query the view above as follows:<br />SELECT * FROM [Current Product List]<br />Another view in the Northwind sample database selects every product in the \"
Products\"
 table with a unit price higher than the average unit price:<br />CREATE VIEW [Products Above Average Price] ASSELECT ProductName,UnitPriceFROM ProductsWHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)<br />We can query the view above as follows:<br />SELECT * FROM [Products Above Average Price]<br />Another view in the Northwind database calculates the total sale for each category in 1997. Note that this view selects its data from another view called \"
Product Sales for 1997\"
:<br />CREATE VIEW [Category Sales For 1997] ASSELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySalesFROM [Product Sales for 1997]GROUP BY CategoryName<br />We can query the view above as follows:<br />SELECT * FROM [Category Sales For 1997]<br />We can also add a condition to the query. Now we want to see the total sale only for the category \"
Beverages\"
:<br />SELECT * FROM [Category Sales For 1997]WHERE CategoryName='Beverages'<br />SQL Updating a View<br />You can update a view by using the following syntax:<br />SQL CREATE OR REPLACE VIEW Syntax<br />CREATE OR REPLACE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition<br />Now we want to add the \"
Category\"
 column to the \"
Current Product List\"
 view. We will update the view with the following SQL:<br />CREATE VIEW [Current Product List] ASSELECT ProductID,ProductName,CategoryFROM ProductsWHERE Discontinued=No<br />SQL Dropping a View<br />You can delete a view with the DROP VIEW command.<br />SQL DROP VIEW Syntax<br />DROP VIEW view_name<br />« PreviousNext Chapter »<br />SQL Date Functions<br />« PreviousNext Chapter »<br />SQL Dates<br />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.<br />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 complicated.<br />Before talking about the complications of querying for dates, we will look at the most important built-in functions for working with dates.<br />MySQL Date Functions<br />The following table lists the most important built-in date functions in MySQL:<br />FunctionDescriptionNOW()Returns the current date and timeCURDATE()Returns the current dateCURTIME()Returns the current timeDATE()Extracts the date part of a date or date/time expressionEXTRACT()Returns a single part of a date/timeDATE_ADD()Adds a specified time interval to a dateDATE_SUB()Subtracts a specified time interval from a dateDATEDIFF()Returns the number of days between two datesDATE_FORMAT()Displays date/time data in different formats<br />SQL Server Date Functions<br />The following table lists the most important built-in date functions in SQL Server:<br />FunctionDescriptionGETDATE()Returns the current date and timeDATEPART()Returns a single part of a date/timeDATEADD()Adds or subtracts a specified time interval from a dateDATEDIFF()Returns the time between two datesCONVERT()Displays date/time data in different formats<br />SQL Date Data Types<br />MySQL comes with the following data types for storing a date or a date/time value in the database:<br />DATE - format YYYY-MM-DD<br />DATETIME - format: YYYY-MM-DD HH:MM:SS<br />TIMESTAMP - format: YYYY-MM-DD HH:MM:SS<br />YEAR - format YYYY or YY<br />SQL Server comes with the following data types for storing a date or a date/time value in the database:<br />DATE - format YYYY-MM-DD<br />DATETIME - format: YYYY-MM-DD HH:MM:SS<br />SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS<br />TIMESTAMP - format: a unique number<br />Note: The date types are chosen for a column when you create a new table in your database!<br />For an overview of all data types available, go to our complete Data Types reference.<br />SQL Working with Dates<br />You can compare two dates easily if there is no time component involved!<br />Assume we have the following \"
Orders\"
 table:<br />OrderIdProductNameOrderDate1Geitost2008-11-112Camembert Pierrot2008-11-093Mozzarella di Giovanni2008-11-114Mascarpone Fabioli2008-10-29<br />Now we want to select the records with an OrderDate of \"
2008-11-11\"
 from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM Orders WHERE OrderDate='2008-11-11'<br />The result-set will look like this:<br />OrderIdProductNameOrderDate1Geitost2008-11-113Mozzarella di Giovanni2008-11-11<br />Now, assume that the \"
Orders\"
 table looks like this (notice the time component in the \"
OrderDate\"
 column):<br />OrderIdProductNameOrderDate1Geitost2008-11-11 13:23:442Camembert Pierrot2008-11-09 15:45:213Mozzarella di Giovanni2008-11-11 11:12:014Mascarpone Fabioli2008-10-29 14:56:59<br />If we use the same SELECT statement as above:<br />SELECT * FROM Orders WHERE OrderDate='2008-11-11'<br />we will get no result! This is because the query is looking only for dates with no time portion.<br />Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your dates!<br />« PreviousNext Chapter »<br />SQL NULL Values<br />« PreviousNext Chapter »<br />NULL values represent missing unknown data.<br />By default, a table column can hold NULL values.<br />This chapter will explain the IS NULL and IS NOT NULL operators.<br />SQL NULL Values<br />If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.<br />NULL values are treated differently from other values.<br />NULL is used as a placeholder for unknown or inapplicable values.<br />Note: It is not possible to compare NULL and 0; they are not equivalent.<br />SQL Working with NULL Values<br />Look at the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOla Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKari Stavanger<br />Suppose that the \"
Address\"
 column in the \"
Persons\"
 table is optional. This means that if we insert a record with no value for the \"
Address\"
 column, the \"
Address\"
 column will be saved with a NULL value.<br />How can we test for NULL values?<br />It is not possible to test for NULL values with comparison operators, such as =, <, or <>.<br />We will have to use the IS NULL and IS NOT NULL operators instead.<br />SQL IS NULL<br />How do we select only the records with NULL values in the \"
Address\"
 column?<br />We will have to use the IS NULL operator:<br />SELECT LastName,FirstName,Address FROM PersonsWHERE Address IS NULL<br />The result-set will look like this:<br />LastNameFirstNameAddressHansenOla PettersenKari <br />Tip: Always use IS NULL to look for NULL values.<br />SQL IS NOT NULL<br />How do we select only the records with no NULL values in the \"
Address\"
 column?<br />We will have to use the IS NOT NULL operator:<br />SELECT LastName,FirstName,Address FROM PersonsWHERE Address IS NOT NULL<br />The result-set will look like this:<br />LastNameFirstNameAddressSvendsonToveBorgvn 23<br />In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.<br />« PreviousNext Chapter »<br />SQL NULL Functions<br />« PreviousNext Chapter »<br />SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions<br />Look at the following \"
Products\"
 table:<br />P_IdProductNameUnitPriceUnitsInStockUnitsOnOrder1Jarlsberg10.4516152Mascarpone32.5623 3Gorgonzola15.67920<br />Suppose that the \"
UnitsOnOrder\"
 column is optional, and may contain NULL values.<br />We have the following SELECT statement:<br />SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)FROM Products<br />In the example above, if any of the \"
UnitsOnOrder\"
 values are NULL, the result is NULL.<br />Microsoft's ISNULL() function is used to specify how we want to treat NULL values.<br />The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.<br />In this case we want NULL values to be zero.<br />Below, if \"
UnitsOnOrder\"
 is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is NULL:<br />SQL Server / MS Access<br />SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))FROM Products<br />Oracle<br />Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:<br />SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))FROM Products<br />MySQL<br />MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function.<br />In MySQL we can use the IFNULL() function, like this:<br />SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))FROM Products<br />or we can use the COALESCE() function, like this:<br />SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))FROM Products<br />« PreviousNext Chapter <br />SQL Data Types<br />« PreviousNext Chapter »<br />Data types and ranges for Microsoft Access, MySQL and SQL Server.<br />Microsoft Access Data Types<br />Data typeDescriptionStorageTextUse for text or combinations of text and numbers. 255 characters maximum MemoMemo is used for larger amounts of text. Stores up to 65,536 characters. Note: You cannot sort a memo field. However, they are searchable ByteAllows whole numbers from 0 to 2551 byteIntegerAllows whole numbers between -32,768 and 32,7672 bytesLongAllows whole numbers between -2,147,483,648 and 2,147,483,6474 bytesSingleSingle precision floating-point. Will handle most decimals 4 bytesDoubleDouble precision floating-point. Will handle most decimals8 bytesCurrencyUse for currency. Holds up to 15 digits of whole dollars, plus 4 decimal places. Tip: You can choose which country's currency to use8 bytesAutoNumberAutoNumber fields automatically give each record its own number, usually starting at 14 bytesDate/TimeUse for dates and times8 bytesYes/NoA logical field can be displayed as Yes/No, True/False, or On/Off. In code, use the constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/No fields1 bitOle ObjectCan store pictures, audio, video, or other BLOBs (Binary Large OBjects)up to 1GBHyperlinkContain links to other files, including web pages Lookup WizardLet you type a list of options, which can then be chosen from a drop-down list4 bytes<br />MySQL Data Types<br />In MySQL there are three main types : text, number, and Date/Time types.<br />Text types:<br />Data typeDescriptionCHAR(size)Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 charactersVARCHAR(size)Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT typeTINYTEXTHolds a string with a maximum length of 255 charactersTEXTHolds a string with a maximum length of 65,535 charactersBLOBFor BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of dataMEDIUMTEXTHolds a string with a maximum length of 16,777,215 charactersMEDIUMBLOBFor BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of dataLONGTEXTHolds a string with a maximum length of 4,294,967,295 charactersLONGBLOBFor BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of dataENUM(x,y,z,etc.)Let you enter 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. Note: The values are sorted in the order you enter them.You enter the possible values in this format: ENUM('X','Y','Z')SETSimilar to ENUM except that SET may contain up to 64 list items and can store more than one choice<br />Number types:<br />Data typeDescriptionTINYINT(size)-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesisSMALLINT(size)-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesisMEDIUMINT(size)-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesisINT(size)-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesisBIGINT(size)-9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesisFLOAT(size,d)A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameterDOUBLE(size,d)A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameterDECIMAL(size,d)A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter<br />*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number. <br />Date types:<br />Data typeDescriptionDATE()A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31'DATETIME()*A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'TIMESTAMP()*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 Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTCTIME()A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59'YEAR()A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069<br />*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.<br />SQL Server Data Types<br />Character strings:<br />Data typeDescriptionStoragechar(n)Fixed-length character string. Maximum 8,000 charactersnvarchar(n)Variable-length character string. Maximum 8,000 characters varchar(max)Variable-length character string. Maximum 1,073,741,824 characters textVariable-length character string. Maximum 2GB of text data <br />Unicode strings:<br />Data typeDescriptionStoragenchar(n)Fixed-length Unicode data. Maximum 4,000 characters nvarchar(n)Variable-length Unicode data. Maximum 4,000 characters nvarchar(max)Variable-length Unicode data. Maximum 536,870,912 characters ntextVariable-length Unicode data. Maximum 2GB of text data <br />Binary types:<br />Data typeDescriptionStoragebitAllows 0, 1, or NULL binary(n)Fixed-length binary data. Maximum 8,000 bytes varbinary(n)Variable-length binary data. Maximum 8,000 bytes varbinary(max)Variable-length binary data. Maximum 2GB imageVariable-length binary data. Maximum 2GB <br />Number types:<br />Data typeDescriptionStoragetinyintAllows whole numbers from 0 to 2551 bytesmallintAllows whole numbers between -32,768 and 32,7672 bytesintAllows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytesbigintAllows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytesdecimal(p,s)Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 –1.The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 05-17 bytesnumeric(p,s)Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 –1.The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 05-17 bytessmallmoneyMonetary data from -214,748.3648 to 214,748.3647 4 bytesmoneyMonetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.58078 bytesfloat(n)Floating precision number data from -1.79E + 308 to 1.79E + 308. The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.4 or 8 bytesrealFloating precision number data from -3.40E + 38 to 3.40E + 384 bytes<br />Date types:<br />Data typeDescriptionStoragedatetimeFrom January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds8 bytesdatetime2From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds6-8 bytessmalldatetimeFrom January 1, 1900 to June 6, 2079 with an accuracy of 1 minute4 bytesdateStore a date only. From January 1, 0001 to December 31, 99993 bytestimeStore a time only to an accuracy of 100 nanoseconds3-5 bytesdatetimeoffsetThe same as datetime2 with the addition of a time zone offset8-10 bytestimestampStores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable <br />Other data types:<br />Data typeDescriptionsql_variantStores up to 8,000 bytes of data of various data types, except text, ntext, and timestampuniqueidentifierStores a globally unique identifier (GUID)xmlStores XML formatted data. Maximum 2GBcursorStores a reference to a cursor used for database operationstableStores a result-set for later processing<br />« PreviousNext Chapter »<br />SQL Functions<br />« PreviousNext Chapter »<br />SQL has many built-in functions for performing calculations on data.<br />SQL Aggregate Functions<br />SQL aggregate functions return a single value, calculated from values in a column.<br />Useful aggregate functions:<br />AVG() - Returns the average value<br />COUNT() - Returns the number of rows<br />FIRST() - Returns the first value<br />LAST() - Returns the last value<br />MAX() - Returns the largest value<br />MIN() - Returns the smallest value<br />SUM() - Returns the sum<br />SQL Scalar functions<br />SQL scalar functions return a single value, based on the input value.<br />Useful scalar functions:<br />UCASE() - Converts a field to upper case<br />LCASE() - Converts a field to lower case<br />MID() - Extract characters from a text field<br />LEN() - Returns the length of a text field<br />ROUND() - Rounds a numeric field to the number of decimals specified<br />NOW() - Returns the current system date and time<br />FORMAT() - Formats how a field is to be displayed<br />Tip: The aggregate functions and the scalar functions will be explained in details in the next chapters.<br />« PreviousNext Chapter »<br />SQL AVG() Function<br />« PreviousNext Chapter »<br />The AVG() Function<br />The AVG() function returns the average value of a numeric column.<br />SQL AVG() Syntax<br />SELECT AVG(column_name) FROM table_name<br />SQL AVG() Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the average value of the \"
OrderPrice\"
 fields.<br />We use the following SQL statement:<br />SELECT AVG(OrderPrice) AS OrderAverage FROM Orders<br />The result-set will look like this:<br />OrderAverage950<br />Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value.<br />We use the following SQL statement:<br />SELECT Customer FROM OrdersWHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)<br />The result-set will look like this:<br />CustomerHansenNilsenJensen<br />« PreviousNext Chapter »<br />SQL COUNT() Function<br />« PreviousNext Chapter »<br />The COUNT() function returns the number of rows that matches a specified criteria.<br />SQL COUNT(column_name) Syntax<br />The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:<br />SELECT COUNT(column_name) FROM table_name<br />SQL COUNT(*) Syntax<br />The COUNT(*) function returns the number of records in a table:<br />SELECT COUNT(*) FROM table_name<br />SQL COUNT(DISTINCT column_name) Syntax<br />The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:<br />SELECT COUNT(DISTINCT column_name) FROM table_name<br />Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.<br />SQL COUNT(column_name) Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to count the number of orders from \"
Customer Nilsen\"
.<br />We use the following SQL statement:<br />SELECT COUNT(Customer) AS CustomerNilsen FROM OrdersWHERE Customer='Nilsen'<br />The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:<br />CustomerNilsen2<br />SQL COUNT(*) Example<br />If we omit the WHERE clause, like this:<br />SELECT COUNT(*) AS NumberOfOrders FROM Orders<br />The result-set will look like this:<br />NumberOfOrders6<br />which is the total number of rows in the table.<br />SQL COUNT(DISTINCT column_name) Example<br />Now we want to count the number of unique customers in the \"
Orders\"
 table.<br />We use the following SQL statement:<br />SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders<br />The result-set will look like this:<br />NumberOfCustomers3<br />which is the number of unique customers (Hansen, Nilsen, and Jensen) in the \"
Orders\"
 table.<br />« PreviousNext Chapter »<br />SQL FIRST() Function<br />« PreviousNext Chapter »<br />The FIRST() Function<br />The FIRST() function returns the first value of the selected column.<br />SQL FIRST() Syntax<br />SELECT FIRST(column_name) FROM table_name<br />SQL FIRST() Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the first value of the \"
OrderPrice\"
 column.<br />We use the following SQL statement:<br />SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders<br />Tip: Workaround if FIRST() function is not supported:<br />SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1<br />The result-set will look like this:<br />FirstOrderPrice1000<br />« PreviousNext Chapter »<br />SQL LAST() Function<br />« PreviousNext Chapter »<br />The LAST() Function<br />The LAST() function returns the last value of the selected column.<br />SQL LAST() Syntax<br />SELECT LAST(column_name) FROM table_name<br />SQL LAST() Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the last value of the \"
OrderPrice\"
 column.<br />We use the following SQL statement:<br />SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders<br />Tip: Workaround if LAST() function is not supported:<br />SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1<br />The result-set will look like this:<br />LastOrderPrice100<br />« PreviousNext Chapter »<br />SQL MAX() Function<br />« PreviousNext Chapter »<br />The MAX() Function<br />The MAX() function returns the largest value of the selected column.<br />SQL MAX() Syntax<br />SELECT MAX(column_name) FROM table_name<br />SQL MAX() Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the largest value of the \"
OrderPrice\"
 column.<br />We use the following SQL statement:<br />SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders<br />The result-set will look like this:<br />LargestOrderPrice2000<br />« PreviousNext Chapter »<br />SQL MIN() Function<br />« PreviousNext Chapter »<br />The MIN() Function<br />The MIN() function returns the smallest value of the selected column.<br />SQL MIN() Syntax<br />SELECT MIN(column_name) FROM table_name<br />SQL MIN() Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the smallest value of the \"
OrderPrice\"
 column.<br />We use the following SQL statement:<br />SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders<br />The result-set will look like this:<br />SmallestOrderPrice100<br />« PreviousNext Chapter »<br />SQL SUM() Function<br />« PreviousNext Chapter »<br />The SUM() Function<br />The SUM() function returns the total sum of a numeric column.<br />SQL SUM() Syntax<br />SELECT SUM(column_name) FROM table_name<br />SQL SUM() Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the sum of all \"
OrderPrice\"
 fields\"
.<br />We use the following SQL statement:<br />SELECT SUM(OrderPrice) AS OrderTotal FROM Orders<br />The result-set will look like this:<br />OrderTotal5700<br />« PreviousNext Chapter »<br />SQL GROUP BY Statement<br />« PreviousNext Chapter »<br />Aggregate functions often need an added GROUP BY statement.<br />The GROUP BY Statement<br />The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.<br />SQL GROUP BY Syntax<br />SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_name<br />SQL GROUP BY Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the total sum (total order) of each customer.<br />We will have to use the GROUP BY statement to group the customers.<br />We use the following SQL statement:<br />SELECT Customer,SUM(OrderPrice) FROM OrdersGROUP BY Customer<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Hansen2000Nilsen1700Jensen2000<br />Nice! Isn't it? :)<br />Let's see what happens if we omit the GROUP BY statement:<br />SELECT Customer,SUM(OrderPrice) FROM Orders<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Hansen5700Nilsen5700Hansen5700Hansen5700Jensen5700Nilsen5700<br />The result-set above is not what we wanted.<br />Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The \"
SUM(OrderPrice)\"
 returns a single value (that is the total sum of the \"
OrderPrice\"
 column), while \"
Customer\"
 returns 6 values (one value for each row in the \"
Orders\"
 table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.<br />GROUP BY More Than One Column<br />We can also use the GROUP BY statement on more than one column, like this:<br />SELECT Customer,OrderDate,SUM(OrderPrice) FROM OrdersGROUP BY Customer,OrderDate<br />« PreviousNext Chapter »<br />SQL HAVING Clause<br />« PreviousNext Chapter »<br />The HAVING Clause<br />The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.<br />SQL HAVING Syntax<br />SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value<br />SQL HAVING Example<br />We have the following \"
Orders\"
 table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find if any of the customers have a total order of less than 2000.<br />We use the following SQL statement:<br />SELECT Customer,SUM(OrderPrice) FROM OrdersGROUP BY CustomerHAVING SUM(OrderPrice)<2000<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Nilsen1700<br />Now we want to find if the customers \"
Hansen\"
 or \"
Jensen\"
 have a total order of more than 1500.<br />We add an ordinary WHERE clause to the SQL statement:<br />SELECT Customer,SUM(OrderPrice) FROM OrdersWHERE Customer='Hansen' OR Customer='Jensen'GROUP BY CustomerHAVING SUM(OrderPrice)>1500<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Hansen2000Jensen2000<br />« PreviousNext Chapter »<br />SQL UCASE() Function<br />« PreviousNext Chapter »<br />The UCASE() Function<br />The UCASE() function converts the value of a field to uppercase.<br />SQL UCASE() Syntax<br />SELECT UCASE(column_name) FROM table_name<br />Syntax for SQL Server<br />SELECT UPPER(column_name) FROM table_name<br />SQL UCASE() Example<br />We have the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the content of the \"
LastName\"
 and \"
FirstName\"
 columns above, and convert the \"
LastName\"
 column to uppercase.<br />We use the following SELECT statement:<br />SELECT UCASE(LastName) as LastName,FirstName FROM Persons<br />The result-set will look like this:<br />LastNameFirstNameHANSENOlaSVENDSONTovePETTERSENKari<br />« PreviousNext Chapter »<br />SQL LCASE() Function<br />« PreviousNext Chapter »<br />The LCASE() Function<br />The LCASE() function converts the value of a field to lowercase.<br />SQL LCASE() Syntax<br />SELECT LCASE(column_name) FROM table_name<br />Syntax for SQL Server<br />SELECT LOWER(column_name) FROM table_name<br />SQL LCASE() Example<br />We have the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the content of the \"
LastName\"
 and \"
FirstName\"
 columns above, and convert the \"
LastName\"
 column to lowercase.<br />We use the following SELECT statement:<br />SELECT LCASE(LastName) as LastName,FirstName FROM Persons<br />The result-set will look like this:<br />LastNameFirstNamehansenOlasvendsonTovepettersenKari<br />« PreviousNext Chapter »<br />SQL MID() Function<br />« PreviousNext Chapter »<br />The MID() Function<br />The MID() function is used to extract characters from a text field.<br />SQL MID() Syntax<br />SELECT MID(column_name,start[,length]) FROM table_name<br />ParameterDescriptioncolumn_nameRequired. The field to extract characters fromstartRequired. Specifies the starting position (starts at 1)lengthOptional. The number of characters to return. If omitted, the MID() function returns the rest of the text<br />SQL MID() Example<br />We have the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to extract the first four characters of the \"
City\"
 column above.<br />We use the following SELECT statement:<br />SELECT MID(City,1,4) as SmallCity FROM Persons<br />The result-set will look like this:<br />SmallCitySandSandStav<br />SQL LEN() Function<br />« PreviousNext Chapter »<br />The LEN() Function<br />The LEN() function returns the length of the value in a text field.<br />SQL LEN() Syntax<br />SELECT LEN(column_name) FROM table_name<br />SQL LEN() Example<br />We have the following \"
Persons\"
 table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the length of the values in the \"
Address\"
 column above.<br />We use the following SELECT statement:<br />SELECT LEN(Address) as LengthOfAddress FROM Persons<br />The result-set will look like this:<br />LengthOfAddress1299<br />« PreviousNext Chapter »<br />SQL ROUND() Function<br />« PreviousNext Chapter »<br />The ROUND() Function<br />The ROUND() function is used to round a numeric field to the number of decimals specified.<br />SQL ROUND() Syntax<br />SELECT ROUND(column_name,decimals) FROM table_name<br />ParameterDescriptioncolumn_nameRequired. The field to round.decimalsRequired. Specifies the number of decimals to be returned.<br />SQL ROUND() Example<br />We have the following \"
Products\"
 table:<br />Prod_IdProductNameUnitUnitPrice1Jarlsberg1000 g10.452Mascarpone1000 g32.563Gorgonzola1000 g15.67<br />Now we want to display the product name and the price rounded to the nearest integer.<br />We use the following SELECT statement:<br />SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products<br />The result-set will look like this:<br />ProductNameUnitPriceJarlsberg10Mascarpone33Gorgonzola16<br />« PreviousNext Chapter »<br />SQL NOW() Function<br />« PreviousNext Chapter »<br />The NOW() Function<br />The NOW() function returns the current system date and time.<br />SQL NOW() Syntax<br />SELECT NOW() FROM table_name<br />SQL NOW() Example<br />We have the following \"
Products\"
 table:<br />Prod_IdProductNameUnitUnitPrice1Jarlsberg1000 g10.452Mascarpone1000 g32.563Gorgonzola1000 g15.67<br />Now we want to display the products and prices per today's date.<br />We use the following SELECT statement:<br />SELECT ProductName, UnitPrice, Now() as PerDate FROM Products<br />The result-set will look like this:<br />ProductNameUnitPricePerDateJarlsberg10.4510/7/2008 11:25:02 AMMascarpone32.5610/7/2008 11:25:02 AMGorgonzola15.6710/7/2008 11:25:02 AM<br />« PreviousNext Chapter »<br />SQL FORMAT() Function<br />« PreviousNext Chapter »<br />The FORMAT() Function<br />The FORMAT() function is used to format how a field is to be displayed.<br />SQL FORMAT() Syntax<br />SELECT FORMAT(column_name,format) FROM table_name<br />ParameterDescriptioncolumn_nameRequired. The field to be formatted.formatRequired. Specifies the format.<br />SQL FORMAT() Example<br />We have the following \"
Products\"
 table:<br />Prod_IdProductNameUnitUnitPrice1Jarlsberg1000 g10.452Mascarpone1000 g32.563Gorgonzola1000 g15.67<br />Now we want to display the products and prices per today's date (with today's date displayed in the following format \"
YYYY-MM-DD\"
).<br />We use the following SELECT statement:<br />SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDateFROM Products<br />The result-set will look like this:<br />ProductNameUnitPricePerDateJarlsberg10.452008-10-07Mascarpone32.562008-10-07Gorgonzola15.672008-10-07<br />« PreviousNext Chapter »<br />SQL Quick Reference From W3Schools<br />« PreviousNext Chapter »<br />SQL StatementSyntaxAND / ORSELECT column_name(s)FROM table_nameWHERE conditionAND|OR conditionALTER TABLEALTER TABLE table_name ADD column_name datatype orALTER TABLE table_name DROP COLUMN column_nameAS (alias)SELECT column_name AS column_aliasFROM table_name orSELECT column_nameFROM table_name  AS table_aliasBETWEENSELECT column_name(s)FROM table_nameWHERE column_nameBETWEEN value1 AND value2CREATE DATABASECREATE DATABASE database_nameCREATE TABLECREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name2 data_type,...)CREATE INDEXCREATE INDEX index_nameON table_name (column_name) orCREATE UNIQUE INDEX index_nameON table_name (column_name)CREATE VIEWCREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE conditionDELETEDELETE FROM table_nameWHERE some_column=some_value orDELETE FROM table_name (Note: Deletes the entire table!!)DELETE * FROM table_name (Note: Deletes the entire table!!)DROP DATABASEDROP DATABASE database_nameDROP INDEXDROP INDEX table_name.index_name (SQL Server)DROP INDEX index_name ON table_name (MS Access)DROP INDEX index_name (DB2/Oracle)ALTER TABLE table_nameDROP INDEX index_name (MySQL)DROP TABLEDROP TABLE table_nameGROUP BYSELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVINGSELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator valueINSELECT column_name(s)FROM table_nameWHERE column_nameIN (value1,value2,..)INSERT INTOINSERT INTO table_nameVALUES (value1, value2, value3,....) orINSERT INTO table_name(column1, column2, column3,...)VALUES (value1, value2, value3,....)INNER JOINSELECT column_name(s)FROM table_name1INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_nameLEFT JOINSELECT column_name(s)FROM table_name1LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_nameRIGHT JOINSELECT column_name(s)FROM table_name1RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_nameFULL JOINSELECT column_name(s)FROM table_name1FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_nameLIKESELECT column_name(s)FROM table_nameWHERE column_name LIKE patternORDER BYSELECT column_name(s)FROM table_nameORDER BY column_name [ASC|DESC]SELECTSELECT column_name(s)FROM table_nameSELECT *SELECT *FROM table_nameSELECT DISTINCTSELECT DISTINCT column_name(s)FROM table_nameSELECT INTOSELECT *INTO new_table_name [IN externaldatabase]FROM old_table_name orSELECT column_name(s)INTO new_table_name [IN externaldatabase]FROM old_table_nameSELECT TOPSELECT TOP number|percent column_name(s)FROM table_nameTRUNCATE TABLETRUNCATE TABLE table_nameUNIONSELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2UNION ALLSELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2UPDATEUPDATE table_nameSET column1=value, column2=value,...WHERE some_column=some_valueWHERESELECT column_name(s)FROM table_nameWHERE column_name operator value<br />Source : http://www.w3schools.com/sql/sql_quickref.asp<br />« PreviousNext Chapter »<br />SQL Hosting<br />« PreviousNext Chapter »<br />SQL Hosting<br />If you want your web site to be able to store and display data from a database, your web server should have access to a database system that uses the SQL language.<br />If your web server will be hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans.<br />The most common SQL hosting databases are MySQL, MS SQL Server, and MS Access.<br />You can have SQL databases on both Windows and Linux/UNIX operating systems.<br />Below is an overview of which database system that runs on which OS.<br />MS SQL Server<br />Runs only on Windows OS.<br />MySQL<br />Runs on both Windows and Linux/UNIX operating systems.<br />MS Access (recommended only for small websites)<br />Runs only on Windows OS.<br />To learn more about web hosting, please visit our Hosting tutorial.<br />« PreviousNext Chapter »<br />You Have Learned SQL, Now What?<br />« PreviousNext Chapter »<br />SQL Summary<br />This SQL tutorial has taught you the standard computer language for accessing and manipulating database systems.<br />You have learned how to execute queries, retrieve data, insert new records, delete records and update records in a database with SQL.<br />You have also learned how to create databases, tables, and indexes with SQL, and how to drop them.<br />You have learned the most important aggregate functions in SQL.<br />You now know that SQL is the standard language that works with all the well-known database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and MS Access.<br />Now You Know SQL, What's Next?<br />Our recommendation is to learn about ADO or PHP MySQL.<br />If you want to learn more about ADO, please visit our ADO tutorial.<br />If you want to learn more about MySQL, please visit our PHP tutorial.<br />« PreviousNext Chapter »<br />SQL Quiz<br />« PreviousNext Chapter »<br />You can test your SQL skills with W3Schools' Quiz.<br />The Test<br />The test contains 20 questions and there is no time limit.<br />The test is not official, it's just a nice way to see how much you know, or don't know, about SQL.<br />Your Score Will be Counted<br />You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 20 points.<br />Good luck! Start the SQL Quiz<br />
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools
Learning sql from w3schools

More Related Content

What's hot (20)

PPTX
SQL Functions
ammarbrohi
 
PPTX
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
Basic SQL and History
SomeshwarMoholkar
 
PPTX
Introduction to SQL
Ehsan Hamzei
 
PDF
Oracle SQL Basics
Dhananjay Goel
 
PDF
SQL Overview
Stewart Rogers
 
PPTX
SQL Commands
Sachidananda M H
 
PPTX
introdution to SQL and SQL functions
farwa waqar
 
PDF
Sql commands
Prof. Dr. K. Adisesha
 
PPT
Mysql
TSUBHASHRI
 
PPT
SQL Queries
Nilt1234
 
PPSX
ADO.NET
Farzad Wadia
 
PPTX
SQL commands
GirdharRatne
 
PDF
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
DOCX
Top 40 sql queries for testers
tlvd
 
PPTX
Sql queries presentation
NITISH KUMAR
 
PPT
MySQL and its basic commands
Bwsrang Basumatary
 
PPT
Introduction to CSS
Amit Tyagi
 
PPT
MYSQL Aggregate Functions
Leroy Blair
 
PPTX
Sql subquery
Raveena Thakur
 
SQL Functions
ammarbrohi
 
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Basic SQL and History
SomeshwarMoholkar
 
Introduction to SQL
Ehsan Hamzei
 
Oracle SQL Basics
Dhananjay Goel
 
SQL Overview
Stewart Rogers
 
SQL Commands
Sachidananda M H
 
introdution to SQL and SQL functions
farwa waqar
 
Sql commands
Prof. Dr. K. Adisesha
 
Mysql
TSUBHASHRI
 
SQL Queries
Nilt1234
 
ADO.NET
Farzad Wadia
 
SQL commands
GirdharRatne
 
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 
Top 40 sql queries for testers
tlvd
 
Sql queries presentation
NITISH KUMAR
 
MySQL and its basic commands
Bwsrang Basumatary
 
Introduction to CSS
Amit Tyagi
 
MYSQL Aggregate Functions
Leroy Blair
 
Sql subquery
Raveena Thakur
 

Viewers also liked (7)

DOC
Database management system file
Ankit Dixit
 
PDF
Database architectureby howard
oracle documents
 
PDF
Userpasswrd
oracle documents
 
PDF
Sql scripting sorcerypresentation
oracle documents
 
PDF
Beginbackup
oracle documents
 
DOC
Bus 120 course assignments wild 3 e
judithzander
 
Database management system file
Ankit Dixit
 
Database architectureby howard
oracle documents
 
Userpasswrd
oracle documents
 
Sql scripting sorcerypresentation
oracle documents
 
Beginbackup
oracle documents
 
Bus 120 course assignments wild 3 e
judithzander
 
Ad

Similar to Learning sql from w3schools (20)

DOCX
Sql
Archana Rout
 
DOC
Introduction to sql
SARVESH KUMAR
 
PDF
SQL Basics and Advanced for analytics.pdf
trg4294
 
PDF
SQL_BASIC AND ADVANCED.pdf
fayoyiwababajide
 
DOCX
SQL Language
Baker Ahimbisibwe
 
PDF
SQL notes 1.pdf
JitendraYadav351971
 
PPT
CE 279 - WRITING SQL QUERIES umat edition.ppt
minusahsaaka
 
DOC
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
Newyorksys.com
 
DOC
Learn sql queries
Sanjay Mago
 
PDF
Sql
Kikuvi John
 
PDF
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 
PPTX
SQL Tutorial for Beginners
Abdelhay Shafi
 
PPT
MS SQL Server 1
Iblesoft
 
PPTX
Sql slid
pacatarpit
 
PPT
SQL || overview and detailed information about Sql
gourav kottawar
 
PDF
Oracle Notes
Abhishek Sharma
 
PDF
SQL-Notes.pdf mba students database note
MrSushilMaurya
 
DOCX
Book HH - SQL MATERIAL
Satya Harish
 
PPTX
Sql
Aman Lalpuria
 
PPT
Sql – Structured Query Language
pandey3045_bit
 
Introduction to sql
SARVESH KUMAR
 
SQL Basics and Advanced for analytics.pdf
trg4294
 
SQL_BASIC AND ADVANCED.pdf
fayoyiwababajide
 
SQL Language
Baker Ahimbisibwe
 
SQL notes 1.pdf
JitendraYadav351971
 
CE 279 - WRITING SQL QUERIES umat edition.ppt
minusahsaaka
 
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
Newyorksys.com
 
Learn sql queries
Sanjay Mago
 
Chapter – 6 SQL Lab Tutorial.pdf
TamiratDejene1
 
SQL Tutorial for Beginners
Abdelhay Shafi
 
MS SQL Server 1
Iblesoft
 
Sql slid
pacatarpit
 
SQL || overview and detailed information about Sql
gourav kottawar
 
Oracle Notes
Abhishek Sharma
 
SQL-Notes.pdf mba students database note
MrSushilMaurya
 
Book HH - SQL MATERIAL
Satya Harish
 
Sql – Structured Query Language
pandey3045_bit
 
Ad

Recently uploaded (20)

PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Horarios de distribución de agua en julio
pegazohn1978
 
infertility, types,causes, impact, and management
Ritu480198
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 

Learning sql from w3schools

  • 1. Introduction to SQL<br />SQL is a standard language for accessing and manipulating databases.<br />What is SQL?<br />SQL stands for Structured Query Language<br />SQL lets you access and manipulate databases<br />SQL is an ANSI (American National Standards Institute) standard<br />What Can SQL do?<br />SQL can execute queries against a database<br />SQL can retrieve data from a database<br />SQL can insert records in a database<br />SQL can update records in a database<br />SQL can delete records from a database<br />SQL can create new databases<br />SQL can create new tables in a database<br />SQL can create stored procedures in a database<br />SQL can create views in a database<br />SQL can set permissions on tables, procedures, and views<br />SQL is a Standard - BUT....<br />Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language.<br />However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.<br />Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!<br />Using SQL in Your Web Site<br />To build a web site that shows some data from a database, you will need the following:<br />An RDBMS database program (i.e. MS Access, SQL Server, MySQL)<br />A server-side scripting language, like PHP or ASP<br />SQL<br />HTML / CSS<br />RDBMS<br />RDBMS stands for Relational Database Management System.<br />RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.<br />The data in RDBMS is stored in database objects called tables.<br />A table is a collection of related data entries and it consists of columns and rows.<br />SQL Syntax<br />« PreviousNext Chapter »<br />Database Tables<br />A database most often contains one or more tables. Each table is identified by a name (e.g. \" Customers\" or \" Orders\" ). Tables contain records (rows) with data.<br />Below is an example of a table called \" Persons\" :<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The table above contains three records (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City).<br />SQL Statements<br />Most of the actions you need to perform on a database are done with SQL statements.<br />The following SQL statement will select all the records in the \" Persons\" table:<br />SELECT * FROM Persons<br />In this tutorial we will teach you all about the different SQL statements.<br />Keep in Mind That...<br />SQL is not case sensitive<br />Semicolon after SQL Statements?<br />Some database systems require a semicolon at the end of each SQL statement.<br />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.<br />We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.<br />SQL DML and DDL<br />SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).<br />The query and update commands form the DML part of SQL:<br />SELECT - extracts data from a database<br />UPDATE - updates data in a database<br />DELETE - deletes data from a database<br />INSERT INTO - inserts new data into a database<br />The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are:<br />CREATE DATABASE - creates a new database<br />ALTER DATABASE - modifies a database<br />CREATE TABLE - creates a new table<br />ALTER TABLE - modifies a table<br />DROP TABLE - deletes a table<br />CREATE INDEX - creates an index (search key)<br />DROP INDEX - deletes an index <br />« PreviousNext Chapter »<br />SQL SELECT Statement<br />« PreviousNext Chapter »<br />This chapter will explain the SELECT and the SELECT * statements.<br />The SQL SELECT Statement<br />The SELECT statement is used to select data from a database.<br />The result is stored in a result table, called the result-set.<br />SQL SELECT Syntax<br />SELECT column_name(s)FROM table_name<br />and<br />SELECT * FROM table_name<br />Note: SQL is not case sensitive. SELECT is the same as select.<br />An SQL SELECT Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the content of the columns named \" LastName\" and \" FirstName\" from the table above.<br />We use the following SELECT statement:<br />SELECT LastName,FirstName FROM Persons<br />The result-set will look like this:<br />LastNameFirstNameHansenOlaSvendsonTovePettersenKari<br />SELECT * Example<br />Now we want to select all the columns from the \" Persons\" table.<br />We use the following SELECT statement: <br />SELECT * FROM Persons<br />Tip: The asterisk (*) is a quick way of selecting all columns!<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Navigation in a Result-set<br />Most database software systems allow navigation in the result-set with programming functions, like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.<br />Programming functions like these are not a part of this tutorial. To learn about accessing data with function calls, please visit our ADO tutorial or our PHP tutorial.<br />« PreviousNext Chapter »<br />SQL SELECT DISTINCT Statement<br />« PreviousNext Chapter »<br />This chapter will explain the SELECT DISTINCT statement.<br />The SQL SELECT DISTINCT Statement<br />In a table, some of the columns may contain duplicate values. This is not a problem; however, sometimes you will want to list only the different (distinct) values in a table.<br />The DISTINCT keyword can be used to return only distinct (different) values.<br />SQL SELECT DISTINCT Syntax<br />SELECT DISTINCT column_name(s)FROM table_name<br />SELECT DISTINCT Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select only the distinct values from the column named \" City\" from the table above.<br />We use the following SELECT statement:<br />SELECT DISTINCT City FROM Persons<br />The result-set will look like this:<br />CitySandnesStavanger<br />« PreviousNext Chapter »<br />SQL WHERE Clause<br />« PreviousNext Chapter »<br />The WHERE clause is used to filter records.<br />The WHERE Clause <br />The WHERE clause is used to extract only those records that fulfill a specified criterion.<br />SQL WHERE Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_name operator value<br />WHERE Clause Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select only the persons living in the city \" Sandnes\" from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City='Sandnes'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Quotes Around Text Fields<br />SQL uses single quotes around text values (most database systems will also accept double quotes).<br />Although, numeric values should not be enclosed in quotes.<br />For text values:<br />This is correct:SELECT * FROM Persons WHERE FirstName='Tove'This is wrong:SELECT * FROM Persons WHERE FirstName=Tove<br />For numeric values:<br />This is correct:SELECT * FROM Persons WHERE Year=1965This is wrong:SELECT * FROM Persons WHERE Year='1965'<br />Operators Allowed in the WHERE Clause<br />With the WHERE clause, the following operators can be used:<br />OperatorDescription=Equal<>Not equal>Greater than<Less than>=Greater than or equal<=Less than or equalBETWEENBetween an inclusive rangeLIKESearch for a patternINIf you know the exact value you want to return for at least one of the columns<br />Note: In some versions of SQL the <> operator may be written as !=<br />« PreviousNext Chapter »<br />SQL AND & OR Operators<br />« PreviousNext Chapter »<br />The AND & OR operators are used to filter records based on more than one condition.<br />The AND & OR Operators<br />The AND operator displays a record if both the first condition and the second condition is true.<br />The OR operator displays a record if either the first condition or the second condition is true.<br />AND Operator Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select only the persons with the first name equal to \" Tove\" AND the last name equal to \" Svendson\" :<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE FirstName='Tove'AND LastName='Svendson'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes<br />OR Operator Example<br />Now we want to select only the persons with the first name equal to \" Tove\" OR the first name equal to \" Ola\" :<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE FirstName='Tove'OR FirstName='Ola'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Combining AND & OR<br />You can also combine AND and OR (use parenthesis to form complex expressions).<br />Now we want to select only the persons with the last name equal to \" Svendson\" AND the first name equal to \" Tove\" OR to \" Ola\" :<br />We use the following SELECT statement:<br />SELECT * FROM Persons WHERELastName='Svendson'AND (FirstName='Tove' OR FirstName='Ola')<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes<br />« PreviousNext Chapter »<br />SQL ORDER BY Keyword<br />« PreviousNext Chapter »<br />The ORDER BY keyword is used to sort the result-set.<br />The ORDER BY Keyword<br />The ORDER BY keyword is used to sort the result-set by a specified column.<br />The ORDER BY keyword sort the records in ascending order by default.<br />If you want to sort the records in a descending order, you can use the DESC keyword.<br />SQL ORDER BY Syntax<br />SELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESC<br />ORDER BY Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23Stavanger<br />Now we want to select all the persons from the table above, however, we want to sort the persons by their last name.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsORDER BY LastName<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes4NilsenTomVingvn 23Stavanger3PettersenKariStorgt 20Stavanger2SvendsonToveBorgvn 23Sandnes<br />ORDER BY DESC Example<br />Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsORDER BY LastName DESC<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23Stavanger1HansenOlaTimoteivn 10Sandnes<br />« PreviousNext Chapter »<br />Your browser does not support inline frames or is currently configured not to display inline frames. <br />SQL INSERT INTO Statement<br />« PreviousNext Chapter »<br />The INSERT INTO statement is used to insert new records in a table.<br />The INSERT INTO Statement<br />The INSERT INTO statement is used to insert a new row in a table.<br />SQL INSERT INTO Syntax<br />It is possible to write the INSERT INTO statement in two forms. <br />The first form doesn't specify the column names where the data will be inserted, only their values:<br />INSERT INTO table_nameVALUES (value1, value2, value3,...)<br />The second form specifies both the column names and the values to be inserted:<br />INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)<br />SQL INSERT INTO Example<br />We have the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to insert a new row in the \" Persons\" table.<br />We use the following SQL statement:<br />INSERT INTO PersonsVALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')<br />The \" Persons\" table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger<br />Insert Data Only in Specified Columns<br />It is also possible to only add data in specific columns.<br />The following SQL statement will add a new row, but only add data in the \" P_Id\" , \" LastName\" and the \" FirstName\" columns:<br />INSERT INTO Persons (P_Id, LastName, FirstName)VALUES (5, 'Tjessem', 'Jakob')<br />The \" Persons\" table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakob  <br />« PreviousNext Chapter »<br />SQL UPDATE Statement<br />« PreviousNext Chapter »<br />The UPDATE statement is used to update records in a table.<br />The UPDATE Statement<br />The UPDATE statement is used to update existing records in a table.<br />SQL UPDATE Syntax<br />UPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value<br />Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!<br />SQL UPDATE Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakob  <br />Now we want to update the person \" Tjessem, Jakob\" in the \" Persons\" table.<br />We use the following SQL statement:<br />UPDATE PersonsSET Address='Nissestien 67', City='Sandnes'WHERE LastName='Tjessem' AND FirstName='Jakob'<br />The \" Persons\" table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakobNissestien 67Sandnes<br />SQL UPDATE Warning<br />Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:<br />UPDATE PersonsSET Address='Nissestien 67', City='Sandnes'<br />The \" Persons\" table would have looked like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaNissestien 67Sandnes2SvendsonToveNissestien 67Sandnes3PettersenKariNissestien 67Sandnes4NilsenJohanNissestien 67Sandnes5TjessemJakobNissestien 67Sandnes<br />« PreviousNext Chapter »<br />SQL DELETE Statement<br />« PreviousNext Chapter »<br />The DELETE statement is used to delete records in a table.<br />The DELETE Statement<br />The DELETE statement is used to delete rows in a table.<br />SQL DELETE Syntax<br />DELETE FROM table_nameWHERE some_column=some_value<br />Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!<br />SQL DELETE Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger5TjessemJakobNissestien 67Sandnes<br />Now we want to delete the person \" Tjessem, Jakob\" in the \" Persons\" table.<br />We use the following SQL statement:<br />DELETE FROM PersonsWHERE LastName='Tjessem' AND FirstName='Jakob'<br />The \" Persons\" table will now look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenJohanBakken 2Stavanger<br />Delete All Rows<br />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:<br />DELETE FROM table_nameorDELETE * FROM table_name<br />Note: Be very careful when deleting records. You cannot undo this statement!<br />« PreviousNext Chapter »<br />SQL Try It<br />« PreviousNext Chapter »<br />Test your SQL Skills<br />On this page you can test your SQL skills.<br />We will use the Customers table in the Northwind database:<br />CompanyNameContactNameAddressCityAlfreds Futterkiste Maria Anders Obere Str. 57 Berlin Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. Ernst Handel Roland Mendel Kirchgasse 6 Graz FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona Island Trading Helen Bennett Garden House Crowther Way Cowes Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo North/South Simon Crowther South House 300 Queensbridge London Paris spécialités Marie Bertrand 265, boulevard Charonne Paris Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque Simons bistro Jytte Petersen Vinbæltet 34 København The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland Vaffeljernet Palle Ibsen Smagsløget 45 Århus Wolski Zajazd Zbyszek Piestrzeniewicz ul. Filtrowa 68 Warszawa <br />To preserve space, the table above is a subset of the Customers table used in the example below.<br />Try it Yourself<br />To see how SQL works, you can copy the SQL statements below and paste them into the textarea, or you can make your own SQL statements.<br />SELECT * FROM customers<br />SELECT CompanyName, ContactName FROM customers<br />SELECT * FROM customers WHERE companyname LIKE 'a%'<br />SELECT CompanyName, ContactNameFROM customersWHERE CompanyName > 'a'<br />When using SQL on text data, \" alfred\" is greater than \" a\" (like in a dictionary).<br />SELECT CompanyName, ContactNameFROM customersWHERE CompanyName > 'g'AND ContactName > 'g'<br />Top of Form<br />Bottom of Form<br />« PreviousNext Chapter »<br />SQL TOP Clause« PreviousNext Chapter »The TOP ClauseThe TOP clause is used to specify the number of records to return.The TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance.Note: Not all database systems support the TOP clause.SQL Server SyntaxSELECT TOP number|percent column_name(s)FROM table_nameSQL SELECT TOP Equivalent in MySQL and OracleMySQL SyntaxSELECT column_name(s)FROM table_nameLIMIT numberExampleSELECT *FROM PersonsLIMIT 5Oracle SyntaxSELECT column_name(s)FROM table_nameWHERE ROWNUM <= numberExampleSELECT *FROM PersonsWHERE ROWNUM <=5SQL TOP ExampleThe \" Persons\" table:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23StavangerNow we want to select only the two first records in the table above.We use the following SELECT statement:SELECT TOP 2 * FROM PersonsThe result-set will look like this:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23SandnesSQL TOP PERCENT ExampleThe \" Persons\" table:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger4NilsenTomVingvn 23StavangerNow we want to select only 50% of the records in the table above.We use the following SELECT statement:SELECT TOP 50 PERCENT * FROM PersonsThe result-set will look like this:P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes« PreviousNext Chapter »<br />SQL LIKE Operator<br />« PreviousNext Chapter »<br />The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.<br />The LIKE Operator<br />The LIKE operator is used to search for a specified pattern in a column.<br />SQL LIKE Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern<br />LIKE Operator Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the persons living in a city that starts with \" s\" from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE 's%'<br />The \" %\" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Next, we want to select the persons living in a city that ends with an \" s\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE '%s'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Next, we want to select the persons living in a city that contains the pattern \" tav\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE '%tav%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity3PettersenKariStorgt 20Stavanger<br />It is also possible to select the persons living in a city that NOT contains the pattern \" tav\" from the \" Persons\" table, by using the NOT keyword.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City NOT LIKE '%tav%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />« PreviousNext Chapter »<br />SQL Wildcards<br />« PreviousNext Chapter »<br />SQL wildcards can be used when searching for data in a database.<br />SQL Wildcards <br />SQL wildcards can substitute for one or more characters when searching for data in a database.<br />SQL wildcards must be used with the SQL LIKE operator.<br />With SQL, the following wildcards can be used:<br />WildcardDescription%A substitute for zero or more characters _A substitute for exactly one character[charlist]Any single character in charlist[^charlist] or[!charlist]Any single character not in charlist<br />SQL Wildcard Examples<br />We have the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Using the % Wildcard<br />Now we want to select the persons living in a city that starts with \" sa\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE 'sa%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Next, we want to select the persons living in a city that contains the pattern \" nes\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE City LIKE '%nes%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes<br />Using the _ Wildcard<br />Now we want to select the persons with a first name that starts with any character, followed by \" la\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE FirstName LIKE '_la'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes<br />Next, we want to select the persons with a last name that starts with \" S\" , followed by any character, followed by \" end\" , followed by any character, followed by \" on\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName LIKE 'S_end_on'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes<br />Using the [charlist] Wildcard<br />Now we want to select the persons with a last name that starts with \" b\" or \" s\" or \" p\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName LIKE '[bsp]%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Next, we want to select the persons with a last name that do not start with \" b\" or \" s\" or \" p\" from the \" Persons\" table.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName LIKE '[!bsp]%'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes<br />« PreviousNext Chapter »<br />SQL IN Operator<br />« PreviousNext Chapter »<br />The IN Operator<br />The IN operator allows you to specify multiple values in a WHERE clause.<br />SQL IN Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_name IN (value1,value2,...)<br />IN Operator Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the persons with a last name equal to \" Hansen\" or \" Pettersen\" from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastName IN ('Hansen','Pettersen')<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes3PettersenKariStorgt 20Stavanger<br />« PreviousNext Chapter »<br />SQL BETWEEN Operator<br />« PreviousNext Chapter »<br />The BETWEEN operator is used in a WHERE clause to select a range of data between two values.<br />The BETWEEN Operator<br />The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.<br />SQL BETWEEN Syntax<br />SELECT column_name(s)FROM table_nameWHERE column_nameBETWEEN value1 AND value2<br />BETWEEN Operator Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the persons with a last name alphabetically between \" Hansen\" and \" Pettersen\" from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM PersonsWHERE LastNameBETWEEN 'Hansen' AND 'Pettersen'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes<br />Note: The BETWEEN operator is treated differently in different databases.<br />In some databases, persons with the LastName of \" Hansen\" or \" Pettersen\" will not be listed, because the BETWEEN operator only selects fields that are between and excluding the test values).<br />In other databases, persons with the LastName of \" Hansen\" or \" Pettersen\" will be listed, because the BETWEEN operator selects fields that are between and including the test values).<br />And in other databases, persons with the LastName of \" Hansen\" will be listed, but \" Pettersen\" will not be listed (like the example above), because the BETWEEN operator selects fields between the test values, including the first test value and excluding the last test value.<br />Therefore: Check how your database treats the BETWEEN operator.<br />Example 2<br />To display the persons outside the range in the previous example, use NOT BETWEEN:<br />SELECT * FROM PersonsWHERE LastNameNOT BETWEEN 'Hansen' AND 'Pettersen'<br />The result-set will look like this:<br />P_IdLastNameFirstNameAddressCity2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />« PreviousNext Chapter »<br />SQL Alias<br />« PreviousNext Chapter »<br />With SQL, an alias name can be given to a table or to a column.<br />SQL Alias<br />You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.<br />An alias name could be anything, but usually it is short.<br />SQL Alias Syntax for Tables<br />SELECT column_name(s)FROM table_nameAS alias_name<br />SQL Alias Syntax for Columns<br />SELECT column_name AS alias_nameFROM table_name<br />Alias Example<br />Assume we have a table called \" Persons\" and another table called \" Product_Orders\" . We will give the table aliases of \" p\" and \" po\" respectively.<br />Now we want to list all the orders that \" Ola Hansen\" is responsible for.<br />We use the following SELECT statement:<br />SELECT po.OrderID, p.LastName, p.FirstNameFROM Persons AS p,Product_Orders AS poWHERE p.LastName='Hansen' AND p.FirstName='Ola'<br />The same SELECT statement without aliases:<br />SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstNameFROM Persons,Product_OrdersWHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'<br />As you'll see from the two SELECT statements above; aliases can make queries easier to both write and to read.<br />« PreviousNext Chapter »<br />SQL Joins<br />« PreviousNext Chapter »<br />SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.<br />SQL JOIN<br />The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.<br />Tables in a database are often related to each other with keys.<br />A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.<br />Look at the \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Note that the \" P_Id\" column is the primary key in the \" Persons\" table. This means that no two rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same name.<br />Next, we have the \" Orders\" table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Note that the \" O_Id\" column is the primary key in the \" Orders\" table and that the \" P_Id\" column refers to the persons in the \" Persons\" table without using their names.<br />Notice that the relationship between the two tables above is the \" P_Id\" column.<br />Different SQL JOINs<br />Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.<br />JOIN: Return rows when there is at least one match in both tables<br />LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table<br />RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table<br />FULL JOIN: Return rows when there is a match in one of the tables<br />« PreviousNext Chapter »<br />SQL INNER JOIN Keyword<br />« PreviousNext Chapter »<br />SQL INNER JOIN Keyword<br />The INNER JOIN keyword return rows when there is at least one match in both tables.<br />SQL INNER JOIN Syntax<br />SELECT column_name(s)FROM table_name1INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />PS: INNER JOIN is the same as JOIN.<br />SQL INNER JOIN Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \" Orders\" table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the persons with any orders.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678<br />The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in \" Persons\" that do not have matches in \" Orders\" , those rows will NOT be listed.<br />« PreviousNext Chapter »<br />SQL LEFT JOIN Keyword<br />« PreviousNext Chapter »<br />SQL LEFT JOIN Keyword<br />The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).<br />SQL LEFT JOIN Syntax<br />SELECT column_name(s)FROM table_name1LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.<br />SQL LEFT JOIN Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \" Orders\" table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the persons and their orders - if any, from the tables above.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsLEFT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678SvendsonTove <br />The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in the right table (Orders).<br />« Previous<br />SQL RIGHT JOIN Keyword<br />« PreviousNext Chapter »<br />SQL RIGHT JOIN Keyword<br />The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).<br />SQL RIGHT JOIN Syntax<br />SELECT column_name(s)FROM table_name1RIGHT JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.<br />SQL RIGHT JOIN Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \" Orders\" table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the orders with containing persons - if any, from the tables above.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsRIGHT JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678  34764<br />The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Persons).<br />« PreviousNext Chapter »<br />SQL FULL JOIN Keyword<br />« PreviousNext Chapter »<br />SQL FULL JOIN Keyword<br />The FULL JOIN keyword return rows when there is a match in one of the tables.<br />SQL FULL JOIN Syntax<br />SELECT column_name(s)FROM table_name1FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name<br />SQL FULL JOIN Example<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \" Orders\" table:<br />O_IdOrderNoP_Id177895324467833224561424562153476415<br />Now we want to list all the persons and their orders, and all the orders with their persons.<br />We use the following SELECT statement:<br />SELECT Persons.LastName, Persons.FirstName, Orders.OrderNoFROM PersonsFULL JOIN OrdersON Persons.P_Id=Orders.P_IdORDER BY Persons.LastName<br />The result-set will look like this:<br />LastNameFirstNameOrderNoHansenOla22456HansenOla24562PettersenKari77895PettersenKari44678SvendsonTove   34764<br />The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are rows in \" Persons\" that do not have matches in \" Orders\" , or if there are rows in \" Orders\" that do not have matches in \" Persons\" , those rows will be listed as well.<br />« PreviousNext Chapter »<br />SQL UNION Operator<br />« PreviousNext Chapter »<br />The SQL UNION operator combines two or more SELECT statements.<br />The SQL UNION Operator<br />The UNION operator is used to combine the result-set of two or more SELECT statements.<br />Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.<br />SQL UNION Syntax<br />SELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2<br />Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.<br />SQL UNION ALL Syntax<br />SELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2<br />PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.<br />SQL UNION Example<br />Look at the following tables:<br />\" Employees_Norway\" :<br />E_IDE_Name01Hansen, Ola02Svendson, Tove03Svendson, Stephen04Pettersen, Kari<br />\" Employees_USA\" :<br />E_IDE_Name01Turner, Sally02Kent, Clark03Svendson, Stephen04Scott, Stephen<br />Now we want to list all the different employees in Norway and USA.<br />We use the following SELECT statement:<br />SELECT E_Name FROM Employees_NorwayUNIONSELECT E_Name FROM Employees_USA<br />The result-set will look like this:<br />E_NameHansen, OlaSvendson, ToveSvendson, StephenPettersen, KariTurner, SallyKent, ClarkScott, Stephen<br />Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.<br />SQL UNION ALL Example<br />Now we want to list all employees in Norway and USA:<br />SELECT E_Name FROM Employees_NorwayUNION ALLSELECT E_Name FROM Employees_USA<br />Result<br />E_NameHansen, OlaSvendson, ToveSvendson, StephenPettersen, KariTurner, SallyKent, ClarkSvendson, StephenScott, Stephen<br />« PreviousNext Chapter »<br />SQL SELECT INTO Statement<br />« PreviousNext Chapter »<br />The SQL SELECT INTO statement can be used to create backup copies of tables.<br />The SQL SELECT INTO Statement<br />The SELECT INTO statement selects data from one table and inserts it into a different table. <br />The SELECT INTO statement is most often used to create backup copies of tables.<br />SQL SELECT INTO Syntax<br />We can select all columns into the new table:<br />SELECT *INTO new_table_name [IN externaldatabase]FROM old_tablename<br />Or we can select only the columns we want into the new table:<br />SELECT column_name(s)INTO new_table_name [IN externaldatabase]FROM old_tablename<br />SQL SELECT INTO Example<br />Make a Backup Copy - Now we want to make an exact copy of the data in our \" Persons\" table.<br />We use the following SQL statement:<br />SELECT *INTO Persons_BackupFROM Persons<br />We can also use the IN clause to copy the table into another database:<br />SELECT *INTO Persons_Backup IN 'Backup.mdb'FROM Persons<br />We can also copy only a few fields into the new table:<br />SELECT LastName,FirstNameINTO Persons_BackupFROM Persons<br />SQL SELECT INTO - With a WHERE Clause<br />We can also add a WHERE clause.<br />The following SQL statement creates a \" Persons_Backup\" table with only the persons who lives in the city \" Sandnes\" :<br />SELECT LastName,FirstnameINTO Persons_BackupFROM PersonsWHERE City='Sandnes'<br />SQL SELECT INTO - Joined Tables<br />Selecting data from more than one table is also possible.<br />The following example creates a \" Persons_Order_Backup\" table contains data from the two tables \" Persons\" and \" Orders\" :<br />SELECT Persons.LastName,Orders.OrderNoINTO Persons_Order_BackupFROM PersonsINNER JOIN OrdersON Persons.P_Id=Orders.P_Id<br />« PreviousNext Chapter »<br />SQL CREATE DATABASE Statement<br />« PreviousNext Chapter »<br />The CREATE DATABASE Statement<br />The CREATE DATABASE statement is used to create a database.<br />SQL CREATE DATABASE Syntax<br />CREATE DATABASE database_name<br />CREATE DATABASE Example<br />Now we want to create a database called \" my_db\" .<br />We use the following CREATE DATABASE statement:<br />CREATE DATABASE my_db<br />Database tables can be added with the CREATE TABLE statement.<br />« PreviousNext Chapter »<br />SQL CREATE TABLE Statement<br />« PreviousNext Chapter »<br />The CREATE TABLE Statement<br />The CREATE TABLE statement is used to create a table in a database.<br />SQL CREATE TABLE Syntax<br />CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,....)<br />The data type specifies what type of data the column can hold. For a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.<br />CREATE TABLE Example<br />Now we want to create a table called \" Persons\" that contains five columns: P_Id, LastName, FirstName, Address, and City.<br />We use the following CREATE TABLE statement:<br />CREATE TABLE Persons(P_Id int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255))<br />The P_Id column is of type int and will hold a number. The LastName, FirstName, Address, and City columns are of type varchar with a maximum length of 255 characters.<br />The empty \" Persons\" table will now look like this:<br />P_IdLastNameFirstNameAddressCity     <br />The empty table can be filled with data with the INSERT INTO statement.<br />« PreviousNext Chapter »<br />SQL Constraints<br />« PreviousNext Chapter »<br />SQL Constraints<br />Constraints are used to limit the type of data that can go into a table.<br />Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).<br />We will focus on the following constraints:<br />NOT NULL<br />UNIQUE<br />PRIMARY KEY<br />FOREIGN KEY<br />CHECK<br />DEFAULT<br />The next chapters will describe each constraint in details.<br />« PreviousNext Chapter »<br />SQL NOT NULL Constraint<br />« PreviousNext Chapter »<br />By default, a table column can hold NULL values.<br />SQL NOT NULL Constraint<br />The NOT NULL constraint enforces a column to NOT accept NULL values.<br />The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.<br />The following SQL enforces the \" P_Id\" column and the \" LastName\" column to not accept NULL values:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />« PreviousNext Chapter »<br />SQL UNIQUE Constraint<br />« PreviousNext Chapter »<br />SQL UNIQUE Constraint<br />The UNIQUE constraint uniquely identifies each record in a database table.<br />The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.<br />A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.<br />Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.<br />SQL UNIQUE Constraint on CREATE TABLE<br />The following SQL creates a UNIQUE constraint on the \" P_Id\" column when the \" Persons\" table is created:<br />MySQL:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),UNIQUE (P_Id))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL UNIQUE,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName))<br />SQL UNIQUE Constraint on ALTER TABLE<br />To create a UNIQUE constraint on the \" P_Id\" column when the table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD UNIQUE (P_Id)<br />To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)<br />To DROP a UNIQUE Constraint<br />To drop a UNIQUE constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsDROP INDEX uc_PersonID<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsDROP CONSTRAINT uc_PersonID<br />« PreviousNext Chapter <br />SQL PRIMARY KEY Constraint<br />« PreviousNext Chapter »<br />SQL PRIMARY KEY Constraint<br />The PRIMARY KEY constraint uniquely identifies each record in a database table.<br />Primary keys must contain unique values.<br />A primary key column cannot contain NULL values.<br />Each table should have a primary key, and each table can have only ONE primary key.<br />SQL PRIMARY KEY Constraint on CREATE TABLE<br />The following SQL creates a PRIMARY KEY on the \" P_Id\" column when the \" Persons\" table is created:<br />MySQL:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName))<br />SQL PRIMARY KEY Constraint on ALTER TABLE<br />To create a PRIMARY KEY constraint on the \" P_Id\" column when the table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD PRIMARY KEY (P_Id)<br />To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)<br />Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).<br />To DROP a PRIMARY KEY Constraint<br />To drop a PRIMARY KEY constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsDROP PRIMARY KEY<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID<br />« PreviousNext Chapter »<br />SQL FOREIGN KEY Constraint<br />« PreviousNext Chapter »<br />SQL FOREIGN KEY Constraint<br />A FOREIGN KEY in one table points to a PRIMARY KEY in another table.<br />Let's illustrate the foreign key with an example. Look at the following two tables:<br />The \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />The \" Orders\" table:<br />O_IdOrderNoP_Id1778953244678332245624245621<br />Note that the \" P_Id\" column in the \" Orders\" table points to the \" P_Id\" column in the \" Persons\" table.<br />The \" P_Id\" column in the \" Persons\" table is the PRIMARY KEY in the \" Persons\" table.<br />The \" P_Id\" column in the \" Orders\" table is a FOREIGN KEY in the \" Orders\" table.<br />The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.<br />The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.<br />SQL FOREIGN KEY Constraint on CREATE TABLE<br />The following SQL creates a FOREIGN KEY on the \" P_Id\" column when the \" Orders\" table is created:<br />MySQL:<br />CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,PRIMARY KEY (O_Id),FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Orders(O_Id int NOT NULL PRIMARY KEY,OrderNo int NOT NULL,P_Id int FOREIGN KEY REFERENCES Persons(P_Id))<br />To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,PRIMARY KEY (O_Id),CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)REFERENCES Persons(P_Id))<br />SQL FOREIGN KEY Constraint on ALTER TABLE<br />To create a FOREIGN KEY constraint on the \" P_Id\" column when the \" Orders\" table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE OrdersADD FOREIGN KEY (P_Id)REFERENCES Persons(P_Id)<br />To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE OrdersADD CONSTRAINT fk_PerOrdersFOREIGN KEY (P_Id)REFERENCES Persons(P_Id)<br />To DROP a FOREIGN KEY Constraint<br />To drop a FOREIGN KEY constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE OrdersDROP FOREIGN KEY fk_PerOrders<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE OrdersDROP CONSTRAINT fk_PerOrders<br />« PreviousNext Chapter »<br />SQL CHECK Constraint<br />« PreviousNext Chapter »<br />SQL CHECK Constraint<br />The CHECK constraint is used to limit the value range that can be placed in a column.<br />If you define a CHECK constraint on a single column it allows only certain values for this column.<br />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.<br />SQL CHECK Constraint on CREATE TABLE<br />The following SQL creates a CHECK constraint on the \" P_Id\" column when the \" Persons\" table is created. The CHECK constraint specifies that the column \" P_Id\" must only include integers greater than 0.<br />My SQL:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CHECK (P_Id>0))<br />SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes'))<br />SQL CHECK Constraint on ALTER TABLE<br />To create a CHECK constraint on the \" P_Id\" column when the table is already created, use the following SQL:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CHECK (P_Id>0)<br />To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:<br />MySQL / SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')<br />To DROP a CHECK Constraint<br />To drop a CHECK constraint, use the following SQL:<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsDROP CONSTRAINT chk_Person<br />« PreviousNext Chapter »<br />SQL DEFAULT Constraint<br />« PreviousNext Chapter »<br />SQL DEFAULT Constraint<br />The DEFAULT constraint is used to insert a default value into a column.<br />The default value will be added to all new records, if no other value is specified.<br />SQL DEFAULT Constraint on CREATE TABLE<br />The following SQL creates a DEFAULT constraint on the \" City\" column when the \" Persons\" table is created:<br />My SQL / SQL Server / Oracle / MS Access:<br />CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255) DEFAULT 'Sandnes')<br />The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():<br />CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,OrderDate date DEFAULT GETDATE())<br />SQL DEFAULT Constraint on ALTER TABLE<br />To create a DEFAULT constraint on the \" City\" column when the table is already created, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsALTER City SET DEFAULT 'SANDNES'<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsALTER COLUMN City SET DEFAULT 'SANDNES'<br />To DROP a DEFAULT Constraint<br />To drop a DEFAULT constraint, use the following SQL:<br />MySQL:<br />ALTER TABLE PersonsALTER City DROP DEFAULT<br />SQL Server / Oracle / MS Access:<br />ALTER TABLE PersonsALTER COLUMN City DROP DEFAULT<br />« PreviousNext Chapter »<br />SQL CREATE INDEX Statement<br />« PreviousNext Chapter »<br />The CREATE INDEX statement is used to create indexes in tables.<br />Indexes allow the database application to find data fast; without reading the whole table.<br />Indexes<br />An index can be created in a table to find data more quickly and efficiently.<br />The users cannot see the indexes, they are just used to speed up searches/queries.<br />Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.<br />SQL CREATE INDEX Syntax<br />Creates an index on a table. Duplicate values are allowed:<br />CREATE INDEX index_nameON table_name (column_name)<br />SQL CREATE UNIQUE INDEX Syntax<br />Creates a unique index on a table. Duplicate values are not allowed:<br />CREATE UNIQUE INDEX index_nameON table_name (column_name)<br />Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.<br />CREATE INDEX Example<br />The SQL statement below creates an index named \" PIndex\" on the \" LastName\" column in the \" Persons\" table:<br />CREATE INDEX PIndexON Persons (LastName)<br />If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:<br />CREATE INDEX PIndexON Persons (LastName, FirstName)<br />« PreviousNext Chapter <br />SQL DROP INDEX, DROP TABLE, and DROP DATABASE<br />« PreviousNext Chapter »<br />Indexes, tables, and databases can easily be deleted/removed with the DROP statement.<br />The DROP INDEX Statement<br />The DROP INDEX statement is used to delete an index in a table.<br />DROP INDEX Syntax for MS Access:<br />DROP INDEX index_name ON table_name<br />DROP INDEX Syntax for MS SQL Server:<br />DROP INDEX table_name.index_name<br />DROP INDEX Syntax for DB2/Oracle:<br />DROP INDEX index_name<br />DROP INDEX Syntax for MySQL:<br />ALTER TABLE table_name DROP INDEX index_name<br />The DROP TABLE Statement<br />The DROP TABLE statement is used to delete a table.<br />DROP TABLE table_name<br />The DROP DATABASE Statement<br />The DROP DATABASE statement is used to delete a database.<br />DROP DATABASE database_name<br />The TRUNCATE TABLE Statement<br />What if we only want to delete the data inside the table, and not the table itself?<br />Then, use the TRUNCATE TABLE statement:<br />TRUNCATE TABLE table_name<br />« PreviousNext Chapter »<br />SQL ALTER TABLE Statement<br />« PreviousNext Chapter »<br />The ALTER TABLE Statement<br />The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.<br />SQL ALTER TABLE Syntax<br />To add a column in a table, use the following syntax:<br />ALTER TABLE table_nameADD column_name datatype<br />To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):<br />ALTER TABLE table_nameDROP COLUMN column_name<br />To change the data type of a column in a table, use the following syntax:<br />ALTER TABLE table_nameALTER COLUMN column_name datatype<br />SQL ALTER TABLE Example<br />Look at the \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to add a column named \" DateOfBirth\" in the \" Persons\" table.<br />We use the following SQL statement:<br />ALTER TABLE PersonsADD DateOfBirth date<br />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 MS Access, MySQL, and SQL Server, go to our complete Data Types reference.<br />The \" Persons\" table will now like this:<br />P_IdLastNameFirstNameAddressCityDateOfBirth1HansenOlaTimoteivn 10Sandnes 2SvendsonToveBorgvn 23Sandnes 3PettersenKariStorgt 20Stavanger <br />Change Data Type Example<br />Now we want to change the data type of the column named \" DateOfBirth\" in the \" Persons\" table.<br />We use the following SQL statement:<br />ALTER TABLE PersonsALTER COLUMN DateOfBirth year<br />Notice that the \" DateOfBirth\" column is now of type year and is going to hold a year in a two-digit or four-digit format.<br />DROP COLUMN Example<br />Next, we want to delete the column named \" DateOfBirth\" in the \" Persons\" table.<br />We use the following SQL statement:<br />ALTER TABLE PersonsDROP COLUMN DateOfBirth<br />The \" Persons\" table will now like this:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />« PreviousNext Chapter <br />SQL AUTO INCREMENT Field<br />« PreviousNext Chapter »<br />Auto-increment allows a unique number to be generated when a new record is inserted into a table.<br />AUTO INCREMENT a Field<br />Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.<br />We would like to create an auto-increment field in a table.<br />Syntax for MySQL<br />The following SQL statement defines the \" P_Id\" column to be an auto-increment primary key field in the \" Persons\" table:<br />CREATE TABLE Persons(P_Id int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))<br />MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature.<br />By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.<br />To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:<br />ALTER TABLE Persons AUTO_INCREMENT=100<br />To insert a new record into the \" Persons\" table, we will not have to specify a value for the \" P_Id\" column (a unique value will be added automatically):<br />INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')<br />The SQL statement above would insert a new record into the \" Persons\" table. The \" P_Id\" column would be assigned a unique value. The \" FirstName\" column would be set to \" Lars\" and the \" LastName\" column would be set to \" Monsen\" .<br />Syntax for SQL Server<br />The following SQL statement defines the \" P_Id\" column to be an auto-increment primary key field in the \" Persons\" table:<br />CREATE TABLE Persons(P_Id int PRIMARY KEY IDENTITY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. <br />By default, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.<br />To specify that the \" P_Id\" column should start at value 10 and increment by 5, change the identity to IDENTITY(10,5).<br />To insert a new record into the \" Persons\" table, we will not have to specify a value for the \" P_Id\" column (a unique value will be added automatically):<br />INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')<br />The SQL statement above would insert a new record into the \" Persons\" table. The \" P_Id\" column would be assigned a unique value. The \" FirstName\" column would be set to \" Lars\" and the \" LastName\" column would be set to \" Monsen\" .<br />Syntax for Access<br />The following SQL statement defines the \" P_Id\" column to be an auto-increment primary key field in the \" Persons\" table:<br />CREATE TABLE Persons(P_Id PRIMARY KEY AUTOINCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))<br />The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature. <br />By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record.<br />To specify that the \" P_Id\" column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10,5).<br />To insert a new record into the \" Persons\" table, we will not have to specify a value for the \" P_Id\" column (a unique value will be added automatically):<br />INSERT INTO Persons (FirstName,LastName)VALUES ('Lars','Monsen')<br />The SQL statement above would insert a new record into the \" Persons\" table. The \" P_Id\" column would be assigned a unique value. The \" FirstName\" column would be set to \" Lars\" and the \" LastName\" column would be set to \" Monsen\" .<br />Syntax for Oracle<br />In Oracle the code is a little bit more tricky.<br />You will have to create an auto-increment field with the sequence object (this object generates a number sequence).<br />Use the following CREATE SEQUENCE syntax:<br />CREATE SEQUENCE seq_personMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10<br />The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.<br />To insert a new record into the \" Persons\" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):<br />INSERT INTO Persons (P_Id,FirstName,LastName)VALUES (seq_person.nextval,'Lars','Monsen')<br />The SQL statement above would insert a new record into the \" Persons\" table. The \" P_Id\" column would be assigned the next number from the seq_person sequence. The \" FirstName\" column would be set to \" Lars\" and the \" LastName\" column would be set to \" Monsen\" .<br />« PreviousNext Chapter <br />SQL Views<br />« PreviousNext Chapter »<br />A view is a virtual table.<br />This chapter shows how to create, update, and delete a view. <br />SQL CREATE VIEW Statement<br />In SQL, a view is a virtual table based on the result-set of an SQL statement.<br />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.<br />You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.<br />SQL CREATE VIEW Syntax<br />CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition<br />Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.<br />SQL CREATE VIEW Examples<br />If you have the Northwind database you can see that it has several views installed by default.<br />The view \" Current Product List\" lists all active products (products that are not discontinued) from the \" Products\" table. The view is created with the following SQL:<br />CREATE VIEW [Current Product List] ASSELECT ProductID,ProductNameFROM ProductsWHERE Discontinued=No<br />We can query the view above as follows:<br />SELECT * FROM [Current Product List]<br />Another view in the Northwind sample database selects every product in the \" Products\" table with a unit price higher than the average unit price:<br />CREATE VIEW [Products Above Average Price] ASSELECT ProductName,UnitPriceFROM ProductsWHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)<br />We can query the view above as follows:<br />SELECT * FROM [Products Above Average Price]<br />Another view in the Northwind database calculates the total sale for each category in 1997. Note that this view selects its data from another view called \" Product Sales for 1997\" :<br />CREATE VIEW [Category Sales For 1997] ASSELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySalesFROM [Product Sales for 1997]GROUP BY CategoryName<br />We can query the view above as follows:<br />SELECT * FROM [Category Sales For 1997]<br />We can also add a condition to the query. Now we want to see the total sale only for the category \" Beverages\" :<br />SELECT * FROM [Category Sales For 1997]WHERE CategoryName='Beverages'<br />SQL Updating a View<br />You can update a view by using the following syntax:<br />SQL CREATE OR REPLACE VIEW Syntax<br />CREATE OR REPLACE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition<br />Now we want to add the \" Category\" column to the \" Current Product List\" view. We will update the view with the following SQL:<br />CREATE VIEW [Current Product List] ASSELECT ProductID,ProductName,CategoryFROM ProductsWHERE Discontinued=No<br />SQL Dropping a View<br />You can delete a view with the DROP VIEW command.<br />SQL DROP VIEW Syntax<br />DROP VIEW view_name<br />« PreviousNext Chapter »<br />SQL Date Functions<br />« PreviousNext Chapter »<br />SQL Dates<br />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.<br />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 complicated.<br />Before talking about the complications of querying for dates, we will look at the most important built-in functions for working with dates.<br />MySQL Date Functions<br />The following table lists the most important built-in date functions in MySQL:<br />FunctionDescriptionNOW()Returns the current date and timeCURDATE()Returns the current dateCURTIME()Returns the current timeDATE()Extracts the date part of a date or date/time expressionEXTRACT()Returns a single part of a date/timeDATE_ADD()Adds a specified time interval to a dateDATE_SUB()Subtracts a specified time interval from a dateDATEDIFF()Returns the number of days between two datesDATE_FORMAT()Displays date/time data in different formats<br />SQL Server Date Functions<br />The following table lists the most important built-in date functions in SQL Server:<br />FunctionDescriptionGETDATE()Returns the current date and timeDATEPART()Returns a single part of a date/timeDATEADD()Adds or subtracts a specified time interval from a dateDATEDIFF()Returns the time between two datesCONVERT()Displays date/time data in different formats<br />SQL Date Data Types<br />MySQL comes with the following data types for storing a date or a date/time value in the database:<br />DATE - format YYYY-MM-DD<br />DATETIME - format: YYYY-MM-DD HH:MM:SS<br />TIMESTAMP - format: YYYY-MM-DD HH:MM:SS<br />YEAR - format YYYY or YY<br />SQL Server comes with the following data types for storing a date or a date/time value in the database:<br />DATE - format YYYY-MM-DD<br />DATETIME - format: YYYY-MM-DD HH:MM:SS<br />SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS<br />TIMESTAMP - format: a unique number<br />Note: The date types are chosen for a column when you create a new table in your database!<br />For an overview of all data types available, go to our complete Data Types reference.<br />SQL Working with Dates<br />You can compare two dates easily if there is no time component involved!<br />Assume we have the following \" Orders\" table:<br />OrderIdProductNameOrderDate1Geitost2008-11-112Camembert Pierrot2008-11-093Mozzarella di Giovanni2008-11-114Mascarpone Fabioli2008-10-29<br />Now we want to select the records with an OrderDate of \" 2008-11-11\" from the table above.<br />We use the following SELECT statement:<br />SELECT * FROM Orders WHERE OrderDate='2008-11-11'<br />The result-set will look like this:<br />OrderIdProductNameOrderDate1Geitost2008-11-113Mozzarella di Giovanni2008-11-11<br />Now, assume that the \" Orders\" table looks like this (notice the time component in the \" OrderDate\" column):<br />OrderIdProductNameOrderDate1Geitost2008-11-11 13:23:442Camembert Pierrot2008-11-09 15:45:213Mozzarella di Giovanni2008-11-11 11:12:014Mascarpone Fabioli2008-10-29 14:56:59<br />If we use the same SELECT statement as above:<br />SELECT * FROM Orders WHERE OrderDate='2008-11-11'<br />we will get no result! This is because the query is looking only for dates with no time portion.<br />Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your dates!<br />« PreviousNext Chapter »<br />SQL NULL Values<br />« PreviousNext Chapter »<br />NULL values represent missing unknown data.<br />By default, a table column can hold NULL values.<br />This chapter will explain the IS NULL and IS NOT NULL operators.<br />SQL NULL Values<br />If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.<br />NULL values are treated differently from other values.<br />NULL is used as a placeholder for unknown or inapplicable values.<br />Note: It is not possible to compare NULL and 0; they are not equivalent.<br />SQL Working with NULL Values<br />Look at the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOla Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKari Stavanger<br />Suppose that the \" Address\" column in the \" Persons\" table is optional. This means that if we insert a record with no value for the \" Address\" column, the \" Address\" column will be saved with a NULL value.<br />How can we test for NULL values?<br />It is not possible to test for NULL values with comparison operators, such as =, <, or <>.<br />We will have to use the IS NULL and IS NOT NULL operators instead.<br />SQL IS NULL<br />How do we select only the records with NULL values in the \" Address\" column?<br />We will have to use the IS NULL operator:<br />SELECT LastName,FirstName,Address FROM PersonsWHERE Address IS NULL<br />The result-set will look like this:<br />LastNameFirstNameAddressHansenOla PettersenKari <br />Tip: Always use IS NULL to look for NULL values.<br />SQL IS NOT NULL<br />How do we select only the records with no NULL values in the \" Address\" column?<br />We will have to use the IS NOT NULL operator:<br />SELECT LastName,FirstName,Address FROM PersonsWHERE Address IS NOT NULL<br />The result-set will look like this:<br />LastNameFirstNameAddressSvendsonToveBorgvn 23<br />In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.<br />« PreviousNext Chapter »<br />SQL NULL Functions<br />« PreviousNext Chapter »<br />SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions<br />Look at the following \" Products\" table:<br />P_IdProductNameUnitPriceUnitsInStockUnitsOnOrder1Jarlsberg10.4516152Mascarpone32.5623 3Gorgonzola15.67920<br />Suppose that the \" UnitsOnOrder\" column is optional, and may contain NULL values.<br />We have the following SELECT statement:<br />SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)FROM Products<br />In the example above, if any of the \" UnitsOnOrder\" values are NULL, the result is NULL.<br />Microsoft's ISNULL() function is used to specify how we want to treat NULL values.<br />The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.<br />In this case we want NULL values to be zero.<br />Below, if \" UnitsOnOrder\" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is NULL:<br />SQL Server / MS Access<br />SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))FROM Products<br />Oracle<br />Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:<br />SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))FROM Products<br />MySQL<br />MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function.<br />In MySQL we can use the IFNULL() function, like this:<br />SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))FROM Products<br />or we can use the COALESCE() function, like this:<br />SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))FROM Products<br />« PreviousNext Chapter <br />SQL Data Types<br />« PreviousNext Chapter »<br />Data types and ranges for Microsoft Access, MySQL and SQL Server.<br />Microsoft Access Data Types<br />Data typeDescriptionStorageTextUse for text or combinations of text and numbers. 255 characters maximum MemoMemo is used for larger amounts of text. Stores up to 65,536 characters. Note: You cannot sort a memo field. However, they are searchable ByteAllows whole numbers from 0 to 2551 byteIntegerAllows whole numbers between -32,768 and 32,7672 bytesLongAllows whole numbers between -2,147,483,648 and 2,147,483,6474 bytesSingleSingle precision floating-point. Will handle most decimals 4 bytesDoubleDouble precision floating-point. Will handle most decimals8 bytesCurrencyUse for currency. Holds up to 15 digits of whole dollars, plus 4 decimal places. Tip: You can choose which country's currency to use8 bytesAutoNumberAutoNumber fields automatically give each record its own number, usually starting at 14 bytesDate/TimeUse for dates and times8 bytesYes/NoA logical field can be displayed as Yes/No, True/False, or On/Off. In code, use the constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/No fields1 bitOle ObjectCan store pictures, audio, video, or other BLOBs (Binary Large OBjects)up to 1GBHyperlinkContain links to other files, including web pages Lookup WizardLet you type a list of options, which can then be chosen from a drop-down list4 bytes<br />MySQL Data Types<br />In MySQL there are three main types : text, number, and Date/Time types.<br />Text types:<br />Data typeDescriptionCHAR(size)Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 charactersVARCHAR(size)Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT typeTINYTEXTHolds a string with a maximum length of 255 charactersTEXTHolds a string with a maximum length of 65,535 charactersBLOBFor BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of dataMEDIUMTEXTHolds a string with a maximum length of 16,777,215 charactersMEDIUMBLOBFor BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of dataLONGTEXTHolds a string with a maximum length of 4,294,967,295 charactersLONGBLOBFor BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of dataENUM(x,y,z,etc.)Let you enter 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. Note: The values are sorted in the order you enter them.You enter the possible values in this format: ENUM('X','Y','Z')SETSimilar to ENUM except that SET may contain up to 64 list items and can store more than one choice<br />Number types:<br />Data typeDescriptionTINYINT(size)-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesisSMALLINT(size)-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesisMEDIUMINT(size)-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesisINT(size)-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesisBIGINT(size)-9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesisFLOAT(size,d)A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameterDOUBLE(size,d)A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameterDECIMAL(size,d)A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter<br />*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number. <br />Date types:<br />Data typeDescriptionDATE()A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31'DATETIME()*A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'TIMESTAMP()*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 Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTCTIME()A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59'YEAR()A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069<br />*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.<br />SQL Server Data Types<br />Character strings:<br />Data typeDescriptionStoragechar(n)Fixed-length character string. Maximum 8,000 charactersnvarchar(n)Variable-length character string. Maximum 8,000 characters varchar(max)Variable-length character string. Maximum 1,073,741,824 characters textVariable-length character string. Maximum 2GB of text data <br />Unicode strings:<br />Data typeDescriptionStoragenchar(n)Fixed-length Unicode data. Maximum 4,000 characters nvarchar(n)Variable-length Unicode data. Maximum 4,000 characters nvarchar(max)Variable-length Unicode data. Maximum 536,870,912 characters ntextVariable-length Unicode data. Maximum 2GB of text data <br />Binary types:<br />Data typeDescriptionStoragebitAllows 0, 1, or NULL binary(n)Fixed-length binary data. Maximum 8,000 bytes varbinary(n)Variable-length binary data. Maximum 8,000 bytes varbinary(max)Variable-length binary data. Maximum 2GB imageVariable-length binary data. Maximum 2GB <br />Number types:<br />Data typeDescriptionStoragetinyintAllows whole numbers from 0 to 2551 bytesmallintAllows whole numbers between -32,768 and 32,7672 bytesintAllows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytesbigintAllows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytesdecimal(p,s)Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 –1.The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 05-17 bytesnumeric(p,s)Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 –1.The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 05-17 bytessmallmoneyMonetary data from -214,748.3648 to 214,748.3647 4 bytesmoneyMonetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.58078 bytesfloat(n)Floating precision number data from -1.79E + 308 to 1.79E + 308. The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.4 or 8 bytesrealFloating precision number data from -3.40E + 38 to 3.40E + 384 bytes<br />Date types:<br />Data typeDescriptionStoragedatetimeFrom January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds8 bytesdatetime2From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds6-8 bytessmalldatetimeFrom January 1, 1900 to June 6, 2079 with an accuracy of 1 minute4 bytesdateStore a date only. From January 1, 0001 to December 31, 99993 bytestimeStore a time only to an accuracy of 100 nanoseconds3-5 bytesdatetimeoffsetThe same as datetime2 with the addition of a time zone offset8-10 bytestimestampStores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable <br />Other data types:<br />Data typeDescriptionsql_variantStores up to 8,000 bytes of data of various data types, except text, ntext, and timestampuniqueidentifierStores a globally unique identifier (GUID)xmlStores XML formatted data. Maximum 2GBcursorStores a reference to a cursor used for database operationstableStores a result-set for later processing<br />« PreviousNext Chapter »<br />SQL Functions<br />« PreviousNext Chapter »<br />SQL has many built-in functions for performing calculations on data.<br />SQL Aggregate Functions<br />SQL aggregate functions return a single value, calculated from values in a column.<br />Useful aggregate functions:<br />AVG() - Returns the average value<br />COUNT() - Returns the number of rows<br />FIRST() - Returns the first value<br />LAST() - Returns the last value<br />MAX() - Returns the largest value<br />MIN() - Returns the smallest value<br />SUM() - Returns the sum<br />SQL Scalar functions<br />SQL scalar functions return a single value, based on the input value.<br />Useful scalar functions:<br />UCASE() - Converts a field to upper case<br />LCASE() - Converts a field to lower case<br />MID() - Extract characters from a text field<br />LEN() - Returns the length of a text field<br />ROUND() - Rounds a numeric field to the number of decimals specified<br />NOW() - Returns the current system date and time<br />FORMAT() - Formats how a field is to be displayed<br />Tip: The aggregate functions and the scalar functions will be explained in details in the next chapters.<br />« PreviousNext Chapter »<br />SQL AVG() Function<br />« PreviousNext Chapter »<br />The AVG() Function<br />The AVG() function returns the average value of a numeric column.<br />SQL AVG() Syntax<br />SELECT AVG(column_name) FROM table_name<br />SQL AVG() Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the average value of the \" OrderPrice\" fields.<br />We use the following SQL statement:<br />SELECT AVG(OrderPrice) AS OrderAverage FROM Orders<br />The result-set will look like this:<br />OrderAverage950<br />Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value.<br />We use the following SQL statement:<br />SELECT Customer FROM OrdersWHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)<br />The result-set will look like this:<br />CustomerHansenNilsenJensen<br />« PreviousNext Chapter »<br />SQL COUNT() Function<br />« PreviousNext Chapter »<br />The COUNT() function returns the number of rows that matches a specified criteria.<br />SQL COUNT(column_name) Syntax<br />The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:<br />SELECT COUNT(column_name) FROM table_name<br />SQL COUNT(*) Syntax<br />The COUNT(*) function returns the number of records in a table:<br />SELECT COUNT(*) FROM table_name<br />SQL COUNT(DISTINCT column_name) Syntax<br />The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:<br />SELECT COUNT(DISTINCT column_name) FROM table_name<br />Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.<br />SQL COUNT(column_name) Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to count the number of orders from \" Customer Nilsen\" .<br />We use the following SQL statement:<br />SELECT COUNT(Customer) AS CustomerNilsen FROM OrdersWHERE Customer='Nilsen'<br />The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:<br />CustomerNilsen2<br />SQL COUNT(*) Example<br />If we omit the WHERE clause, like this:<br />SELECT COUNT(*) AS NumberOfOrders FROM Orders<br />The result-set will look like this:<br />NumberOfOrders6<br />which is the total number of rows in the table.<br />SQL COUNT(DISTINCT column_name) Example<br />Now we want to count the number of unique customers in the \" Orders\" table.<br />We use the following SQL statement:<br />SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders<br />The result-set will look like this:<br />NumberOfCustomers3<br />which is the number of unique customers (Hansen, Nilsen, and Jensen) in the \" Orders\" table.<br />« PreviousNext Chapter »<br />SQL FIRST() Function<br />« PreviousNext Chapter »<br />The FIRST() Function<br />The FIRST() function returns the first value of the selected column.<br />SQL FIRST() Syntax<br />SELECT FIRST(column_name) FROM table_name<br />SQL FIRST() Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the first value of the \" OrderPrice\" column.<br />We use the following SQL statement:<br />SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders<br />Tip: Workaround if FIRST() function is not supported:<br />SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1<br />The result-set will look like this:<br />FirstOrderPrice1000<br />« PreviousNext Chapter »<br />SQL LAST() Function<br />« PreviousNext Chapter »<br />The LAST() Function<br />The LAST() function returns the last value of the selected column.<br />SQL LAST() Syntax<br />SELECT LAST(column_name) FROM table_name<br />SQL LAST() Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the last value of the \" OrderPrice\" column.<br />We use the following SQL statement:<br />SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders<br />Tip: Workaround if LAST() function is not supported:<br />SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1<br />The result-set will look like this:<br />LastOrderPrice100<br />« PreviousNext Chapter »<br />SQL MAX() Function<br />« PreviousNext Chapter »<br />The MAX() Function<br />The MAX() function returns the largest value of the selected column.<br />SQL MAX() Syntax<br />SELECT MAX(column_name) FROM table_name<br />SQL MAX() Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the largest value of the \" OrderPrice\" column.<br />We use the following SQL statement:<br />SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders<br />The result-set will look like this:<br />LargestOrderPrice2000<br />« PreviousNext Chapter »<br />SQL MIN() Function<br />« PreviousNext Chapter »<br />The MIN() Function<br />The MIN() function returns the smallest value of the selected column.<br />SQL MIN() Syntax<br />SELECT MIN(column_name) FROM table_name<br />SQL MIN() Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the smallest value of the \" OrderPrice\" column.<br />We use the following SQL statement:<br />SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders<br />The result-set will look like this:<br />SmallestOrderPrice100<br />« PreviousNext Chapter »<br />SQL SUM() Function<br />« PreviousNext Chapter »<br />The SUM() Function<br />The SUM() function returns the total sum of a numeric column.<br />SQL SUM() Syntax<br />SELECT SUM(column_name) FROM table_name<br />SQL SUM() Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the sum of all \" OrderPrice\" fields\" .<br />We use the following SQL statement:<br />SELECT SUM(OrderPrice) AS OrderTotal FROM Orders<br />The result-set will look like this:<br />OrderTotal5700<br />« PreviousNext Chapter »<br />SQL GROUP BY Statement<br />« PreviousNext Chapter »<br />Aggregate functions often need an added GROUP BY statement.<br />The GROUP BY Statement<br />The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.<br />SQL GROUP BY Syntax<br />SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_name<br />SQL GROUP BY Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find the total sum (total order) of each customer.<br />We will have to use the GROUP BY statement to group the customers.<br />We use the following SQL statement:<br />SELECT Customer,SUM(OrderPrice) FROM OrdersGROUP BY Customer<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Hansen2000Nilsen1700Jensen2000<br />Nice! Isn't it? :)<br />Let's see what happens if we omit the GROUP BY statement:<br />SELECT Customer,SUM(OrderPrice) FROM Orders<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Hansen5700Nilsen5700Hansen5700Hansen5700Jensen5700Nilsen5700<br />The result-set above is not what we wanted.<br />Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The \" SUM(OrderPrice)\" returns a single value (that is the total sum of the \" OrderPrice\" column), while \" Customer\" returns 6 values (one value for each row in the \" Orders\" table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.<br />GROUP BY More Than One Column<br />We can also use the GROUP BY statement on more than one column, like this:<br />SELECT Customer,OrderDate,SUM(OrderPrice) FROM OrdersGROUP BY Customer,OrderDate<br />« PreviousNext Chapter »<br />SQL HAVING Clause<br />« PreviousNext Chapter »<br />The HAVING Clause<br />The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.<br />SQL HAVING Syntax<br />SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value<br />SQL HAVING Example<br />We have the following \" Orders\" table:<br />O_IdOrderDateOrderPriceCustomer12008/11/121000Hansen22008/10/231600Nilsen32008/09/02700Hansen42008/09/03300Hansen52008/08/302000Jensen62008/10/04100Nilsen<br />Now we want to find if any of the customers have a total order of less than 2000.<br />We use the following SQL statement:<br />SELECT Customer,SUM(OrderPrice) FROM OrdersGROUP BY CustomerHAVING SUM(OrderPrice)<2000<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Nilsen1700<br />Now we want to find if the customers \" Hansen\" or \" Jensen\" have a total order of more than 1500.<br />We add an ordinary WHERE clause to the SQL statement:<br />SELECT Customer,SUM(OrderPrice) FROM OrdersWHERE Customer='Hansen' OR Customer='Jensen'GROUP BY CustomerHAVING SUM(OrderPrice)>1500<br />The result-set will look like this:<br />CustomerSUM(OrderPrice)Hansen2000Jensen2000<br />« PreviousNext Chapter »<br />SQL UCASE() Function<br />« PreviousNext Chapter »<br />The UCASE() Function<br />The UCASE() function converts the value of a field to uppercase.<br />SQL UCASE() Syntax<br />SELECT UCASE(column_name) FROM table_name<br />Syntax for SQL Server<br />SELECT UPPER(column_name) FROM table_name<br />SQL UCASE() Example<br />We have the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the content of the \" LastName\" and \" FirstName\" columns above, and convert the \" LastName\" column to uppercase.<br />We use the following SELECT statement:<br />SELECT UCASE(LastName) as LastName,FirstName FROM Persons<br />The result-set will look like this:<br />LastNameFirstNameHANSENOlaSVENDSONTovePETTERSENKari<br />« PreviousNext Chapter »<br />SQL LCASE() Function<br />« PreviousNext Chapter »<br />The LCASE() Function<br />The LCASE() function converts the value of a field to lowercase.<br />SQL LCASE() Syntax<br />SELECT LCASE(column_name) FROM table_name<br />Syntax for SQL Server<br />SELECT LOWER(column_name) FROM table_name<br />SQL LCASE() Example<br />We have the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the content of the \" LastName\" and \" FirstName\" columns above, and convert the \" LastName\" column to lowercase.<br />We use the following SELECT statement:<br />SELECT LCASE(LastName) as LastName,FirstName FROM Persons<br />The result-set will look like this:<br />LastNameFirstNamehansenOlasvendsonTovepettersenKari<br />« PreviousNext Chapter »<br />SQL MID() Function<br />« PreviousNext Chapter »<br />The MID() Function<br />The MID() function is used to extract characters from a text field.<br />SQL MID() Syntax<br />SELECT MID(column_name,start[,length]) FROM table_name<br />ParameterDescriptioncolumn_nameRequired. The field to extract characters fromstartRequired. Specifies the starting position (starts at 1)lengthOptional. The number of characters to return. If omitted, the MID() function returns the rest of the text<br />SQL MID() Example<br />We have the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to extract the first four characters of the \" City\" column above.<br />We use the following SELECT statement:<br />SELECT MID(City,1,4) as SmallCity FROM Persons<br />The result-set will look like this:<br />SmallCitySandSandStav<br />SQL LEN() Function<br />« PreviousNext Chapter »<br />The LEN() Function<br />The LEN() function returns the length of the value in a text field.<br />SQL LEN() Syntax<br />SELECT LEN(column_name) FROM table_name<br />SQL LEN() Example<br />We have the following \" Persons\" table:<br />P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger<br />Now we want to select the length of the values in the \" Address\" column above.<br />We use the following SELECT statement:<br />SELECT LEN(Address) as LengthOfAddress FROM Persons<br />The result-set will look like this:<br />LengthOfAddress1299<br />« PreviousNext Chapter »<br />SQL ROUND() Function<br />« PreviousNext Chapter »<br />The ROUND() Function<br />The ROUND() function is used to round a numeric field to the number of decimals specified.<br />SQL ROUND() Syntax<br />SELECT ROUND(column_name,decimals) FROM table_name<br />ParameterDescriptioncolumn_nameRequired. The field to round.decimalsRequired. Specifies the number of decimals to be returned.<br />SQL ROUND() Example<br />We have the following \" Products\" table:<br />Prod_IdProductNameUnitUnitPrice1Jarlsberg1000 g10.452Mascarpone1000 g32.563Gorgonzola1000 g15.67<br />Now we want to display the product name and the price rounded to the nearest integer.<br />We use the following SELECT statement:<br />SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products<br />The result-set will look like this:<br />ProductNameUnitPriceJarlsberg10Mascarpone33Gorgonzola16<br />« PreviousNext Chapter »<br />SQL NOW() Function<br />« PreviousNext Chapter »<br />The NOW() Function<br />The NOW() function returns the current system date and time.<br />SQL NOW() Syntax<br />SELECT NOW() FROM table_name<br />SQL NOW() Example<br />We have the following \" Products\" table:<br />Prod_IdProductNameUnitUnitPrice1Jarlsberg1000 g10.452Mascarpone1000 g32.563Gorgonzola1000 g15.67<br />Now we want to display the products and prices per today's date.<br />We use the following SELECT statement:<br />SELECT ProductName, UnitPrice, Now() as PerDate FROM Products<br />The result-set will look like this:<br />ProductNameUnitPricePerDateJarlsberg10.4510/7/2008 11:25:02 AMMascarpone32.5610/7/2008 11:25:02 AMGorgonzola15.6710/7/2008 11:25:02 AM<br />« PreviousNext Chapter »<br />SQL FORMAT() Function<br />« PreviousNext Chapter »<br />The FORMAT() Function<br />The FORMAT() function is used to format how a field is to be displayed.<br />SQL FORMAT() Syntax<br />SELECT FORMAT(column_name,format) FROM table_name<br />ParameterDescriptioncolumn_nameRequired. The field to be formatted.formatRequired. Specifies the format.<br />SQL FORMAT() Example<br />We have the following \" Products\" table:<br />Prod_IdProductNameUnitUnitPrice1Jarlsberg1000 g10.452Mascarpone1000 g32.563Gorgonzola1000 g15.67<br />Now we want to display the products and prices per today's date (with today's date displayed in the following format \" YYYY-MM-DD\" ).<br />We use the following SELECT statement:<br />SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDateFROM Products<br />The result-set will look like this:<br />ProductNameUnitPricePerDateJarlsberg10.452008-10-07Mascarpone32.562008-10-07Gorgonzola15.672008-10-07<br />« PreviousNext Chapter »<br />SQL Quick Reference From W3Schools<br />« PreviousNext Chapter »<br />SQL StatementSyntaxAND / ORSELECT column_name(s)FROM table_nameWHERE conditionAND|OR conditionALTER TABLEALTER TABLE table_name ADD column_name datatype orALTER TABLE table_name DROP COLUMN column_nameAS (alias)SELECT column_name AS column_aliasFROM table_name orSELECT column_nameFROM table_name  AS table_aliasBETWEENSELECT column_name(s)FROM table_nameWHERE column_nameBETWEEN value1 AND value2CREATE DATABASECREATE DATABASE database_nameCREATE TABLECREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name2 data_type,...)CREATE INDEXCREATE INDEX index_nameON table_name (column_name) orCREATE UNIQUE INDEX index_nameON table_name (column_name)CREATE VIEWCREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE conditionDELETEDELETE FROM table_nameWHERE some_column=some_value orDELETE FROM table_name (Note: Deletes the entire table!!)DELETE * FROM table_name (Note: Deletes the entire table!!)DROP DATABASEDROP DATABASE database_nameDROP INDEXDROP INDEX table_name.index_name (SQL Server)DROP INDEX index_name ON table_name (MS Access)DROP INDEX index_name (DB2/Oracle)ALTER TABLE table_nameDROP INDEX index_name (MySQL)DROP TABLEDROP TABLE table_nameGROUP BYSELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVINGSELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator valueINSELECT column_name(s)FROM table_nameWHERE column_nameIN (value1,value2,..)INSERT INTOINSERT INTO table_nameVALUES (value1, value2, value3,....) orINSERT INTO table_name(column1, column2, column3,...)VALUES (value1, value2, value3,....)INNER JOINSELECT column_name(s)FROM table_name1INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_nameLEFT JOINSELECT column_name(s)FROM table_name1LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_nameRIGHT JOINSELECT column_name(s)FROM table_name1RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_nameFULL JOINSELECT column_name(s)FROM table_name1FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_nameLIKESELECT column_name(s)FROM table_nameWHERE column_name LIKE patternORDER BYSELECT column_name(s)FROM table_nameORDER BY column_name [ASC|DESC]SELECTSELECT column_name(s)FROM table_nameSELECT *SELECT *FROM table_nameSELECT DISTINCTSELECT DISTINCT column_name(s)FROM table_nameSELECT INTOSELECT *INTO new_table_name [IN externaldatabase]FROM old_table_name orSELECT column_name(s)INTO new_table_name [IN externaldatabase]FROM old_table_nameSELECT TOPSELECT TOP number|percent column_name(s)FROM table_nameTRUNCATE TABLETRUNCATE TABLE table_nameUNIONSELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2UNION ALLSELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2UPDATEUPDATE table_nameSET column1=value, column2=value,...WHERE some_column=some_valueWHERESELECT column_name(s)FROM table_nameWHERE column_name operator value<br />Source : http://www.w3schools.com/sql/sql_quickref.asp<br />« PreviousNext Chapter »<br />SQL Hosting<br />« PreviousNext Chapter »<br />SQL Hosting<br />If you want your web site to be able to store and display data from a database, your web server should have access to a database system that uses the SQL language.<br />If your web server will be hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans.<br />The most common SQL hosting databases are MySQL, MS SQL Server, and MS Access.<br />You can have SQL databases on both Windows and Linux/UNIX operating systems.<br />Below is an overview of which database system that runs on which OS.<br />MS SQL Server<br />Runs only on Windows OS.<br />MySQL<br />Runs on both Windows and Linux/UNIX operating systems.<br />MS Access (recommended only for small websites)<br />Runs only on Windows OS.<br />To learn more about web hosting, please visit our Hosting tutorial.<br />« PreviousNext Chapter »<br />You Have Learned SQL, Now What?<br />« PreviousNext Chapter »<br />SQL Summary<br />This SQL tutorial has taught you the standard computer language for accessing and manipulating database systems.<br />You have learned how to execute queries, retrieve data, insert new records, delete records and update records in a database with SQL.<br />You have also learned how to create databases, tables, and indexes with SQL, and how to drop them.<br />You have learned the most important aggregate functions in SQL.<br />You now know that SQL is the standard language that works with all the well-known database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and MS Access.<br />Now You Know SQL, What's Next?<br />Our recommendation is to learn about ADO or PHP MySQL.<br />If you want to learn more about ADO, please visit our ADO tutorial.<br />If you want to learn more about MySQL, please visit our PHP tutorial.<br />« PreviousNext Chapter »<br />SQL Quiz<br />« PreviousNext Chapter »<br />You can test your SQL skills with W3Schools' Quiz.<br />The Test<br />The test contains 20 questions and there is no time limit.<br />The test is not official, it's just a nice way to see how much you know, or don't know, about SQL.<br />Your Score Will be Counted<br />You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 20 points.<br />Good luck! Start the SQL Quiz<br />