Labmanual
Labmanual
What is SQL?
Database Tables
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.
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
SQL Comments
Comments are used to explain sections of SQL statements, or to prevent execution of SQL
statements.
Any text between -- and the end of the line will be ignored (will not be executed).
Example:
--Select all:
SELECT * FROM Customers;
2. Multi-line Comments
Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored.
Example:
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:
The PersonID column is of type int and will hold an integer. The LastName, FirstName, Address,
and City columns are of type varchar and will hold characters, and the maximum length for these
fields is 255 characters.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
ALTER TABLE student ADD id int not null primary key(id); // to add PK
ALTER TABLE instructor ADD id int foreign key references departmen(Dnum)// to add FK
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
The following SQL deletes the "Email" column from the "Customers" table:
To change the data type of a column in a table, use the following syntax:
SQL Server:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
Constraints can be specified when the table is created with the CREATE TABLE statement, or after
the table is created with the ALTER TABLE statement.
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT
accept NULL values. This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and
PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A
PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many
UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:
The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain
UNIQUE values, and cannot contain NULL values. A table can have only one primary key, which
may consist of single or multiple fields.
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are
trying to insert, matches the format of the date column in the database. As long as your data contains
only the date portion, your queries will work as expected. However, if a time portion is involved, it
gets more complicated.
Note: The date types are chosen for a column when you create a new table in your database!
The SELECT statement is used to select data from a database. The data returned is stored in a result
table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
The following SQL statement selects all the columns from the "Customers" table:
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a
column often contains many duplicate values; and sometimes you only want to list the different
(distinct) values.
The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:
The WHERE clause is used to filter records. The WHERE clause is used to extract only those
records that fulfill a specified condition.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE
statement, etc.!
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
= [equal], <> (!=) [not equal], > [greater than],< [Less than], >= [greater than or equal], <= []less
than or equal, BETWEEN [Between a certain range],IN [To specify multiple possible values for a
column], LIKE [Search for a pattern]
The WHERE clause can be combined with AND, OR, and NOT operators. The AND and OR
operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
The following SQL statement selects all fields from "Customers" where country is "Germany" AND
city is "Berlin":
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The
ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
The following SQL statement selects all customers from the "Customers" table, sorted ascending by
the "Country" and descending by the "CustomerName" column:
It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will
have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
The following SQL lists all customers with a NULL value in the "Address" field:
The INSERT INTO statement is used to insert new records in a table. It is possible to write the
INSERT INTO statement in two ways. The first way specifies both the column names and the values
to be inserted:
If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. The INSERT INTO syntax would be as follows:
The following SQL statement inserts a new record in the "Customers" table:
It is also possible to only insert data in specific columns. The following SQL statement will insert a
new record, but only insert data in the "CustomerName", "City", and "Country" columns
(CustomerID will be updated automatically):
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
It is the WHERE clause that determines how many records that will be updated.
The following SQL statement will update the contactname to "Juan" for all records where country is
"Mexico":
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
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:
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
The MIN() function returns the smallest value of the selected column. The MAX() function returns
the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
The following SQL statement finds the price of the cheapest product:
The following SQL statement finds the price of the most expensive product:
The COUNT() function returns the number of rows that matches a specified criteria. The AVG()
function returns the average value of a numeric column. The SUM() function returns the total sum of
a numeric column.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
SELECT COUNT(ProductID)
FROM Products;
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
SELECT SUM(Quantity)
FROM OrderDetails;
Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE
clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
The following SQL statement selects all customers with a CustomerName starting with "a":
The following SQL statement selects all customers with a CustomerName ending with "a":
The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used
to make column names more readable. An alias only exists for the duration of the query.
Alias Column Syntax
SELECT column_name AS alias_name
FROM table_name;
The following SQL statement creates two aliases, one for the CustomerID column and one for the
CustomerName column:
The following SQL statement creates two aliases, one for the CustomerName column and one for the
ContactName column. Note: It requires double quotation marks or square brackets if the alias name
contains spaces:
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from
the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
The INNER JOIN keyword selects records that have matching values in both tables.
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records
from the right table (table2). The result is NULL from the right side, if there is no match.
The following SQL statement will select all customers, and any orders they might have:
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records
from the left table (table1). The result is NULL from the left side, when there is no match.
The following SQL statement will return all employees, and any orders they might have placed:
The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or
right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!
The following SQL statement selects all customers, and all orders:
Let us consider table named Employee and with using this table write different SQL Queries
Query 1 : List the employee whose employee number is 100.
Answer:
Simple where clause is used to write this query,
Select * from Employee where employee_Num=100;
Query 4 : List the Employees whose name starts with A and surname starts with S.
Answer :
We need to use like operator to achieve this,
Select * from Employees where name like ‘A%’ and surname like ‘S%’;
Query 12 : Find Query to get information of Employee where Employee is not assigned to
the department
Answer: