sql notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

09 October 2024 15:15

DB: collection of interrrelated data.


DBMS: s/w used to create manage & organize DB
RDBMS: a DBMS based on concept of tables (relations)
Data is organized into table(relations) with rows(records) and columns(attributes/fields). Data is
stored in DB obj's called tables(coll of related data entries consists of rows and col's).
MYSQL, Postgre SQL, Oracle
SQL: used to store manipulate and retrieve data frm DB
A language used to interact with DB
Use for CRUD oper's:
CREATE: DB's, tables, insert tuples in tables (tuple: a coll of attbu val's
READ: data present in DB
UPDATE: modify already inserted data
DELETE: DB, table or specific data point/ tuple/ row/s
• In RDB a tuple is single row in a table that contains a single record for a rel'n, row is a record of a set of attrb's.
tuples are ordered and unchangeable collec of data.
• A record in SQL is a single entry in a table (row)
• Records are coll of data that are organized into fields within a table

SQL keywords not case sensitive


SQL is language used to perform CRUD oper's in RDB, while MYSQL is a RDBMS that uses SQL
SQL DATA TYPES:
DT define kind of data stored in col or variable
CHAR is fixed len VARCHAR is variable len strings, VARCHAR is better occupes necessary mem & works
more effi

TYPES OF SQL COMMANDS:


DQL: retrieve data frm DB's
SELECT
DDL: create, alter, delete DB obj's like tables indexes
CREATE DROP ALTER RENAME TRUNCATE
DML: modify the DB
INSERT UPDATE DELETE
DCL: grant & revoke permissions
GRANT REVOKE
TCL: manage transactions
COMMIT, ROLLBACK, START TRANSACTIONS, SAVEPOINT

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

SELECT DISTINCT - return only distinct values


WHERE clause - to extract only those records that fulfil condition
Used in SELECT UPDATE DELETE
Follow operator can be used in where clause
<> - not equal (some versions of SQL !=)
BETWEEN - certain range
LIKE - search for a pattern (CustomerName LIKE 'G%')
IN to specify multiple possible values for a column
ORDER BY __ ASC|DESC - to sort the result-set in asc or desc
Country, CustomerName - it order by country, but if some rows have same country it orders
them by CustomerName.
Country ASC, Sorted asc by country and desc by customername
CustomerName DESC
String DESC Alphabetically reversed
AND - all conditions
OR - any conditions
SELECT * FROM Customers;
WHERE Country = 'Spain' AND (CustomerName LIKE 'g%' OR CustomerName LIKE 'R%')
NOT, NOT LIKE, NOT BETWEEN 10 AND 60, NOT IN
INSERT INTO - insert new records
INSERT INTO tablename (col1, col2, …) {no col's need if adding all col's, order imp}
VALUES (val1, v2,….), (v1,v2,…) {rows}
CustomerID is an auto-increment field
IS NULL / IS NOT NULL
UPDATE tablename
SET col1 = val, col2= val2, …
WHERE condition;
If you omit the WHERE clause, ALL records will be updated
DELETE FROM tablename WHERE condition;
DELETE FROM tablename; - deletes all rows in table while keeping attrbs, indexes, table structure intact.
SELECT TOP - used to specify the no.of records to return.
SELECT TOP 3 * FROM Customers; - first 3 records
MySQL supports LIMIT clause
Oracle FETCH FIRST n ROWS ONLY and ROWNUM
SELECT TOP 50 PERCENT * FROM tablename;
SELECT TOP 3 * FROM customers ORDER BY CustomerName DESC;

SQL AGGREGATE FUNCTIONS


Func that performs cal on a set of vals and returns a single val
Used with GROUP BY clause (splits the result-set into grps) of SELECT statement
MIN() - smallest val within selected col
MAX() - returns largest val
COUNT() - no of rows in set
SUM() - total sum of a numerical col
AVG() - avg val of a numerical col
Aggregate func ignore null val (expect for COUNT())

SELECT MIN(col) AS name FROM tablename WHERE condition;


SELECT MIN(Price) AS name, CategoryID FROM Products GROUP BY CategoryID;

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;

GROUP BY clause - grps rows with same vals in specified cols


Use aggregate func to summarize grped data

SELECT COUNT(*) AS [Number of records], CategoryID


FROM Products
GROUP BY CategoryID;
COUNT(*) AS [Number of records]: This counts the number of rows for each CategoryID.
GROUP BY CategoryID: This groups the rows by CategoryID, so the count is calculated for each
unique category.

SUM() func - total sum of numeric col


SELECT SUM(col) AS name FROM table WHERE cond; / GROUP BY col;
SELECT SUM(col * 10) FROM table;

AVG() NULL values are ignored


returns the average value of a numeric column.

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.

** Supported only in Oracle databases.

IN, NOT IN operator


specify multiple values in a WHERE clause.
shorthand for multiple OR conditions.
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

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';

Aliases is optional (AS KEYWORD)


used to give a table, or a column in a table, a temporary name.
SELECT column_name AS [alias name] FROM table_name;

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;

JOIN and INNER JOIN return same result


LEFT JOIN result is 0 records frm right side if there is no match vice versa

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName


FROM ((Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

select all customers, and any orders they might have:


SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
LEFT JOIN keyword returns all records from the left table (Customers), even if there are no matches in the
right table (Orders).

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;

UNION/ UNION ALL

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);

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders


FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

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;

SELECT Customers.CustomerName, Orders.OrderID


INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

INSERT INTO SELECT


copies data from one table and inserts it into another table.
data types in source and target tables match
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

INSERT INTO Customers (CustomerName, City, Country)


SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

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;

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)


AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

-- single line comments


/* and */

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;

CREATE TABLE Persons (


PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
From existing table
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

DROP TABLE table_name;


drop an existing table in a database.
TRUNCATE TABLE table_name;
used to delete the data inside a table, but not the table itself
ALTER TABLE
used to add, delete, or modify columns in an existing table.

ALTER TABLE table_name


ADD column_name datatype;

ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE table_name


RENAME COLUMN old_name to new_name;

ALTER TABLE table_name


ALTER COLUMN column_name datatype;

SQL constraints are used to specify rules for data in a table.


Constraints are used to limit the type of data that can go into a table.
NOT NULL - Ensures that a column cannot have a NULL value
ALTER TABLE Persons
ALTER COLUMN Age int NOT NULL;

sql Page 7
ALTER COLUMN Age int NOT NULL;

UNIQUE - Ensures that all values in a column are different


CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

ALTER TABLE Persons


ADD UNIQUE (ID); / ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

ALTER TABLE Persons


DROP CONSTRAINT UC_Person;

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)
);

ALTER TABLE Persons


ADD PRIMARY KEY (ID); / ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

ALTER TABLE Persons


DROP CONSTRAINT PK_Person;

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;

DEFAULT - Sets a default value for a column if no value is specified


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;

ALTER TABLE Persons


ALTER COLUMN City DROP DEFAULT;

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, ...);

DROP INDEX table_name.index_name;

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;

S SQL Server uses the IDENTITY keyword to perform an auto-increment feature.


CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy