You are on page 1of 8

What is SQL?!

!SQL stands for Structured Query Language. It's used for creating, querying, updating and
manipulating modern relational databases. SQL is used on virtually all major platforms, and by
virtually all major relational database systems.!

The SQL language can be divided into two major categories. The Data Definition Language, or
DDL, is used to define tables, indexes, and relationships. And the Data Manipulation Language,
or DML, is used to add, query, manipulate, and delete data from tables and datasets.!

How SQL works is it understands fields that are in tables, and how to find the data in the tables
based on the contents of the fields. All SQL operations are then one of four general things to do
with tables:!

Create!
Putting data into tables.!

Read!
Query data out of a table.!

Update!
Change data already in a table.!

Delete!
Remove data from the table.!

This has been given the acronym "CRUD" and is considered a fundamental set of features every
data storage system must have.!

!
One way to explain how SQL works is by comparing it to a spreadsheet software like Excel:!
!

!
!
!
!
!

A database is a whole spreadsheet file.!


A table is a tab/sheet in the spreadsheet, with each one being given a name.!
A column is a column in both.!
A row is a row in both.!
SQL then gives you a language for doing CRUD operations on these to produce new tables or
alter existing ones.

SQL Essential Training

SQL Essential Commands

Based on SQLite Standard


Every database system has it's own set of functions. Some functions might not be
standardised. Check the documentation of the system for more information.

FUNDAMENTALS

SELECT !
SELECT * FROM Table_Name;!
SELECT Column1, Column2, FROM Table_Name;!
Rename Column1 to Column One
SELECT Column1 AS Column One FROM Table_Name;!

Select rows with conditions


SELECT Column1, Column2, FROM Table_Name WHERE Column 1 = Condition 1;!

Select rows and limit number of rows to 5


SELECT Column1 FROM Table_Name WHERE Column 1 = Condition 1 LIMIT 5;!

Work with NULL NULL is not empty, false or zero. Its a lack of data.
SELECT * FROM Table_Name WHERE Column1 IS NULL;
SELECT * FROM Table_Name WHERE Column1 IS NOT NULL;
SELECT * FROM Table_Name WHERE Column1 < 0 OR Column1 IS NULL;!

Work with LIKE operator


SELECT * FROM Table_Name WHERE Name LIKE %island%1;
Contains the word island
SELECT * FROM Table_Name WHERE Name LIKE _a%;
Anything for the first letter, only a as a second letter, and anything else in the rest!

To work with IN operator IN operators use to select results that match values in a list
SELECT * FROM Table_Name WHERE Continent IN (Europe, Asia);!

Select only distinct value from Column1


SELECT DISTINCT Column1 FROM Table_Name;
SELECT DISTINCT Column1, Column2 FROM Table_Name;
Distinct in both ( Show both (a, b) and (a, c) )!

Sorting the result with ORDER BY


SELECT Column1 FROM Table_Name ORDER BY Name; Ascending order
SELECT Column1 FROM Table_Name ORDER BY Name ASC; Ascending order
SELECT Column1 FROM Table_Name ORDER BY Name DESC; Descending order
SELECT Column1 FROM Table_Name ORDER BY Continent, Name;
Within the ascending continent, we also sort the name alphabetically

%, the wildcard in SQL, matches zero or more characters in a string while the _ matches a single character.

SQL Essential Training

SELECT Column1 FROM Table_Name ORDER BY Continent DESC, Name;


Within the descending continent, we also sort the name alphabetically!

Conditional expressions with CASE

The followings are exactly the same


SELECT
CASE WHEN column1 THEN true ELSE false END AS boolA
CASE WHEN column2 THEN true ELSE false END AS boolB
;
SELECT
CASE column1 WHEN 1 THEN true ELSE false END AS boolA
CASE column2 WHEN 1 THEN true ELSE false END AS boolB
;!

INSERT!
INSERT INTO Table_Name ( Column1, Column3, Column9 ) VALUES ( A, 999, ABC);!
To insert a new row without specific field (values MUST be equal to number of columns)
INSERT INTO Table_Name VALUES ( 1, one, integer);!

INSERT INTO Table_Name (Column1, Column2) SELECT id, name FROM Table2;!

CREATE!
CREATE TABLE Table_Name (
id INTEGER PRIMARY KEY, A sequence generator2. It will create sequential
numbers in this column.
aaa INTEGER NOT NULL, A NOT NULL constraint
bbb TEXT DEFAULT panda, A pre-defined value. If bbb is null then panda appears
ccc TEXT UNIQUE Note that NULL is unique. Its possible to have 2 rows with NULL
in column ccc.
) ;!

Then insert the values into the new table


INSERT INTO Table_Name ( aaa, bbb, ccc ) VALUES ( 1, apple, fruit);
INSERT INTO Table_Name ( aaa, bbb, ccc ) VALUES ( 2, bird, animal);!

Note: the following is error since aaa cannot be null.

!
!

INSERT INTO Table_Name (bbb) VALUES ( cat );!

ALTER!
To add a new column ddd to an existing table
ALTER TABLE Table_Name ADD ddd TEXT;!

ALTER TABLE Table_Name ADD eee TEXT DEFAULT panda;!


2

A sequence generator varies significantly from system to system.

SQL Essential Training

UPDATE!

UPDATE Table_Name SET Column1 = AAA, Column2 = 999 WHERE id = 5;!


UPDATE Table_Name SET Column1 = NULL, Column2 = 999 WHERE Column1 = ab;!

DELETE!

DELETE FROM Table_Name WHERE Column1 = 1;!

DROP!

!
!
!
!
!

DROP TABLE Table_Name;!


DROP TABLE IF EXISTS Table_Name;!

RELATIONSHIP
Related tables with JOIN
1. Select the intersection of the two tables
The result will include rows from both tables where the joined condition is met.
SELECT l.description AS column1, r.description AS column2
FROM left_table AS l left table
JOIN right_table AS r
ON l.id = r.id the condition
;!

2. Select the left outer join (even the condition is not met)
A left outer join includes the rows where the condition is met,
plus all the rows from the left table, where the condition is not met.
SELECT l.description AS column1, r.description AS column2
FROM left_table AS l
LEFT JOIN right_table AS r
ON l.id = r.id
;!

3. Select the relation for 3 tables


SELECT c.name AS Customer, i.name AS Item, s.price AS Price
FROM Customer_Table AS c left table
JOIN Sale_Table AS s ON s.customer_id = c.id
JOIN Item_Table AS i ON s.item_id = i.id Sale table as a junction table
;!

SQL Essential Training

STRINGS
Finding the length of a string with LENGTH
SELECT Name, LENGTH(Name) AS Length_Column_Name FROM Table_Name;!

Selecting the part of a string with SUBSTR Example: 2008-07-22


SELECT
SUBSTR( Date_Column, 1, 4) AS Year,
SUBSTR( Date_Column, 6, 2) AS Month,
SUBSTR( Date_Column, 9, 2) AS Date
FROM Table_Name;!

Removing spaces with TRIM


SELECT TRIM ( String ) ; Remove space by default
SELECT LTRIM ( String ) ;
SELECT RTRIM ( String ) ;
SELECT TRIM ( String , . ) ; Specified to remove . (period)!

Making strings uppercase and lowercase

!
!
!

SELECT UPPER (Name) FROM Table_Name;


SELECT LOWER (Name) FROM Table_Name;!

NUMBERS
Finding the type of a value
SELECT TYPEOF ( expression/value );!

Converting the type of a value


SELECT CAST ( 1 AS REAL );!

Finding the remainders


SELECT 17 % 5 Some system might use MOD(17,5) instead!

Rounding numbers

!
!
!
!

SELECT ROUND ( value, precision );!

DATE AND TIMES

SELECT DATETIME(now); returns the current UTC time!


SELECT DATE(now);!
SELECT TIME(now);!
SELECT DATE(now, +2 days);!
SELECT DATE(now, +3 hours, -27 minutes, -2 months, +1 year);!

SQL Essential Training

AGGREGATE DATA
Counting the number of rows
SELECT COUNT(*) FROM Table_Name;
SELECT COUNT(*) FROM Table_Name WHERE Column1 > 999 AND Column2 = 888;!

GROUP BY clause
SELECT Continent, COUNT(*)
FROM Table_Name
GROUP BY Continent
;!

Conditional statement with HAVING


HAVING is for aggregate data, and WHERE is for non-aggregate data
SELECT a.title AS Album, COUNT(t.track_number) AS Tracks
FROM track AS t
JOIN album AS a
ON a.id = t.album_id
WHERE a.artist = The Beatles
GROUP BY a.id WHERE clause is before GROUP BY, and HAVING clause is after it
HAVING Tracks >= 10
ORDER BY Tracks DESC, Album
;!

Common aggregate functions!


SELECT COUNT(Population) FROM Table_Name Count non null values!
SELECT Region,
AVG(Population), MIN(Population), MAX(Population), SUM(Population)
FROM Table_Name GROUP BY Region
;!

Selecting counting distinct values

!
!
!
!
!
!
!
!

The distinct keyword can be used with any of the aggregate functions. It's used to remove
duplicates before the aggregate function is called.
SELECT COUNT(DISTINCT HeadofState) AS Counter FROM Country ;!

SQL Essential Training

TRANSACTIONS!

Transactional database operations can improve reliability and performance for larger or more
complex operations. The begin transaction statement tells the system that all the statements up
to the end transaction statement, are to be treated as one unit. And the end transaction
statement, ends that transaction and allows the system to commit those statements in that
transaction to storage.!

!
!
!
!
!
!
!

BEGIN TRANSACTION;!
!
ROLLBACK;!
!
BEGIN TRANSACTION;

END TRANSACTION!;!

!
!

TRIGGERS
Updating a table with a trigger
Trigger can be an excellent way to enforce business rules that require a table to be
updated whenever another table is updated.

CREATE TRIGGER trigger_name AFTER INSERT ON table1


BEGIN
UPDATE table2 SET column1 = NEW.id WHERE table2.id = NEW.customer_id
END
; This trigger will happen every time there's an insert on the table1.!

Preventing automatic updates with a trigger


the RAISE function is only valid inside the trigger, in this case, it rolls back transaction.
CREATE TRIGGER trigger_name BEFORE UPDATE ON table1
BEGIN
SELECT RAISE(ROLLBACK, error message') FROM table1
WHERE id = NEW.id AND reconciled = 1;
END
;!

SQL Essential Training

Automating timestamps with a trigger

!
!
!

CREATE TRIGGER trigger_name AFTER INSERT ON table1


BEGIN
UPDATE table1 SET stamp = DATETIME('now') WHERE id = NEW.id;
UPDATE table2 SET last_order_id = NEW.id, stamp = DATETIME('now')
WHERE table2.id = NEW.customer_id;
INSERT INTO log_table (stamp, event, username, tablename, table_id)
VALUES (DATETIME('now'), 'INSERT', 'TRIGGER', 'table1', NEW.id);
END ;!

SUBSELECT AND VIEWS


Creating a simple subselect
Subselects are effectively nested select statements. A subselect is a select statement that
is being used as if it were a table.
SELECT co.Name, ss.CCode FROM (
SELECT
SUBSTR(b, 1, 2) AS Country, SUBSTR(b, 3) AS CCode FROM pre_table
) AS ss pre_table input is, for example, US4567.
JOIN table2 AS co
ON co.Code = ss.Country
;
Subselects are a convenient way of making your data available in different forms, while
keeping your database schema and well organised.!

Searching within a result set


SELECT a.title AS album, a.artist, t.track_number AS seq, t.title, t.duration AS secs
FROM album AS a
JOIN (
SELECT album_id, track_number, duration, title
FROM track_table
WHERE duration <= 90
) AS t
ON t.album_id = a.id
;!

Creating a view
We can use VIEW to store the result of a SELECT statement effectively as a table. Any
SELECT statement at all can be saved as a view.
CREATE VIEW trackView AS
SELECT id, album_id, title, track_number, duration / 60 AS m, duration % 60 AS s FROM
track_table ;
SELECT * FROM trackView treat VIEW as a normal table

SQL Essential Training

You might also like