sql notes
sql notes
sql notes
All records
SELECT * FROM Customers;
SELECT - extract data frm DB
UPDATE - updates data in DB
DELETE - deletes data frm DB
INSERT INTO - inserts new data into DB
CREATE DATABASE- creates new DB
ALTER DATABASE - modifies a DB
CREATE TABLE - create new table
ALTER TABLE - modifies table
DROP TABLE - delete table
CREATE INDEX - create index (search key)
sql Page 1
CREATE INDEX - create index (search key)
DROP INDEX - delete index
sql Page 2
COUNT() - no. of rows that match criterion; *-in table
SELECT COUNT(colname/*) FROM tablename WHERE condition;
SELECT COUNT(DISTINCT Price) AS name FROM Products;
LIKE NOT LIKE used in a WHERE clause to search for a specified pattern in a column.
(Wildcard) character is used to substitute one or more characters in a string.
% rep zero, one or multi char
_ rep one, single char
[] Represents any single character within the brackets *
if any of the characters inside gets a match.[bsp]%
^ Represents any character not in the brackets *
- Represents any single character within the specified range *
specify a range of characters inside the [] wildcard. [a-f]%
{} Represents any escaped character **
* Not supported in PostgreSQL and MySQL databases.
BETWEEN, NOT BETWEEN operator inclusive operator selects values within a given range. The values can be
numbers, text, or dates.
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
'1996-07-01' AND '1996-07-31';
sql Page 3
SELECT column_name AS [alias name] FROM table_name;
SELECT column_name(s) FROM table_name AS "alias name";
Concatenate col:
SELECT CustomerName, Address + ', ' + PostalCode+ ' ' + City + ', '+Country AS address FROM
Customers;
SELECT col, CONCAT(,,' ',) FROM
SELECT o.OrderId, o.OrderDate, c.CustomerName
FROM Customers AS c, Order AS o
WHERE c.Customername = 'Around' AND c.custID = o.custID;
JOIN clause - combine rows from 2 or more tables, based on a related col between them
INNER JOIN - selects records that have matching val in both tables (rows in match)
LEFT (OUTER) JOIN - ret all records from left table, and the matched records from the right table
RIGHT (OUTER) JOIN - ret all records frm right and matched frm left
FULL (OUTER) JOIN - ret all records where there is a match in either left or right table
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
return all employees, and any orders they might have placed:
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
FULL OUTER JOIN and FULL JOIN are the same
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
SELF JOIN - regular join, but the table is joined with itself
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
sql Page 4
UNION/ UNION ALL
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL / UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
GROUP BY
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
HAVING clause
Coz WHERE keyword cannot be used with aggregate funs
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
EXISTS operator
is used to test for the existence of any record in a subquery.
returns TRUE if the subquery returns one or more records.
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID
AND Price = 22);
ANY / ALL
ANY(returns TRUE if ANY of the subquery values meet the condition) and ALL(returns TRUE if ALL of the
subquery values meet the condition, is used with SELECT, WHERE and HAVING statements) operators
allow you to perform a comparison between a single column value and a range of other values.
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
SELECT ProductName
FROM Products
sql Page 5
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
return FALSE because the Quantity column has many different values (not only the value of 10)
SELECT INTO
copies data from one table into a new table.
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the
parameter value(s) that is passed.
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
EXEC SelectAllCustomers;
sql Page 6
/* and */
CREATE DATABASE
used to create a new SQL database.
DROP DATABASE databasename;
drop an existing SQL database.
BACKUP DATABASE
create a full back up of an existing SQL database.
BACKUP DATABASE databasename
TO DISK = 'filepath';
A differential back up only backs up the parts of the database that have changed since the last full
database backup.
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
sql Page 7
ALTER COLUMN Age int NOT NULL;
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
A table can have only ONE primary key; and in the table, this primary key can consist of single or
multiple columns (fields).
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
FOREIGN KEY - Prevents actions that would destroy links between tables
The table with the foreign key is called the child table, and the table with the primary key is called
the referenced or parent table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the parent table.
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
sql Page 8
CHECK - Ensures that the values in a column satisfies a specific condition
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
ALTER TABLE Persons
ADD CHECK (Age>=18);
ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;
CREATE INDEX - Used to create and retrieve data from the database very quickly
create an index on a combination of columns
CREATE UNIQUE(no duplicates) INDEX index_name
ON table_name (column1, column2, ...);
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a
table.
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
ALTER TABLE Persons AUTO_INCREMENT=100;
sql Page 9
);
CREATE VIEW
a view is a virtual table based on the result-set of an SQL statement.
fields in a view are fields from one or more real tables in the database.
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
SELECT * FROM [Products Above Average Price];
CREATE OR REPLACE VIEW
DROP VIEW view_name;
SQL Injection
code injection technique that might destroy your database.
one of the most common web hacking techniques.
placement of malicious code in SQL statements, via web page input.
Based on 1=1 is Always True
SELECT * FROM Users WHERE UserId = 105 OR 1=1;
OR 1=1 is always TRUE.
Based on ""="" is Always True
OR ""="" is always TRUE.
Batched SQL Statements
105; DROP TABLE Suppliers
SQL parameters are values that are added to an SQL query at execution time
parameters are represented in the SQL statement by a @ marker.
The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally,
and not as part of the SQL to be executed.
SQL Hosting
If you want your web site to be able to store and retrieve data from a database, your web server should
have access to a database-system that uses the SQL language.
common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS Access.
MS Access(simple db) is not well suited for very high-traffic, and not as powerful as MySQL, SQL Server,
or Oracle(popular database softwares for database-driven web sites with high traffic; very powerful,
robust and full featured SQL database system).
MySQL is an inexpensive alternative to the expensive Microsoft and Oracle solutions.
sql Page 10