SQL DBMS
SQL DBMS
SQL
SQL — Structured Query Language (is a standard language for interacting
with RDBMS)
Data sharing
DDL (Data Definition Language) — deals with creation of the database and
modifies
SQL 1
DML (Data Manipulation Language) — mainly deals with querying the data in
the database
Use of SQL (Structured Query Language) for querying and managing data
https://www.youtube.com/watch?v=OqjJjpjDRLc
Relational: Data is stored in a tabular format using rows for individual records
and columns to store attributes or data points related to the records.
Key-Value: Data is stored in a dictionary format with each item having a key
and value.
Graph: Data is stored as a knowledge graph using nodes, edges to define the
relationship between these nodes, and properties that store individual data
points.
SQL 2
https://www.youtube.com/watch?v=_Ss42Vb1SU4
SELECT
#syntax
Select select_list
from table_name
select option1,option2,...
from table_name;
SQL 3
select age
from employee;
select age,
lastname,
firstname
from employee
select 1+1;
+-------+
|1+1|
+-------+
| 2|
+-------+
1 row in set (0.00 sec)
select now();
+---------------------+
| NOW() |
+---------------------+
| 2021-07-26 08:08:02 |
+---------------------+
1 row in set (0.00 sec)
select concat('billo','','bagge');
+--------------------------+
| CONCAT('John',' ','Doe') |
SQL 4
+--------------------------+
| John Doe |
+--------------------------+
1 row in set (0.00 sec)
SELECT DISTINCT
SELECT ORDER BY
You use ASC to sort the result set in ascending order and DESC to sort the result
set in descending order.
By default, the ORDER BY clause uses ASC if you don’t explicitly specify any option
SQL 5
ORDER BY
column1 ASC,
column2 DESC;
First, sort the result set by the values in the column1 in ascending order.
Then, sort the sorted result set by the values in the column2 in descending
order. Note that the order of values in the column1 will not change in this step,
only the order of values in the column2 changes.
SELECT
orderNumber,
orderlinenumber,
quantityOrdered * priceEach
FROM
orderdetails
ORDER BY
quantityOrdered * priceEach DESC;
+-------------+-----------------+-----------------------------+
| orderNumber | orderlinenumber | quantityOrdered * priceEach |
+-------------+-----------------+-----------------------------+
| 10403 | 9| 11503.14 |
| 10405 | 5| 11170.52 |
| 10407 | 2| 10723.60 |
| 10404 | 3| 10460.16 |
| 10312 | 3| 10286.40 |
...
SQL Comments
SQL 6
--select all;
select * from table_name
SQL WHERE
Operator Description
= Equal
Not equal. Note: In some versions of SQL this operator may be written as
<>
!=
SQL 7
WHERE Price BETWEEN 50 AND 60;
SELECT
firstName,
lastName
FROM
employees
WHERE
lastName LIKE '%son'
ORDER BY firstName;
+-----------+-----------+
| firstName | lastName |
+-----------+-----------+
| Leslie | Thompson |
| Mary | Patterson |
| Steve | Patterson |
| William | Patterson |
+-----------+-----------+
4 rows in set (0.00 sec)
-- example in operator
SELECT * FROM Customers
WHERE City IN ('Paris','London');
SELECT
lastName,
firstName,
reportsTo
SQL 8
FROM
employees
WHERE
reportsTo IS NULL;
+----------+-----------+-----------+
| lastName | firstName | reportsTo |
+----------+-----------+-----------+
| Murphy | Diane | NULL |
+----------+-----------+-----------+
1 row in set (0.01 sec)
AND OPERATOR
The AND operator is a logical operator that combines two or
more Boolean expressions and returns 1, 0, or NULL
A AND B
select A and B;
+---------+
| 1 AND 1 |
+---------+
| 1|
+---------+
1 row in set (0.00 sec)
SQL 9
select 1 and 0, 0 and 1, 0 and 0, 0 and null;
+---------+---------+---------+------------+
| 1 AND 0 | 0 AND 1 | 0 AND 0 | 0 AND NULL |
+---------+---------+---------+------------+
| 0| 0| 0| 0|
+---------+---------+---------+------------+
1 row in set (0.00 sec)
SELECT
customername,
country,
state,
creditlimit
FROM
customers
WHERE
country = 'USA' AND
state = 'CA' AND
creditlimit > 100000;
+------------------------------+---------+-------+-------------+
| customername | country | state | creditlimit |
+------------------------------+---------+-------+-------------+
| Mini Gifts Distributors Ltd. | USA | CA | 210500.00 |
SQL 10
| Collectable Mini Designs Co. | USA | CA | 105000.00 |
| Corporate Gift Ideas Co. | USA | CA | 105000.00 |
+------------------------------+---------+-------+-------------+
3 rows in set (0.00 sec)
The AND operator returns true when both expressions are true; otherwise, it
returns false
OR Operator
A or B
if both A and B are not NULL, the OR operator returns 1 (true) if either A or B is
non-zero.
select 1 or 1, 1 or 0, 0 or 1;
+--------+--------+--------+
| 1 OR 1 | 1 OR 0 | 0 OR 1 |
+--------+--------+--------+
| 1| 1| 1|
+--------+--------+--------+
1 row in set (0.00 sec)
SELECT
first_name,
SQL 11
last_name,
hire_date,
department_id
FROM
employees
WHERE
department_id = 3
AND
EXTRACT(year from hire_date) = 1999 OR
EXTRACT(year from hire_date) = 2000
ORDER BY
hire_date;
NOT operator
The NOT operator is used in combination with other operators to give the opposite
result, also called the negative result.
If the condition is true , the NOT operator makes it false and vice versa. However, if
the condition is NULL , the NOT operator returns NULL .
SQL 12
SELECT
first_name,
salary
FROM
employees
WHERE
NOT salary >= 3000;
first_name | salary
------------+---------
Shelli | 2900.00
Sigal | 2800.00
Guy | 2600.00
Karen | 2500.00
Irene | 2700.00
IN Operator
The IN operator allows you to determine if a value matches any value in a list of
values. Here’s the syntax of the IN operator:
The IN operator return 1 (true) if they value equals any value in the list ( value1 ,
value2 , value3 , …) otherwise it returns 0.
SELECT 1 IN (1,2,3);
+--------------+
| 1 IN (1,2,3) |
+--------------+
SQL 13
| 1|
+--------------+
1 row in set (0.00 sec)
SELECT
officeCode,
city,
phone,
country
FROM
offices
WHERE
country IN ('USA' , 'France');
+------------+---------------+-----------------+---------+
| officeCode | city | phone | country |
+------------+---------------+-----------------+---------+
|1 | San Francisco | +1 650 219 4782 | USA |
|2 | Boston | +1 215 837 0825 | USA |
|3 | NYC | +1 212 555 3000 | USA |
|4 | Paris | +33 14 723 4404 | France |
+------------+---------------+-----------------+---------+
4 rows in set (0.01 sec)
SELECT
first_name,
last_name,
job_id
FROM
employees
WHERE
job_id IN (8, 9, 10)
ORDER BY
job_id;
SQL 14
first_name | last_name | job_id
------------+-----------+--------
Susan | Mavris | 8
Bruce | Ernst | 9
David | Austin | 9
Alexander | Hunold | 9
Diana | Lorentz | 9
Valli | Pataballa | 9
Michael | Hartstein | 10
NOT IN OPERATOR
The NOT IN operator returns one if the value doesn’t equal any value in the list.
Otherwise, it returns 0.
SQL 15
select null not in (1,2,3)
+---------------------+
| NULL NOT IN (1,2,3) |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
The following example uses the NOT IN operator to find the offices that are not
located in France and the USA
BETWEEN OPERATOR
The BETWEEN operator is logical operator that specifies whether a value is in a
range or not.
otherwise it returns 0.
SQL 16
select employee_id, first_name, last_name, salary from employees
where salary between 2500 and 2900
order by salary;
NOT BETWEEN — to negate the result of the BETWEEN operator you use the NOT
operator:
The NOT BETWEEN returns true if the expression is less than low or greater
than high ; otherwise, it returns false .
LIKE OPERATOR
SQL 17
The LIKE operator is a logical operator that tests whether a string contains a
specified pattern or not.
in this syntax, if the expression matches the pattern , the like operator returns 1.
otherwise it returns 0.
MySQL provides two wildcard characters for constructing patterns:
Percentage % and underscore _ .
Expression Meaning
match a string that includes the string are and ends with one
LIKE '%are_'
character.
match a string that includes the string are , starts with one
LIKE '_are%'
character and ends with any number of characters.
first_name | last_name
------------+-----------
Daniel | Faviet
David | Austin
SQL 18
NOT LIKE
To negate the result of a LIKE operator, you use the NOT operator:
first_name | last_name
------------+-----------
Sarah | Bell
Sigal | Tobias
Steven | King
Susan | Mavris
value is NULL
result
--------
NULL
SQL 19
SELECT customerName, country, salesrepemployeenumber
FROM customers
WHERE salesrepemployeenumber IS NULL
ORDER BY customerName;
+--------------------------------+--------------+------------------------+
| customerName | country | salesrepemployeenumber |
+--------------------------------+--------------+------------------------+
| ANG Resellers | Spain | NULL |
| Anton Designs, Ltd. | Spain | NULL |
| Asian Shopping Network, Co | Singapore | NULL |
| Asian Treasures, Inc. | Ireland | NULL |
...
-- IS NULL
SELECT column_names
FROM table_name
WHERE column_name IS NULL
-- IS NOT NULL
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Use the IS NULL operator to test if a value is NULL or not. The IS NOT
The value IS NULL returns true if the value is NULL or false if the value is not
NULL.
The value IS NOT NULL returns true if the value is not NULL or false if the value is
NULL.
UPDATE STATEMENT
SQL 20
The UPDATE statement is used to modify the existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
-- here the rows which contains mexico will set their contact_name to juan
UPDATE Customers
SET ContactName='Juan';
INSERT STATEMENT
The INSERT INTO statement is used to insert new records in a table
/* 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
SQL 21
the values is in the same order as the columns in the table. */
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
DELETE STATEMENT
The DELETE statement is used to delete existing records in a table.
SQL 22
delete from coutomers where coutomername = "Alfreds Futterkiste";
--it will delete the whole row which contains the coustomer_name "Alfreds Fut
terkiste"
Delete all records — here all the data means rows gets deleted while keeping the
table intact with their attributes and indexes
Not all database systems support the SELECT TOP clause. MySQL supports
the LIMIT clause to select a limited number of records, while Oracle
uses FETCH FIRST n ROWS ONLY and ROWNUM .
SQL 23
FROM table_name
WHERE condition;
-- MySQL Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
LIMIT
FETCH FIRST
SQL 24
SQL AGGREGATE Functions —
An aggregate function in SQL performs a calculation on a set of values and
returns a single summary value.
-- MIN()
select MIN(column_name)
from table_name
where condition;
select MAX(column_name)
from table_name
where condition;
When you use MIN() or MAX() , the returned column will not have a descriptive
name. To give the column a descriptive name, use the AS keyword:
SQL 25
SQL COUNT() Function
The COUNT() function returns the number of rows that matches a specified
criterion.
You can specify a column name instead of the asterix symbol (*) .
If you specify a column name instead of (*) , NULL values will not be counted.
-- to ignore duplicates
select count(distinct column_name)
from table_name;
-- use an alice
select count (column_name) as [number of records]
from tavble_name
SQL 26
select sum(column_name)
from table_name
where condition;
-- with alias
-- Name the column "total":
select sum (Quantity) as total
from OrderDetails
select avg(column_name)
from table_name
where condition;
SQL 27
-- add WHERE clause
select avg(Price)
from Products
where CategoryID = 1;
-- use an alias
-- Name the column "average price":
select avg(Price) as [average price]
from Products;
-- Return all products with a higher price than the average price:
select * from Products
where price > (select avg(price) from Products);
SQL Wildcards
Symbol Description
SQL 28
-- Using the _ Wildcard (It can be any character or number, but each _ represe
nts one, and only one, character.)
-- Return all customers with a City starting with any character,
--followed by "ondon":
SELECT * FROM Customers
WHERE City LIKE '_ondon';
-- Using the [] Wildcard (The [] wildcard returns a result if any of the characte
rs inside gets a match.)
-- Return all customers starting with either "b", "s", or "p":
SELECT * FROM Customers
WHERE CustomerName LIKE '[bsp]%';
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.
SQL 29
SELECT CustomerID AS ID
FROM Customers;
If you want your alias to contain one or more spaces, like " My Great Products ",
surround your alias with square brackets or double quotes.
Concatenate Columns
SELECT CustomerName, CONCAT(Address, ', ', PostalCode, ', ', City, ', ', Coun
try) AS Address
FROM Customers;
select column_nmae()
from table_name as alias_name;
SQL JOINS
A join clause is used to combine rows from two or more tables, based on a related
column between them
INNER JOIN — Return records that have matching values in both tables
LEFT (OUTER) JOIN — Returns all records from the left table, and the matched
records from the right table
SQL 30
RIGHT (OUTER) JOIN — Returns all records from the right table and the
matched records from the left table
Full (OUTER) JOIN — Returns all records when there is a match in either left or
right table
SQL 31
select column_name from table1
inner join table2
on table1.column_name = table2.column_name;
The example works without specifying table names, because none of the
specified column names are present in both tables. If you try to
include CategoryID in the SELECT statement, you will get an error if you do not
specify the table name (because CategoryID is present in both tables).
INNER is the default join type for JOIN , so when you write JOIN the parser actually
writes INNER JOIN .
select column_name
from table1
SQL 32
left join table2
on table1.column_name = table2.column_name;
select column_name
from table1
right join table2
on table1.column_name = table2.column_name
SQL 33
SQL FULL (OUTER) JOIN
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
SQL 34
and A.City = B.City
order by A.city;
statements
Every SELECT statement within UNION must have the same number of columns
The columns in every in SELECT statement must also be in the same order
--The following SQL statement returns the cities (only distinct values) from
--both the "Customers" and the "Suppliers" table:
select city from customers
union
select city from suppliers
order by city
If some customers or suppliers have the same city, each city will only be listed
once, because UNION selects only distinct values
-- The following SQL statement returns the cities (duplicate values also) from
-- both the "Customers" and the "Suppliers" table:
select city from customers
union all
select city from suppliers
SQL 35
SQL UNION with WHERE
select column_name(s)
from table_name
group by column_name(s)
order by column_name(s)
--The following SQL statement lists the number of customers in each country:
select count(customerID), country
from customers
group by country
SQL 36
--The following SQL statement lists the number of customers in each country,
--sorted high to low:
select count(customerID), country
from customers
group by country
order by count(customerID) DESC
💡 Is where clause can only filter out rows but not the groups?
Yes — the WHERE clause filters rows before grouping happens, so it
can only filter individual rows, not groups.
select column_name(s)
from table_name
where condition
group by column_name(s)
having condition
order by column_name(s)
SQL 37
--The following SQL statement lists the number of customers
--in each country, sorted high to low (Only include countries
--with more than 5 customers):
select count(CustomerID),country
from customers
group by country
having count(CustomerID) > 5
order by count(CustomerID) DESC
The EXISTS operator returns TRUE if the subquery returns one or more records.
select column_name(s)
from table_name
where exists
(select column_name from table_name where condition);
Examples —
SQL 38
where exists (select productname from products where product.supplierID = s
uppliers.supplierID and price = 22)
ANY means that the condition will be true if the operation is true for any of the
values in the range.
select column_name(s)
from table_name
where column_name operator ANY
(select column_name
from table_name
where condition)
ALL Operator —
ALL means that the condition will be true only if the operation is true for all values
in the range.
SQL 39
The following SQL statement lists the ProductName if it finds ANY records in
OrderDetails table has Quantity equal to 10 (this will return TRUE because the
select ProductName
fro Products
where ProductID = ANY
(select ProductID
from OrderDetails
where quantity = 10)
The following SQL statement lists the ProductName if it finds ANY records in the
table has Quantity larger than 1000 (this will return FALSE because
OrderDetails
select ProductName
from Products
where ProductID = any
(select ProductID
from OrderDetails
where quantity > 1000)
The following SQL statement lists the ProductName if ALL the records in the
OrderDetails table has Quantity equal to 10. This will of course return FALSE
because the Quantity column has many different values (not only the value of
10):
SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
SQL 40
FROM OrderDetails
WHERE Quantity = 10);
the new table will be created with the column-names and types as defined in the
old table. You can create new column names using the AS clause
-- The following SQL statement uses the IN clause to copy the table into
--a new table in another database:
select * into customersbackup2017 in 'Backup.mdb'
from customers;
-- The following sql statement copies only a few columns into a new table
select customername, contactname into customersbackup2017
from customers;
SQL 41
-- the following sql statement copies only the german customers into a new ta
ble
select * into customergermany
from customers
where country = 'Germany'
-- the following sql statement copies data from more than one table into a
-- new table:
select customers.customername, orders.orderID
into ustomersorderbackup2017
from customers
left join orders on customers.customerID = orders.customerID;
Tip: SELECT INTO can also be used to create a new, empty table using the schema
of another. Just add a WHERE clause that causes the query to return no data:
SQL 42
select col1, col2, col3, ....
from table1
where condition
here columns of both tables that are employees_backup and employees are same
so can you give this one example with any data you want?
Initial table — employee
id name department
1 Alice HR
2 Bob Sales
3 Charlie Engineering
id name department
5 David Finance
output --
| id | name | department |
| -- | ------- | ----------- |
| 5 | David | Finance |
| 1 | Alice | HR |
| 2 | Bob | Sales |
| 3 | Charlie | Engineering |
SQL 43
-- copy all columns
insert into supplier
select * from customer
is it correct?
Compatible data types (e.g., both name columns are strings, etc.)
my question is can i copy a whole table and it's all columns without putting any
condition like this
"insert into table2
select * from table 1
where condition"?
Yes, you absolutely can copy an entire table’s data — all columns, all rows —
without any WHERE clause.
Just make sure that table1 and table2 have —
If employees_backup has different columns or order, it will fail. Then you'd need to
explicitly list columns:
If the column names differ, but you're using SELECT *, then your query will fail
unless the column order and data types match exactly.
SQL 44
SQL CASE Expression
The CASE expression goes through condition and returns a value when the first
condition is met(like an if-then-else statement). So, once a condition is true, it will
stop reading and return the result. If no conditions are true, it returns the value in
the ELSE clause.
If there is no ELSE part and no conditions are true it returns null.
case
when condition1 then result1
when condition2 then result2
when conditionN then resultN
else result
end;
-- The following SQL will order the customer by city , however if city is null,
-- then order by country
select CustomerName, City,Country
from customers
order by
(case
when city is null then country
else city
end)
SQL 45
SQL NULL Function (SQL IFNULL(), ISNULL(), COALESCE(), and NVL() Functions)
Product table
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20
If here any of the “unitsonorder” values are null, the result will be null
For MySQL
SQL 46
select productname, unitprice * (unitsinstock + coalesce(unitsonorder,0))
from products;
For Oracle
exec procedure_name
SQL 47
Stored Procedure with One Parameter
The following SQL statement creates a stored procedure that selects Customers
from a particular City with a particular postalcode from the "Customers" table:
SQL 48
-- the following SQL statement creates database called "testDB"
create database testDB
SQL 49
BACKUP DATABASE testDB
TO DISK = 'D:\backups\testDB.bak'
WITH DIFFERENTIAL;
The following example creates a table called "Persons" that contains five
columns: PersonID, LastName, FirstName, Address, and City:
SQL 50
FROM customers;
TRUNCATE TABLE used to delete the data inside a table, but not the table itself
The alter table statement is also used to add and drop various constraints on an
table
Add Column
Drop Column
SQL 51
-- The following SQL deletes the "Email" column from the "Customers" ta
ble:
alter table customer
drop column email;
Rename Column
Alter/Modify datatype
MySQL
SQL 52
column3 datatype constraint,
....
);
primary key — a combination of a not null and unique uniquely identifies each row in a
table
foreign key — prevents actions that would destroy links between tables
create index — used to create and retrieve data from the database very quickly
SQL 53
-- MySQL
alter table persons
modify column age int not null;
-- MySQL
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
SQL 54
-- To name a UNIQUE constraint, and to define a UNIQUE
--constraint on multiple columns, use the following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a table which contain
UNIQUE values and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
SQL 55
--use the following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
-- Alter table
alter table persons
add primary key (id)
FOREIGN KEY
The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
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.
SQL 56
-- to create a foreign key consists on the "PersonID" column when the
-- "Orders" table is already created
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
CHECK
If you define a CHECK constraint on a column it will allow only certain values for
this column.
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
SQL 57
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
DEFAULT Constraint
The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.
INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.
SQL 58
Indexes are used to retrieve data from the database more quickly than otherwise.
The users cannot see the indexes, they are just used to speed up
searches/queries.
SQL 59
Age int,
primary key (Personid)
);
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for
each new record.
To let the AUTO_INCREMENT sequence start with another value, use the following SQL
statement:
To insert a new record into the “ Persons ” table, we will not have to specify a value
for the “ Personid ” column (a unique value will be added automatically)
The SQL statement above would insert a new record into the “ Persons ” table. The
“ Personid ” column would be assigned a unique value. The “FirstName” column
would be set to “ Lars ” and the “ LastName ” column would be set to “ Monsen ”
SQL 60
FirstName varchar(255),
Age int
);
-- The MS Access uses the AUTOINCREMENT keyword to perform an
-- auto-increment feature.
-- the starting value for AUTOINCREMENT is 1, and it will increment
-- by 1 for each new record.
SQL Server comes with the following data types for storing a date or a
date/time value in the database:
1 Geitost 2008-11-11
SQL 61
We use the following select statement
1 Geitost 2008-11-11
we will get no result! This is because the query is looking only for dates with no
time portion.
VIEWS
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 statements and functions to a view and present the data as if the
data were coming from one single table.
A view is created with the CREATE VIEW statement.
SQL 62
FROM table_name
WHERE condition;
The following SQL creates a view that shows all customers from Brazil:
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
SQL 63
-- following SQL adds "City" column to the "Brazil Customers" view:
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
SQL Injection
SQL injection is a code injection technique that might destroy your database.
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
username/userid, and instead of a name/id, the user gives you an SQL
statement that you will unknowingly run on your database.
SQL 64
The SQL above is valid and will return ALL rows from the "Users" table, since OR
1=1 is always TRUE.
Does the example above look dangerous? What if the "Users" table contains
names and passwords?
The SQL statement above is much the same as this:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
A hacker might get access to all the user names and passwords in a database, by
simply inserting 105 OR 1=1 into the input field.
Password: myPass
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
A hacker might get access to user names and passwords in a database by simply
inserting " OR ""=" into the user name or password text box:
User Name: “ or “”=”
Password: “ or “”=”
The code at the server will create a valid SQL statement like this:
Result
SQL 65
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The SQL above is valid and will return all rows from the "Users" table, since OR
""="" is always TRUE.
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
SQL Hosting
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL,
and MS Access
SQL 66
MS SQL Server is a popular database software for database-driven web sites
with high traffic
SQL Server is a very powerful, robust and full featured SQL database system
Oracle is also a database software for database-driven web sites with high
traffic
MS Access a web site requires only a simple database, Microsoft Access can
be a solution
MS Access is not well suited for very high-traffic, and not as powerful as
MySQL, SQL Server, or Oracle.
SQL Keywords
Keyword Description
ALL Returns true if all of the subquery values meet the condition
ANY Returns true if any of the subquery values meet the condition
CHECK A constraint that limits the value that can be placed in a column
SQL 67
Keyword Description
CREATE OR
Updates a view
REPLACE VIEW
CREATE
Creates a stored procedure
PROCEDURE
CREATE UNIQUE
Creates a unique index on a table (no duplicate values)
INDEX
CREATE VIEW Creates a view based on the result set of a SELECT statement
SQL 68
Keyword Description
FOREIGN KEY A constraint that is a key used to link two tables together
Returns all rows when there is a match in either left table or right
FULL OUTER JOIN
table
Groups the result set (used with aggregate functions: COUNT, MAX,
GROUP BY
MIN, SUM, AVG)
INNER JOIN Returns rows that have matching values in both tables
INSERT INTO
Copies data from one table into another table
SELECT
Returns all rows from the left table, and the matching rows from the
LEFT JOIN
right table
NOT NULL A constraint that enforces a column to not accept NULL values
Returns all rows when there is a match in either left table or right
OUTER JOIN
table
PRIMARY KEY A constraint that uniquely identifies each record in a database table
Returns all rows from the right table, and the matching rows from
RIGHT JOIN
the left table
SQL 69
Keyword Description
SELECT INTO Copies data from one table into a new table
SELECT TOP Specifies the number of records to return in the result set
TRUNCATE TABLE Deletes the data inside a table, but not the table itself
UNIQUE A constraint that ensures that all values in a column are unique
Python-PostgreSQL Question
SQL 70
import psycopg2
import sys
SQL 71
import os
# Opening the given file to read the data inside
file = open("user.txt", "r")
uid = file.read().strip()
# Closing the file
file.close() # Not a necessary step
# Using try-except block to handle errors
try:
# Creating the connection
connection = psycopg2.connect(
database = sys.argv[1],
user = os.environ.get(“PGUSER”),
password = os.environ.get(“PGPASSWORD”),
host = os.environ.get(“PGHOST”),
port = os.environ.get(“PGPORT”))
# Creating the cursor
cursor = connection.cursor()
# executing the query
query = f"select email from users where user_id = '{uid}'"
cursor.execute(query)
# Obtaining the result
result = cursor.fetchall() # or fetchmany() or fetchone()
for r in result:
print(r[0]) # Extracting the output we require
# Closing the cursor
cursor.close()
# This except block will catch both the general Python exception and
PostgreSQL(Database) related errors and print them to the console
except(Exception, psycopg2.DatabaseError) as error:
print(error)
# Closing the connection
finally:
connection.close()
SQL 72
1. Imports
import sys,os,psycopg2
2. Reading user.txt
Closes the file (good practice, but here not strictly needed).
⚠️ Note: This reads exactly what’s in the file — including newlines ( \n ) if
present.
Example: If user.txt has CLAUS\n , then uid = "CLAUS\n" .
This can cause problems unless .strip() is used.
3. Try-except-finally block
try:
# connection + query
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
connection.close()
SQL 73
except → If something goes wrong (connection issue, query issue), prints the
error.
4. Connecting to PostgreSQL
connection = psycopg2.connect(
database = sys.argv[1],
user = os.environ.get("PGUSER"),
password = os.environ.get("PGPASSWORD"),
host = os.environ.get("PGHOST"),
port = os.environ.get("PGPORT"))
5. Cursor creation
cursor = connection.cursor()
SQL 74
Example: if uid = "CLAUS" , query becomes:
7. Fetching results
result = cursor.fetchall()
for r in result:
print(r[0])
Example output:
8. Closing resources
cursor.close()
connection.close()
Closes the cursor and the connection → good practice to free resources.
⚙️ Example Run
Suppose:
user.txt contains:
CLAUS
SQL 75
Table users has:
user_id | email
--------+---------------------
CLAUS | [email protected]
Run:
Output:
✅ In summary:
1. Reads user_id from user.txt .
SQL 76