SQL BASIC
1.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.
2.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.
3.SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).
4.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 defines indexes (keys), specifies links between tables, and imposes 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
5.The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
Example
SELECT column_name(s) FROM table_name
OR
SELECT * FROM TableName
6.The SQL SELECT DISTINCT Statement
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.
The DISTINCT keyword can be used to return only distinct (different) values.
Example
7. SELECT DISTINCT column_name(s) FROM table_name
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
8.The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
QUERY
SELECT column_name(s) FROM table_name WHERE column_name operator value
EXample
SELECT * FROM Persons WHERE FirstName='Tove'
9.The AND & OR Operators
The AND operator displays a record if both the first condition and the second condition is rue.
The OR operator displays a record if either the first condition or the second condition is true.
Example
SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson'
SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola'
10.Combining AND & OR
You can also combine AND and OR (use parenthesis to form complex expressions).
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":
Example
SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR irstName='Ola')
11.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.
Query
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Example
SELECT * FROM Persons ORDER BY LastName
SELECT * FROM Persons ORDER BY LastName DESC
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
12.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,...)
Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns:
Query
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
13.The UPDATE Statement
The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value
Example
UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob'
14.The DELETE Statement
The DELETE statement is used to delete rows in a table.
Query
DELETE FROM table_name WHERE some_column=some_value
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!
Example
DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'
SQL ADVANCE
15.The TOP Clause
The 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.
Syntax
SELECT TOP number|percent column_name(s) FROM table_name
Example
SELECT column_name(s) FROM table_name LIMIT number
SELECT * FROM Persons LIMIT 5
SELECT TOP 2 * FROM Persons
SELECT TOP 50 PERCENT * FROM Persons
16.The LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern
Example
SELECT * FROM Persons WHERE City LIKE 's%'
SELECT * FROM Persons WHERE City LIKE '%s'
SELECT * FROM Persons WHERE City LIKE '%tav%'
SELECT * FROM Persons WH0.ERE City NOT LIKE '%tav%'
17.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
Example
SELECT * FROM Persons WHERE FirstName LIKE '_la'
SELECT * FROM Persons WHERE LastName LIKE 'S_end_on'
SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%'
18.The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...)
Example
SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen')
19.The BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2
Example
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'
SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'
20.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.
Syntax
SELECT column_name(s) FROM table_name AS alias_name
Syntax for Columns
SELECT column_name AS alias_name FROM table_name
Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the table aliases of "p" and "po" respectively.
Now we want to list all the orders that "Ola Hansen" is responsible for.
We use the following SELECT statement with Aliases:
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p,Product_Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola'
The same SELECT statement without aliases:
SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons,
Product_Orders
WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'
21.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.
Look at 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
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.
Next, we have the "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
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.
Notice that the relationship between the two tables above is the "P_Id" column.
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
INNER JOIN Example
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
SQL LEFT JOIN Keyword
LEFT JOIN Example
22.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).
Syntax
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name
Example
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
23.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).
Syntax
SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name
Example
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
24.FULL JOIN
The FULL JOIN keyword return rows when there is a match in one of the tables.
Syntax
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name
25.SQL UNION
The SQL UNION operator combines two or more SELECT statements.
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.
Syntax
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2
SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
Example
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
--------------------------------------------------------------------------
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
26.SQL SELECT INTO
The SELECT INTO statement selects data from one table and inserts it into a different table.
The SELECT INTO statement is most often used to create backup copies of tables.
Syntax
We can select all columns into the new table:
SELECT * INTO new_table_name [IN externaldatabase] FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_tablename
Examples
SELECT * INTO Persons_Backup FROM Persons.
SELECT LastName,FirstName INTO Persons_Backup FROM Persons.
27.The CREATE TABLE Statement
The CREATE TABLE statement is used to create a table in a database.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
28.NOT NULL Constraint
By default, a table column can hold NULL values.
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)
)
29.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.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
Syntax
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)
)
30.SQL PRIMARY KEY
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.
SQL PRIMARY KEY Constraint on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:
MySQL:
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)
)
31.SQL FOREIGN KEY
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:
Example
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)
)
32.INDEX
The CREATE INDEX statement is used to create indexes in tables.
Indexes allow the database application to find data fast; without reading the whole table.
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
33.SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.
Example
The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons" table:
CREATE INDEX PIndex
ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
CREATE INDEX PIndex
ON Persons (LastName, FirstName)
34.DROP INDEX
The DROP INDEX statement is used to delete an index in a table.
Syntax
DROP INDEX index_name ON table_name
ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
Syntax
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
35.AUTO INCREMENT a Field
Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.
We would like to create an auto-increment field in a table.
Syntax
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table:
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)
)
Syntax
CREATE TABLE Persons
(
P_Id int PRIMARY KEY IDENTITY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
36.SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
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.
37.SQL Dates
Note The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the most important built-in functions for working with dates.
MySQL Date Functions
The following table lists the most important built-in date functions in MySQL:
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
38.SQL Server Date Functions
The following table lists the most important built-in date functions in SQL Server:
Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds or subtracts a specified time interval from a date
DATEDIFF() Returns the time between two dates
CONVERT() Displays date/time data in different formats
------------------------------------------------------------------------------------------------------------
1.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.
2.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.
3.SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).
4.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 defines indexes (keys), specifies links between tables, and imposes 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
5.The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
Example
SELECT column_name(s) FROM table_name
OR
SELECT * FROM TableName
6.The SQL SELECT DISTINCT Statement
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.
The DISTINCT keyword can be used to return only distinct (different) values.
Example
7. SELECT DISTINCT column_name(s) FROM table_name
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
8.The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
QUERY
SELECT column_name(s) FROM table_name WHERE column_name operator value
EXample
SELECT * FROM Persons WHERE FirstName='Tove'
9.The AND & OR Operators
The AND operator displays a record if both the first condition and the second condition is rue.
The OR operator displays a record if either the first condition or the second condition is true.
Example
SELECT * FROM Persons WHERE FirstName='Tove' AND LastName='Svendson'
SELECT * FROM Persons WHERE FirstName='Tove' OR FirstName='Ola'
10.Combining AND & OR
You can also combine AND and OR (use parenthesis to form complex expressions).
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":
Example
SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR irstName='Ola')
11.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.
Query
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Example
SELECT * FROM Persons ORDER BY LastName
SELECT * FROM Persons ORDER BY LastName DESC
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
12.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,...)
Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns:
Query
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
13.The UPDATE Statement
The UPDATE statement is used to update existing records in a table.
Syntax
UPDATE table_name SET column1=value, column2=value2,...
WHERE some_column=some_value
Example
UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob'
14.The DELETE Statement
The DELETE statement is used to delete rows in a table.
Query
DELETE FROM table_name WHERE some_column=some_value
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!
Example
DELETE FROM Persons WHERE LastName='Tjessem' AND FirstName='Jakob'
SQL ADVANCE
15.The TOP Clause
The 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.
Syntax
SELECT TOP number|percent column_name(s) FROM table_name
Example
SELECT column_name(s) FROM table_name LIMIT number
SELECT * FROM Persons LIMIT 5
SELECT TOP 2 * FROM Persons
SELECT TOP 50 PERCENT * FROM Persons
16.The LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern
Example
SELECT * FROM Persons WHERE City LIKE 's%'
SELECT * FROM Persons WHERE City LIKE '%s'
SELECT * FROM Persons WHERE City LIKE '%tav%'
SELECT * FROM Persons WH0.ERE City NOT LIKE '%tav%'
17.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
Example
SELECT * FROM Persons WHERE FirstName LIKE '_la'
SELECT * FROM Persons WHERE LastName LIKE 'S_end_on'
SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%'
18.The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...)
Example
SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen')
19.The BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2
Example
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'
SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'
20.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.
Syntax
SELECT column_name(s) FROM table_name AS alias_name
Syntax for Columns
SELECT column_name AS alias_name FROM table_name
Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the table aliases of "p" and "po" respectively.
Now we want to list all the orders that "Ola Hansen" is responsible for.
We use the following SELECT statement with Aliases:
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p,Product_Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola'
The same SELECT statement without aliases:
SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons,
Product_Orders
WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'
21.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.
Look at 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
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.
Next, we have the "Orders" table:
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
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.
Notice that the relationship between the two tables above is the "P_Id" column.
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
INNER JOIN Example
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
SQL LEFT JOIN Keyword
LEFT JOIN Example
22.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).
Syntax
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name
Example
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
23.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).
Syntax
SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name
Example
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
24.FULL JOIN
The FULL JOIN keyword return rows when there is a match in one of the tables.
Syntax
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name
25.SQL UNION
The SQL UNION operator combines two or more SELECT statements.
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.
Syntax
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2
SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
Example
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
--------------------------------------------------------------------------
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
26.SQL SELECT INTO
The SELECT INTO statement selects data from one table and inserts it into a different table.
The SELECT INTO statement is most often used to create backup copies of tables.
Syntax
We can select all columns into the new table:
SELECT * INTO new_table_name [IN externaldatabase] FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_tablename
Examples
SELECT * INTO Persons_Backup FROM Persons.
SELECT LastName,FirstName INTO Persons_Backup FROM Persons.
27.The CREATE TABLE Statement
The CREATE TABLE statement is used to create a table in a database.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
28.NOT NULL Constraint
By default, a table column can hold NULL values.
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)
)
29.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.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
Syntax
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)
)
30.SQL PRIMARY KEY
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.
SQL PRIMARY KEY Constraint on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:
MySQL:
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)
)
31.SQL FOREIGN KEY
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:
Example
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)
)
32.INDEX
The CREATE INDEX statement is used to create indexes in tables.
Indexes allow the database application to find data fast; without reading the whole table.
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
33.SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.
Example
The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons" table:
CREATE INDEX PIndex
ON Persons (LastName)
If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
CREATE INDEX PIndex
ON Persons (LastName, FirstName)
34.DROP INDEX
The DROP INDEX statement is used to delete an index in a table.
Syntax
DROP INDEX index_name ON table_name
ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
Syntax
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
35.AUTO INCREMENT a Field
Very often we would like the value of the primary key field to be created automatically every time a new record is inserted.
We would like to create an auto-increment field in a table.
Syntax
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table:
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)
)
Syntax
CREATE TABLE Persons
(
P_Id int PRIMARY KEY IDENTITY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
36.SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
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.
37.SQL Dates
Note The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the most important built-in functions for working with dates.
MySQL Date Functions
The following table lists the most important built-in date functions in MySQL:
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
38.SQL Server Date Functions
The following table lists the most important built-in date functions in SQL Server:
Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds or subtracts a specified time interval from a date
DATEDIFF() Returns the time between two dates
CONVERT() Displays date/time data in different formats
------------------------------------------------------------------------------------------------------------
No comments:
Post a Comment