W3S SQL
W3S SQL
--LEFT JOIN keyword returns all records from the left table,
and matched records from the right table. The result is NULL
from the right side if there is no match.
SELECT column_names FROM table1 LEFT JOIN table2 ON
table1.column_name = table2.column_name;
--RIGHT JOIN keyword returns all records from the right table
and the matched records from the left table. The result is
NULL from the left side, when there is no match.
SELECT column_names FROM table1 RIGHT JOIN table2 ON
table1.column_name = table2.column_name;
--A self JOIN is a regular join, but the table is joined with
itself.
SELECT column_names FROM table1 T1, table1 T2 WHERE condition;
--The HAVING clause was added to SQL because the WHERE keyword
could not be used with aggregate functions.
SELECT column_names FROM table_name WHERE condition GROUP BY
column_names HAVING condition ORDER BY column_name;
--The ANY and ALL operators are used with a WHERE or HAVING
clause
--The ANY operator returns true if any of the subquery values
meet the condition
SELECT column_names FROM table_name WHERE column_name operator
ANY
(SELECT column_name FROM table_name WHERE condition);
--The ALL operator returns true if all of the subquery values
meet the condition
SELECT column_names FROM table_name WHERE column_name operator
ALL
(SELECT column_name FROM table_name WHERE condition);
--The SELECT INTO statement copies data from one table into a
new table.
--Copy all columns into a new table:
SELECT * INTO newtable [IN externaldb] FROM oldtable WHERE
condition;
--Copy some columns into a new table:
SELECT column1, column2, ... INTO newtable [IN externaldb]
FROM oldtable WHERE condition;
--The INSERT INTO SELECT statement copies data from one table
and inserts it into another table. It requires that data types
in source and target tables match. The existing records in the
target table are unaffected.
--Copy all columns from one table to another table:
INSERT INTO table2 SELECT * FROM table1 WHERE condition;
--Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, ...) SELECT column1,
column2, ...
FROM table1 WHERE condition;
--A stored procedure is a prepared SQL code that you can save,
so the code can be reused over and over again. So if you have
an SQL query that you write over and over again, save it as a
stored procedure and then call it to execute it. You can pass
parameters to a stored procedure, so that the stored procedure
can act based on the parameter values that is passed.
--Creates a stored procedure: (parameter is optional)
-CREATE PROCEDURE procedure_name @parameter_name data_type
AS sql_statement
GO;
--Executes a stored procedure:
EXEC procedure_name;
--Example:
CREATE PROCEDURE SelectALLCustomers @City nvarchar(30)
AS SELECT * FROM Customers WHERE City = @City
GO;
SQL database
--Data types:
/*
CHAR(size) fixed length string, 255 characters max
VARCHAR(size) variable length string, 255 characters max
TINYTEXT string with max length 255 characters
TEXT String with max length 65,535 characters
BLOB for Binary Large Objects, 65,535 bytes of data
MEDIUMTEXT string with max length 16,777,215
MEDIUMBLOB for BLOBs, 16,777,215 bytes of data
LONGTEXT string with max length 4,294,967,295
LONGBLOB for BLOBs, 4,294,967,295 bytes of data
ENUM(x,y,z,…) can enter list of possible values, 65535 list
size
Values stored in order you enter
SET Can store up to 64 items and more than one
choice
/*
SQL constraints are used to specify rules for the data in a
table.
Constraints are used to limit the type of data that can go
into a table. This ensures the accuracy and reliability of the
data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints
apply to the whole table.
Following constraints are commonly used:
Can have many UNIQUE constraints per table but only one
PRIMARY KEY
PRIMARY KEY may consists of single or multiple fields,
composite key
Table containing the foreign key is called the child table,
and the table containing the candidate key is called the
referenced or parent table. FOREIGN KEY is used to link two
table together. The FOREIGN KEY constraint is used to prevent
actions that would destroy links between tables. The FOREIGN
KEY constraint also prevents invalid data from being inserted
into the foreign key column, because it has to be one of the
value contained in the table it points to. CHECK constraint
used to limit value range that can be in a column.
*/
--MySQL:
CREATE TABLE Persons (
....
PersonID PRIMARY KEY (ID,LastName) --composite primary
key
Age int CHECK (Age>=18) DEFAULT 18
);
--For alter:
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
--Foreign key
CREATE TABLE Orders (
....
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
--To create an index
CREATE INDEX index_name ON table_name (col1, col2, ...);
--To create an unique index
CREATE UNIQUE INDEX index_name ON table_name (col1,
col2, ...);
/*
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.
MySQL has the following data types for dates and times:
DATE YYYY-MM-DD
DATETIME YYYY-MM-DD HH:MI:SS
TIMESTAMP YYYY-MM-DD HH:MI:SS
YEAR YYYY or YY
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. Views always show up-to-date
data. The database engine recreates the data, using the view’s
SQL statement, every time the user queries a view.
*/
CREATE VIEW view_name AS SELECT col1, col2, ...
FROM table_name WHERE condition;
--A view can be updated using CREATE OR REPLACE VIEW command:
CREATE OR REPLACE VIEW view-name AS SELECT col1, col2, ...
FROM table_name WHERE condition;
--View can also be dropped
DROP VIEW view_name;
/*
SQL injection is a code injection technique that has the
potential to destroy your database. It is one of the most
common web hacking techniques. SQL injection is the placement
of malicious code in SQL statements via web page input.
SQL injection usually occurs when you ask a user for input,
like their uername/userid, and instead of a name/id, the user
gives you an SQL statement that you will unknowingly run on
your database.
The following example creates a SELECT statement by adding a
variable to a select string. The variable is fetched from user
input:
txtUserId = getRequestString(“UserId”);
txtSQL = “SELECT * FROM Users WHERE UserId = “ + txtUserId;
To protect a web site from SQL injection, you can use SQL
parameters. SQL parameters are values that are added to an SQL
query at execution time, in a controlled manner. 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.
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. You may need to
look for SQL hosting plans with your ISP. The most common SQL
hosting databases are MS SQL Server, Oracle, MySQL, and MS
Access.
MS SQL Server is popular for websites with high traffic, very
powerful, robust and full featured SQL database system.
Oracle is a popular database software for websites with high
traffic, powerful, robust, full featured SQL database system,
but is run by assholes who only want your money.
MySQL is a popular choice for web sites, powerful, robust and
full featured SQL database system. Inexpensive alternative to
expensive Mirosoft and Oracle solutions
Access is great for simple databases, not suited for high-
traffic, and not as powerful as the rest.
Bitwise operators:
& AND
| OR
^ exclusive OR
Compound operators
+= Add equals
-= Subtract equals
*= Multiple equals
/= Divide equals
%= Modulo equals
&= AND equals
^-= exclusive equals
|*= OR equals