Codehelp: Lec-9: SQL in 1-Video
Codehelp: Lec-9: SQL in 1-Video
p
1. SQL is Structured Query language used to perform CRUD operations in R-DB, while MySQL is a RDBMS used to
store, manage and administrate DB (provided by itself) using SQL.
el
SQL DATA TYPES (Ref: https://www.w3schools.com/sql/sql_datatypes.asp)
VARCHAR string(0-255)
TINYTEXT String(0-255)
TEXT string(0-65535)
od
BLOB string(0-65535)
MEDIUMTEXT string(0-16777215)
MEDIUMBLOB string(0-16777215)
LONGTEXT string(0-4294967295)
C
LONGBLOB string(0-4294967295)
DATE YYYY-MM-DD
TIMESTAMP YYYYMMDDHHMMSS
TIME HH:MM:SS
BOOLEAN 0/1
p
3. Size: TINY < SMALL < MEDIUM < INT < BIGINT.
4. Variable length Data types e.g., VARCHAR, are better to use as they occupy space equal to the actual data size.
el
6. Types of SQL commands:
2. ALTER TABLE: modification in table structure. e.g, change column datatype or add/remove columns.
eH
3. DROP: delete table, DB, view.
2. DRL/DQL (data retrieval language / data query language): retrieve data from the tables.
1. SELECT
od
MANAGING DB (DDL)
1. Creation of DB
2. USE db-name; //need to execute to choose on which DB CREATE TABLE etc commands will be executed.
//make switching between DBs possible.
2. Dual tables are dummy tables created by MySQL, help users to do certain obvious actions without referring to user
defined tables.
4. WHERE
5. BETWEEN
p
6. IN
1. Reduces OR conditions;
2. e.g., SELECT * FROM officers WHERE officer_name IN ('Lakshay', ‘Maharana Pratap', ‘Deepika’);
el
7. AND/OR/NOT
eH
8. IS NULL
10. ORDER BY
od
11. GROUP BY
1. GROUP BY Clause is used to collect data from multiple records and group the result by one or more column. It is
generally used in a SELECT statement.
3. SELECT c1, c2, c3 FROM sample_table WHERE cond GROUP BY c1, c2, c3.
4. All the column names mentioned after SELECT statement shall be repeated in GROUP BY, in order to successfully
execute the query.
1. COUNT()
2. SUM()
3. AVG()
4. MIN()
5. MAX()
12. DISTINCT
1. “Select col_name from table GROUP BY col_name;” same output as above DISTINCT query.
2.SQL is smart enough to realise that if you are using GROUP BY and not using any aggregation function, then
you mean “DISTINCT”.
13. GROUP BY HAVING
1. Out of the categories made by GROUP BY, we would like to know only particular thing (cond).
2. Similar to WHERE.
3. Select COUNT(cust_id), country from customer GROUP BY country HAVING COUNT(cust_id) > 50;
4. WHERE vs HAVING
1. Both have same function of filtering the row base on certain conditions.
2. WHERE clause is used to filter the rows from the table based on specified condition
3. HAVING clause is used to filter the rows from the groups based on the specified condition.
4. HAVING is used after GROUP BY while WHERE is used before GROUP BY clause.
5. If you are using HAVING, GROUP BY is necessary.
6. WHERE can be used with SELECT, UPDATE & DELETE keywords while GROUP BY used with SELECT.
CONSTRAINTS (DDL)
1. Primary Key
p
el
eH
1. PK is not null, unique and only one per table.
2. Foreign Key
1. FK refers to PK of other table.
2. Each relation can having any number of FK.
od
3. UNIQUE
1. Unique, can be null, table can have multiple unique attributes.
2. CREATE TABLE customer (
…
email VARCHAR(1024) UNIQUE,
…
);
4. CHECK
1. CREATE TABLE customer (
…
CONSTRAINT age_check CHECK (age > 12),
…
);
2. “age_check”, can also avoid this, MySQL generates name of constraint automatically.
5. DEFAULT
1. Set default value of the column.
2. CREATE TABLE account (
…
saving-rate DOUBLE NOT NULL DEFAULT 4.25,
…
);
6. An attribute can be PK and FK both in a table.
7. ALTER OPERATIONS
1. Changes schema
2. ADD
1. Add new column.
2. ALTER TABLE table_name ADD new_col_name datatype ADD new_col_name_2 datatype;
3. e.g., ALTER TABLE customer ADD age INT NOT NULL;
3. MODIFY
1. Change datatype of an attribute.
p
2. ALTER TABLE table-name MODIFY col-name col-datatype;
3. E.g., VARCHAR TO CHAR
ALTER TABLE customer MODIFY name CHAR(1024);
el
4. CHANGE COLUMN
1. Rename column name.
2. ALTER TABLE table-name CHANGE COLUMN old-col-name new-col-name new-col-datatype;
3. e.g., ALTER TABLE customer CHANGE COLUMN name customer-name VARCHAR(1024);
eH
5. DROP COLUMN
1. Drop a column completely.
2. ALTER TABLE table-name DROP COLUMN col-name;
3. e.g., ALTER TABLE customer DROP COLUMN middle-name;
6. RENAME
1. Rename table name itself.
2. ALTER TABLE table-name RENAME TO new-table-name;
3. e.g., ALTER TABLE customer RENAME TO customer-details;
od
1. INSERT
1. INSERT INTO table-name(col1, col2, col3) VALUES (v1, v2, v3), (val1, val2, val3);
2. UPDATE
1. UPDATE table-name SET col1 = 1, col2 = ‘abc’ WHERE id = 1;
C
p
JOINING TABLES
1. All RDBMS are relational in nature, we refer to other tables to get meaningful outcomes.
2. FK are used to do reference to other table.
el
3. INNER JOIN
1. Returns a resultant table that has matching values from both the tables or all the tables.
2. SELECT column-list FROM table1 INNER JOIN table2 ON condition1
INNER JOIN table3 ON condition2
eH
…;
3. Alias in MySQL (AS)
1. Aliases in MySQL is used to give a temporary name to a table or a column in a table for the purpose of
a particular query. It works as a nickname for expressing the tables or column names. It makes the query short
and neat.
2. SELECT col_name AS alias_name FROM table_name;
3. SELECT col_name1, col_name2,... FROM table_name AS alias_name;
4. OUTER JOIN
od
1. LEFT JOIN
1. This returns a resulting table that all the data from left table and the matched data from the right table.
2. SELECT columns FROM table LEFT JOIN table2 ON Join_Condition;
2. RIGHT JOIN
1. This returns a resulting table that all the data from right table and the matched data from the left table.
2. SELECT columns FROM table RIGHT JOIN table2 ON join_cond;
C
3. FULL JOIN
1. This returns a resulting table that contains all data when there is a match on left or right table data.
2. Emulated in MySQL using LEFT and RIGHT JOIN.
3. LEFT JOIN UNION RIGHT JOIN.
4. SELECT columns FROM table1 as t1 LEFT JOIN table2 as t2 ON t1.id = t2.id
UNION
SELECT columns FROM table1 as t1 RIGHT JOIN table2 as t2 ON t1.id = t2.id;
5. UNION ALL, can also be used this will duplicate values as well while UNION gives unique values.
5. CROSS JOIN
1. This returns all the cartesian products of the data present in both tables. Hence, all possible variations
are reflected in the output.
2. Used rarely in practical purpose.
3. Table-1 has 10 rows and table-2 has 5, then resultant would have 50 rows.
4. SELECT column-lists FROM table1 CROSS JOIN table2;
6. SELF JOIN
1. It is used to get the output from a particular table when the same table is joined to itself.
SET OPERATIONS
Combines multiple tables based on matching Combination is resulting set from two or more
condition. SELECT statements.
p
Column wise combination. Row wise combination.
Data types of two tables can be different. Datatypes of corresponding columns from each
el
table should be the same.
The number of column(s) selected may or may not The number of column(s) selected must be the
be the same from each table. same from each table.
eH
Combines results horizontally. Combines results vertically.
3. UNION
od
3. Number of column, order of column must be same for table1 and table2.
4. INTERSECT
2. Emulated.
5. MINUS
1. This operator returns the distinct row from the first table that does not occur in the second table.
2. Emulated.
3. SELECT column_list FROM table1 LEFT JOIN table2 ON condition WHERE table2.column_name IS NULL;
4. e.g., SELECT id FROM table-1 LEFT JOIN table-2 USING(id) WHERE table-2.id IS NULL;
SUB QUERIES
2. Alternative to joins.
3. Nested queries.
5. e.g., SELECT * FROM table1 WHERE col1 IN (SELECT col1 FROM table1);
1. SELECT MAX(rating) FROM (SELECT * FROM movie WHERE country = ‘India’) as temp;
1. SELECT (SELECT column_list(s) FROM T_name WHERE condition), columnList(s) FROM T2_name WHERE
condition;
9. Derived Subquery
1. SELECT columnLists(s) FROM (SELECT columnLists(s) FROM table_name WHERE [condition]) as new_table_name;
p
JOIN VS SUB-QUERIES
el
JOINS SUBQUERIES
Faster Slower
MySQL VIEWS
1. A view is a database object that has no values. Its contents are based on the base table. It contains rows and columns
od
2. In MySQL, the View is a virtual table created by a query by joining one or more tables. It is operated similarly to the base
table but does not contain any data of its own.
3. The View and table have one main difference that the views are definitions built on top of other tables (or views). If any
changes occur in the underlying table, the same changes reflected in the View also.
7. CREATE VIEW Trainer AS SELECT c.course_name, c.trainer, t.email FROM courses c, contact t WHERE c.id = t.id; (View
using Join clause).
NOTE: We can also import/export table schema from files (.csv or json).