What is SQL?
- SQL stands for Structured Query Language
- SQL lets you access and manipulate databases
- SQL is an ANSI (American National Standards Institute) standard
What Can SQL do?
- SQL can execute queries against a database
- SQL can retrieve data from a database
- SQL can insert records in a database
- SQL can update records in a database
- SQL can delete records from a database
- SQL can create new databases
- SQL can create new tables in a database
- SQL can create stored procedures in a database
- SQL can create views in a database
- SQL can set permissions on tables, procedures, and views
SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).
The query and update commands form the DML part of SQL:
- SELECT - extracts data from a database
- UPDATE - updates data in a database
- DELETE - deletes data from a database
- INSERT INTO - inserts new data into a database
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:
- CREATE DATABASE - creates a new database
- ALTER DATABASE - modifies a database
- CREATE TABLE - creates a new table
- ALTER TABLE - modifies a table
- DROP TABLE - deletes a table
- CREATE INDEX - creates an index (search key)
- DROP INDEX - deletes an index
SQL SELECT Syntax
SELECT column_name(s) FROM table_name |
SELECT * FROM table_name |
The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s) FROM table_name |
The WHERE clause is used to filter records.
The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.SQL WHERE Syntax
SELECT column_name(s) FROM table_name WHERE column_name operator value |
SELECT * FROM Persons WHERE City='Sandnes'C
SELECT * FROM Persons WHERE FirstName='Tove'
SELECT * FROM Persons WHERE Year=1965
Operators Allowed in the WHERE Clause
With the WHERE clause, the following operators can be used:
Operator | Description |
= | Equal |
<> | Not equal |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
BETWEEN | Between an inclusive range |
LIKE | Search for a pattern |
IN | If you know the exact value you want to return for at least one of the columns |
The AND & OR operators are used to filter records based on more than one condition.
The AND & OR Operators
· The AND operator displays a record if both the first condition and the second condition is true.
SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson'
· The OR operator displays a record if either the first condition or the second condition is true.
SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola'
Combining AND & OR
You can also combine AND and OR (use parenthesis to form complex expressions). SELECT * FROM Persons WHERE LastName='Svendson'
AND (FirstName='Tove' OR FirstName='Ola')
The ORDER BY keyword is used to sort the result-set.
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column.The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC |
ORDER BY Example
The "Persons" table: P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
4 | Nilsen | Tom | Vingvn 23 | Stavanger |
We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName |
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
4 | Nilsen | Tom | Vingvn 23 | Stavanger |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
ORDER BY DESC Example
Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.We use the following SELECT statement:
SELECT * FROM Persons ORDER BY LastName DESC |
P_Id | LastName | FirstName | Address | City |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
4 | Nilsen | Tom | Vingvn 23 | Stavanger |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name VALUES (value1, value2, value3,...) |
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) |
EX :
INSERT INTO Persons VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
The UPDATE statement is used to update records in a table.
The UPDATE Statement
The UPDATE statement is used to update existing records in a table.SQL UPDATE Syntax
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value |
The DELETE statement is used to delete records in a table.
The DELETE Statement
The DELETE statement is used to delete rows in a table.SQL DELETE Syntax
DELETE FROM table_name WHERE some_column=some_value |
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name or DELETE * FROM table_name |
Note: Be very careful when deleting records. You cannot undo this statement!
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
The LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.SQL LIKE Syntax
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern |
We use the following SELECT statement:
SELECT * FROM Persons WHERE City LIKE 's%' |
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
SQL wildcards can be used when searching for data in a database.
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE operator.
With SQL, the following wildcards can be used:
Wildcard | Description |
% | 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 |
SQL Wildcard Examples
We have the following "Persons" table:
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
Using the % Wildcard
Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons WHERE City LIKE 'sa%' |
The result-set will look like this:
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons WHERE City LIKE '%nes%' |
The result-set will look like this:
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
Using the _ Wildcard
Now we want to select the persons with a first name that starts with any character, followed by "la" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons WHERE FirstName LIKE '_la' |
The result-set will look like this:
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
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.
We use the following SELECT statement:
SELECT * FROM Persons WHERE LastName LIKE 'S_end_on' |
The result-set will look like this:
P_Id | LastName | FirstName | Address | City |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
Using the [charlist] Wildcard
Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the "Persons" table.
We use the following SELECT statement:
SELECT * FROM Persons WHERE LastName LIKE '[bsp]%' |
The result-set will look like this:
P_Id | LastName | FirstName | Address | City |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
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.
We use the following SELECT statement:
SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%' |
The result-set will look like this:
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.SQL IN Syntax
SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) |
SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen')
The BETWEEN operator is used in a WHERE clause to select a range of data between two values.
The BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.SQL BETWEEN Syntax
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2 |
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'
SQL Alias
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.An alias name could be anything, but usually it is short.
SQL Alias Syntax for Tables
SELECT column_name(s) FROM table_name AS alias_name |
SQL Alias Syntax for Columns
SELECT column_name AS alias_name FROM table_name |
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola'
WHERE p.LastName='Hansen' AND p.FirstName='Ola'
SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.
SQL JOIN
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.
Tables in a database are often related to each other with keys.
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.Different SQL JOINs
Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.
- JOIN: Return rows when there is at least one match in both tables
- LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
- RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
- FULL JOIN: Return rows when there is a match in one of the tables
SQL INNER JOIN Keyword
The INNER JOIN keyword return rows when there is at least one match in both tables.SQL INNER JOIN Syntax
SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name |
SQL LEFT JOIN Keyword
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).SQL LEFT JOIN Syntax
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name |
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all the rows from the right table (table_name2), even if there are no matches in the left table (table_name1).SQL RIGHT JOIN Syntax
SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name |
SQL FULL JOIN Keyword
The FULL JOIN keyword return rows when there is a match in one of the tables.SQL FULL JOIN Syntax
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name |
The SQL UNION operator combines two or more SELECT statements.
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.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.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 |
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 |
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
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).
We will focus on the following constraints:
- NOT NULL
- UNIQUE
- PRIMARY KEY
- FOREIGN KEY
- CHECK
- DEFAULT
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.
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.
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) |
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
Ex :
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two tables:
The "Persons" table:
P_Id | LastName | FirstName | Address | City |
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
The "Orders" table:
O_Id | OrderNo | P_Id |
1 | 77895 | 3 |
2 | 44678 | 3 |
3 | 22456 | 2 |
4 | 24562 | 1 |
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
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.
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.The default value will be added to all new records, if no other value is specified.
Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
The DROP INDEX Statement
The DROP INDEX statement is used to delete an index in a table.DROP INDEX Syntax for MS Access:
DROP INDEX index_name ON table_name |
DROP INDEX Syntax for MS SQL Server:
DROP INDEX table_name.index_name |
DROP INDEX Syntax for DB2/Oracle:
DROP INDEX index_name |
DROP INDEX Syntax for MySQL:
ALTER TABLE table_name DROP INDEX index_name |
The DROP TABLE Statement
The DROP TABLE statement is used to delete a table. DROP TABLE table_name |
The DROP DATABASE Statement
The DROP DATABASE statement is used to delete a database. DROP DATABASE database_name |
The TRUNCATE TABLE Statement
What if we only want to delete the data inside the table, and not the table itself?Then, use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name |
The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax: ALTER TABLE table_name ADD column_name datatype |
ALTER TABLE table_name DROP COLUMN column_name |
ALTER TABLE table_name ALTER COLUMN column_name datatype |
SQL Server Date Functions
The following table lists the most important built-in date functions in SQL Server:
Function | Description |
Returns the current date and time | |
Returns a single part of a date/time | |
Adds or subtracts a specified time interval from a date | |
Returns the time between two dates | |
Displays date/time data in different formats |
SQL has many built-in functions for performing calculations on data.
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
- AVG() - Returns the average value
- COUNT() - Returns the number of rows
- FIRST() - Returns the first value
- LAST() - Returns the last value
- MAX() - Returns the largest value
- MIN() - Returns the smallest value
- SUM() - Returns the sum
The AVG() Function
The AVG() function returns the average value of a numeric column.SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name |
We use the following SQL statement:
SELECT AVG(OrderPrice) AS OrderAverage FROM Orders |
The COUNT() function returns the number of rows that matches a specified criteria.
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name |
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name |
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: SELECT COUNT(DISTINCT column_name) FROM table_name |
The FIRST() Function
The FIRST() function returns the first value of the selected column.SQL FIRST() Syntax
SELECT FIRST(column_name) FROM table_name |
We use the following SQL statement:
SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders |
Tip: Workaround if FIRST() function is not supported:
SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1 |
The LAST() Function
The LAST() function returns the last value of the selected column.SQL LAST() Syntax
SELECT LAST(column_name) FROM table_name |
The MAX() Function
The MAX() function returns the largest value of the selected column.SQL MAX() Syntax
SELECT MAX(column_name) FROM table_name |
The MIN() Function
The MIN() function returns the smallest value of the selected column.SQL MIN() Syntax
SELECT MIN(column_name) FROM table_name |
The SUM() Function
The SUM() function returns the total sum of a numeric column.SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name |
Aggregate functions often need an added GROUP BY statement.
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name |
SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer
GROUP BY More Than One Column
We can also use the GROUP BY statement on more than one column, like this:
SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate |
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value |
SQL HAVING Example
We have the following "Orders" table:
O_Id | OrderDate | OrderPrice | Customer |
1 | 2008/11/12 | 1000 | Hansen |
2 | 2008/10/23 | 1600 | Nilsen |
3 | 2008/09/02 | 700 | Hansen |
4 | 2008/09/03 | 300 | Hansen |
5 | 2008/08/30 | 2000 | Jensen |
6 | 2008/10/04 | 100 | Nilsen |
Now we want to find if any of the customers have a total order of less than 2000.
We use the following SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000 |
The result-set will look like this:
Customer | SUM(OrderPrice) |
Nilsen | 1700 |
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:
- UCASE() - Converts a field to upper case
- LCASE() - Converts a field to lower case
- MID() - Extract characters from a text field
- LEN() - Returns the length of a text field
- ROUND() - Rounds a numeric field to the number of decimals specified
- NOW() - Returns the current system date and time
- FORMAT() - Formats how a field is to be displayed
The UCASE() Function
The UCASE() function converts the value of a field to uppercase.SQL UCASE() Syntax
SELECT UCASE(column_name) FROM table_name |
Syntax for SQL Server
SELECT UPPER(column_name) FROM table_name |
The LCASE() Function
The LCASE() function converts the value of a field to lowercase.SQL LCASE() Syntax
SELECT LCASE(column_name) FROM table_name |
Syntax for SQL Server
SELECT LOWER(column_name) FROM table_name |
The MID() Function
The MID() function is used to extract characters from a text field.SQL MID() Syntax
SELECT MID(column_name,start[,length]) FROM table_name |
We use the following SELECT statement:
SELECT MID(City,1,4) as SmallCity FROM Persons |
The LEN() Function
The LEN() function returns the length of the value in a text field.SQL LEN() Syntax
SELECT LEN(column_name) FROM table_name |
We use the following SELECT statement:
SELECT LEN(Address) as LengthOfAddress FROM Persons |
The ROUND() Function
The ROUND() function is used to round a numeric field to the number of decimals specified.SQL ROUND() Syntax
SELECT ROUND(column_name,decimals) FROM table_name |
We use the following SELECT statement:
SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products |
The NOW() Function
The NOW() function returns the current system date and time.SQL NOW() Syntax
SELECT NOW() FROM table_name |
We use the following SELECT statement:
SELECT ProductName, UnitPrice, Now() as PerDate FROM Products |
The FORMAT() Function
The FORMAT() function is used to format how a field is to be displayed.SQL FORMAT() Syntax
SELECT FORMAT(column_name,format) FROM table_name |
We use the following SELECT statement:
SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate FROM Products |
No comments:
Post a Comment