0% found this document useful (0 votes)
6 views

Order of Execution in SQL

Uploaded by

zam.pfe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Order of Execution in SQL

Uploaded by

zam.pfe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

SQL

ORDER OF EXECUTION IN SQL


query is processed in the following steps:
1. Getting Data (FROM/JOIN)
2. Row Filter (WHERE)

3. Grouping (GROUP BY)

4. Group Filter (HAVING)

5. Return Expression (SELECT)

6. Order & Paging (ORDER BY & LIMIT/OFFSET)


Database
Create a database:
CREATE DATABASE <db_name>;

Use database:
USE <db_name>;

Delete database:
DROP <db_name>;

Set database to readOnly:


ALTER DATABASE <db_name> READ ONLY = 1;

Enable encryption to database:


ALTER DATABASE <db_name> ENCRYPTION = ‘Y’;

Tables
Create tables:
Create Table <table_name> (
<column_name> <column_type> [<other_infos>],
….
);
 <column_type> can be INT, VARCHAR(number), DATE….

Select from table:


SELECT <column1>,<column2>,.. FROM <table_name>;
Rename table:
RENAME TABLE <old_name> TO <new_name>;

Delete table:
DROP TABLE <table_name>;

Add column to table:


ALTER TABLE <table_name> ADD <column_name> <column_type>;

Rename column of table:


ALTER TABLE <table_name> RENAME COLUMN <old_column_name> TO
<new_column_name>;

Modify column (type):


ALTER TABLE <table_name> MODIFY <column_name> <new_type>;

Change position of column:


ALTER TABLE <table_name> MODIFY <column_name> <column_type> <KEYWORD>
[<column_name>];
 <KEYWORD> can be FIRST, AFTER and BEFORE, with AFTER and BEFORE we must
specified column.

Insert into table:


INSERT INTO <table_name> VALUES (<value1>,….),(…),….;
 To specified the columns:
INSERT INTO <tabel_nmae>(<column1>,….) VALUES (<value1>,….);

Select from table:


SELECT <selector> FROM <table_name>;
<selector> can be columns, * to select all columns, ….
 `we can use WHERE to select specific line of table:
SELECT <selector> FROM <table_name> WHERE <condition>
 to select NULL value we must use this condition:
<column> IS NULL

Update table values:


UPDATE <table_name> SET <column>=<value> WHERE <condition>;
 to update all column in table we don’t use WHERE;

Delete table values:


DELETE FROM <table_name> WHERE <condition>;
 to delete all table values we remove WHERE;

AUTOCOMMIT, COMMIT, ROLLBACK:


To save current state we use:
COMMIT;
 automatically MYSQL save all our changes, we can turn that off by:
SET AUTOCOMMIT = OFF;
 now we must manually add COMMIT after any change to save it.
 To undo change (for non saved change) we use:
ROLLBACK;

Current date and time:


 We use CURRENT_DATE() function to get current date.
 We use also CURRENT_TIME() to get current time.
 We use NOW() to get current time and date;
 CURRENT_DATE()+1 give use the next day date.

UNIQUE:
It’s means that this entry is unique in this column.

When creating table:


we add it after <type> of column.
After creating table:
ALTER TABLE <table_name> ADD CONSTRAINT UNIQUE(<column_name>);

NOT NULL:
When creating table:
Add it after <type> of column

AFTER CREATING TABLE:


ALTER TABLE <table_name> MODIFY <column_name> <type> NOT NULL;

CHECK:
When creating table:
CONSTRAINT <name_constraint> CHECK (<condition>);

After creating table:


ALTER TABLE <table_name> ADD CONSTRAINT <name_constraint>
CHECK(<condition>);

Delete check:
ALTER TABLE <table_name> DROP CHECK <constraint_name>;

DEFAULT:
Its used to set a default value to column:
<column_name> <type> DEAULT <value>

PRIMARY KEY:
Primary key => UNIQUE + NOT NULL.

When creating table:


<column_name> <type> PRIMARY KEY;
After creating table:
ALTER TABLE <table_name> ADD CONSTRAINT PRIMARY
KEY(<column_name>);

AUTO_INCREMENT:
 Auto increment column after each insertion.
<column_name> <type> AUTO_INCREMENT;
 to change auto_increment starting index:
ALTER TABLE <table_name> AUTO_INCREMENT=<index>;

Foreign KEY
When creating table:
FOREIGN KEY(<column_name>) REFERENCES <table_name>
(<primary_key_column>) [ON DELETE <SET NULL or CASCADE>];

After creating table:


ALTER TABLE <table_name> ADD CONSTRAINT FOREIGN KEY(<colum_name>)
REFERENCES <table_name>(<primary_key_column>);

Delete foreign key:


ALTER TABLE <table_name> DROP FOREIGN KEY <foreign_key_name>;

Rename foreign key:


To rename it we add constraint with the new name and same information.

ON DELETE:
When we delete the primary key we:
ON DELETE SET NULL => set foreign key to NULL
CASCADE => delete also the row that contain the foreign key
JOINS:
INNER JOIN:
SELECT <selector> FROM <table1> INNER JOIN <table2> ON <condition>

LEFT JOIN:
SELECT <selector> FROM <table1> LEFT JOIN <table2> ON <condition>
In here we select all lines of the left table, if the condition is true for a line we show the
line in the right table else we put NULL

RIGHT JOIN:
Same as LEFT JOIN we just change direction.

Functions:
COUNT():
Count the number of rows.

MIN() / MAX()

SUM() / AVG

CONCAT(<column1>, [“ ”],<column2>, ….):


Concatenate columns or text.

ROUND(number, [decimal places]) / FLOOR(...)/ CEIL(...)

LOWER / UPPER

LEFT(str, number) / right(str, number)

LENGTH(column: string|number)

REPLACE(column, <letter(s)-to-replace>, <l-to-replace-with>


ALIAS:
Give a name to a column:
SELECT <column_name> AS <name> ……...

LIKE _,% (wild card characters):


It’s like regular expressions, _ for one random character, % for random characters (0 to n).
we must used with LIKE, not =.

ORDER BY:
It’s gonna sort our result query to ascend or descend form.
SELECT <selector> FROM <table_name> ORDER BY <column_name> [ASC, DESC] ,
<column-name> [ASC, DESC], ….
by default it’s gonna sort results on ascend form.

LIMIT:
It’s used to limit the number of returned result of a query.
SELECT <selector> FROM <table_name> LIMIT <offset>,<limit>;

UNIONS:
To join vertically two tables, the two tables must have exactly the same number of columns.
UNION don’t allow duplicate rows.
EX: supposing that we have two tables, table1 with 6 columns and table2 with 2 columns, to
join themes:
SELECT <column1>,<column2> FROM <table1>
UNION
SELECT * FROM <table2>
we use UNION ALL to include duplicates.

SELF JOIN:
We join a table with it self using INNER JOIN, LEFT JOIN or RIGHT JOIN.
We must give every table an alias to distinguish themes
EX:
SELECT a.<column1>,…..,b.<column1>,….
FROM <table1> AS a
INNER JOIN <table1> AS b
ON a.<column> = b.<column>

Views:
View is a virtual table based on result-set of a SQL statement.

Create view:
CREATE VIEW <view_name> AS <the view>;

Drop view:
DROP VIEW <view_name>;

INDEXES:
Are used to find values within a specific column more quickly.
They cause UPDATE and INSERT to be more slower, but SELECT more faster.

Create index:
CREATE INDEX <index_name> ON <table_name>(<column1>,….);
 the columns must be sorted from the most used to the less.

Delete index:
ALTER TABLE <table_name> DROP INDEX <index_name>;

Show indexes of a tables:


SHOW INDEXES FROM <table_name>

SUBQUERIES:
EX:
SELECT <column1>, …. , (SELECT * FROM <table>) FROM <table>
IN:
Value in list of rows;
EX:
a in (select v from b)
be aware from the not in (null values)

EXISTS:
The EXISTS operator is used to test for the existence of any record in a subquery.

The EXISTS operator returns TRUE if the subquery returns one or more records.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

GROUP BY:
It aggregate all rows by a specific column.
EX:
SELECT SUM(<column>)
FROM <table>
GROUP BY <column>;
if we want to filter GROUP BY we use HAVING

ROLLUP:
It’s used with GROUP BY, it add a row with sum of results (grand total).
We use like that:
GROUP BY <column> WITH ROLLUP;
Procedures:
Create procedure:
DELIMITER $$
CREATE PROCEDURE <procedure_name>(IN <parameter_name> <type>,...)
BEGIN
<body of procedure>
END $$
DELIMITER ;

Call procedure:
CALL <procedure_name>();

Delete procedure:
DROP PROCEDURE <procedure_name>

TRIGGERS:
CREATE TRIGGER <trigger_name> BEFORE | AFTER UPDATE | DELETE | … ON <table>
[FOR EACH ROW] SET <change>
don’t forget using NEW.<column> to specified the new column (not the original column)

CASE:
- The CASE statement goes through conditions and return 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 will return the value in the ELSE clause.

- If there is no ELSE part and no conditions are true, it returns NULL.

EX:
SELECT
CASE
WHEN <condition> THEN <result>
WHEN <condition2> THEN <result2>
ELSE <result3>
END
FROM <table>

DISTINCT:
The SELECT DISTINCT statement is used to return only distinct (different) values.

EX:
SELECT COUNT(DISTINCT Country) FROM Customers;

You might also like