SQL Notes 27/01/23
What is a database?
Any collection of related information (exp of DB: phone book, shopping list, Facebook’s user base, etc.)
Can be stored in different ways ( on paper, own mind, computer, comments section, etc.)
Database Management Systems?
A special software program that helps users create and maintain a database (handling security, backups,
importing/exporting data, interacts with software applications, etc.)
In charge of Creating, Reading, Updating, & deleting information.
C.R.U.D (Main operations of a database)?
• Create
• Read (Retrieve)
• Update
• Delete
Relational Vs Non-relational Databases ?
Relational Databases (SQL) Non-Relational Databases (noSQL)
-Organize data into tables (with column & rows) -Organize data in anything but a traditional table.
-Existence of unique key (identifier of each row)
-managed by relational Database management systems
(RDBMS).
Exp : MySQL, Oracle, MariaDB, etc.
- use a Structured Query Language (SQL) to perform CRUD
operations and other administrative tasks (user
management, security, backup, etc.) -Managed by non-relational Database management
systems (NRDBMS).
-RDBMS implement SQL a little bit different→ not all SQL Exp : MongoDB, Dynamo DB, apache Cassandra, etc.
codes used on one RDMS will port over to another one -No set language standard.
without slight modification. For more insights…
What are queries?
Requests made to DBMS for specific information (to get certain data with certain specification).
SQL Notes 27/01/23
Tables and Keys?
Primary keys: an attribute that uniquely
defines a row in a database.
- Surrogate keys: random number,
has no mapping to anything in
the real world.
- natural keys: has a meaning/
purpose in the real world. Exp:
Surrogate primary key passport number.
Natural primary key
Foreign keys: an attribute that will link us
to another database table.
A foreign key that links table
A foreign key that links table Employee to itself → it
Employee to table Branch → identifies every employee’s
it identifies every employee’s supervisor.
branch.
A foreign key that links table Branch to table
Employee to → it identifies every branch’s manager.
A foreign key that links table Client to table Branch A composite primary Key. Only together, they can identify each
→ it identifies every client’s branch they buy from. row.
→emp-id and client-id are foreign keys that relates to employee
and client tables. Together they are primary key.
Basics of SQL:
-SQL is a hybrid language, it is 4 in 1:
• Data query language (DQL)→ to get information already stored there.
• Data definition language (DDL)→ to define database schemas (what tables, types of data, columns, etc.)
• Data control language (DCL)→ manage & control access to data in the database (who can do changes in the
database and where exactly (which tables)).
• Data manipulation language (DML)→ to insert, update, and delete data from databases.
Common Data types:
INT → integers
DECIMAL (M, N) → Decimal numbers – M: total number of digits in that number / N: number of digits after comma
VARCHAR (l) → String of text of length l
BLOB →Binary large Object, Stores large data.
DATE → ‘YYYY-MM-DD’
TIMESTAMP → ‘YYYY-MM-DD HH: MM: SS’ – used for creating tables.
SQL Notes 26/03/2023
Data Definition Language (DDL) Queries:
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies an existing database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies an existing table
• DROP TABLE - deletes an existing table
Data Manipulation Language (DML) Queries:
• SELECT - extracts data from an existing table
• UPDATE - updates data in an existing table
• DELETE - deletes data from an existing table
• INSERT INTO - inserts new data into the table
SQL Constraints:
➔ Are rules enforced on data columns or tables.
➔ Are used to limit type of data that can go into a table.
➔ Column constraints are applied only to one column while table constraints are applied to the whole table.
• NOT NULL Constraint: Ensures that a column cannot have NULL value.
• DEFAULT Constraint: Provides a default value for a column when none is specified.
• UNIQUE Constraint: Ensures that all values in a column are different.
• AUTO_INCREMENT Constraint: automatically increments values of the column.
• PRIMARY Key: Unique identifier of each row/record in a database table. (NOT NULL & UNIQUE)
• FOREIGN Key: Unique identifier of a row/record in any another database table.
Deep View on DDL:
1. Database statements.
2. Table Creation & deletion.
3. Adding, Removing, and Modifying Attributes.
1.DATABASE STATEMENTS:
To create a database: CREATE DATABASE database_name;
To delete a database: DROP DATABASE database_name;
2.TABLE STATEMENTS:
➔ To create a table, need to specify table name, list of attributes with their names and types.
Exp: CREATE TABLE employee (empl_id int (11) AUTO_INCREMENT,
first_name varchar (20) NOT NULL,
last_name varchar (20),
birth_date date DEFAULT NULL,
salary int (8) DEFAULT 3500,
PRIMARY KEY (empl_id) );
➔ To describe a table DECRIBE table_name;
➔ Defining a foreign key
we create foreign key with a references clause.
1. Through table creation:
CREATE TABLE employee (empl_id int (11) AUTO_INCREMENT PRIMARY KEY,
first_name varchar (20) NOT NULL,
last_name varchar (20),
birth_date date DEFAULT NULL,
salary int (8) DEFAULT 3500,
FOREIGN KEY (branch_id) REFERENCES branch (branch_id));
You can rename the foreign key (branch_id) or you can keep it as it’s.
SQL Notes 27/03/2023
2. Through alter query:
ALTER TABLE table_name1 ADD key_name
ALTER TABLE table_name1 ADD FOREIGN_KEY (key_name) REFERENCES table_name2 (PRIM_KEY_ table_name2);
➔ Adding, Removing, and Modifying Attributes
To add an extra column to an existing table: ALTER TABLE table_name ADD column_name datatype
To remove an existing column: ALTER TABLE table_name DROP COLUMN column_name
To change the data type of an existing column:
ALTER TABLE table_name MODIFY column_name datatype
➔ To remove a table from a dataset
DROP TABLE table_name
Deep View on DML:
1. INSERT STATEMENT:
It is possible to write it the INSERT INTO statement in two ways:
→ By specifying both column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, …) VALUES (value1, value2, value3, …) ;
→ If adding values to all columns, no need to specify the column names in SQL query:
INSERT INTO table_name VALUES (value1, value2, value3, …) ;
2. UPDATE STATEMENT:
➔ It allows to change one or more rows of an existing table.
UPDATE table_name
SET column1= value1, column2= value2, …
WHERE condition ;
Exp: we’re changing the salary of employees with ids 101 & 102 to 80,000 instead of 78,000 and 75,000.
UPDATE employee SET salary= 80000 WHERE emp_id=102 AND emp_id=101;
The table to be updated One/more assignements to specify which Which rows to change
attributes to change and their new values (in this case only one)
➔ If where is to be deleted from the query, then all rows are to be affected
Exp: UPDATE employee SET salary= 80000 → all employees will get a salary of 80,000
3. DELETE STATEMENTS
➔ It deletes row(s) from a table.
DELETE FROM table_name
WHERE condition ;
Exp: DELETE FROM employee WHERE first_name= ‘Jan’; → It deletes first row.
➔ DELETE FROM table_name; →deletes all the rows in the table.
4. SELECT STATEMENT:
➔ It gets information from the database.
SELECT column_name(s)/ Function (column_name)
FROM table_name
[WHERE condition]
[ORDER BY column_name]
[GROUP BY column_name] ;
SELECT * FROM table_name ; → It selects all columns.
SELECT colum_name(i) →It selects the ith column.
Exp: Select first_name from employee;→ it only lists the column
FROM table_name ; first_name
SELECT DISTINCT colum_name(i)
→It selects the ith column without repetition.
FROM table_name ;
SQL Notes 28/03/2023
➔ WHERE clause:
Used to extract only the records that specify certain conditions.
It may use AND / OR operator to filter records based on more than one condition.
• AND → displays record if both 1st & 2nd conditions are true.
• OR→ displays record if either 1st or 2nd condition is true.
We can also use these operators with WHERE clause: Exp : The IN operator :
It will display rows nb 1, 2, & 5
Operator Description
= Equal
<> Not Equal
> Greater than
< Lesser than
>= Greater than or equal
Exp : The BETWEEN operator :
<= Lesser than or equal
BETWEEN Between an inclusive range
LIKE Search for pattern
With it we can use
NOT LIKE
IN To specify multiple possible values for a
column
SQL Notes 24/10/2023
➔ BUILT IN FUNCTIONS:
COUNT : is a built-in database function that retrieves the number of rows that match the query criteria.
SELECT COUNT (*) FROM table_name ; → Gives total number of rows in the table.
SELECT COUNT (column_name)
FROM table_name → Return the number of rows that matches the specified condition
WHERE condition;
AVG : built-in function, returns the average value of a numeric column.
SELECT AVG (column_name) FROM table_name WHERE condition;
SUM : built-in function, returns the total sum of a numeric column.
SELECT SUM (column_name) FROM table_name WHERE condition;
DISTINCT: built-in function, returns unique values in specified columns.
SELECT DISTINCT column_name FROM table_name WHERE condition;
➔ Using COUNT & DISTINT together:
SELECT COUNT (DISTINCT column_name) FROM table_name ;
➔ Difference between two codes:
SELECT DISTINCT column1, column2, ... FROM table_name;
→ Returns distinct combinations. (total row is unique)
SELECT DISTINCT column1, DISTINCT column2, ... FROM table_name; → Retrieve unique values from each individual
column
LIMIT : Clause, used to specify the maximum number of rows the result set must have.
SELECT * FROM table_name LIMIT nb_rows_retrieved;
Within a certain range (exp from col 5 to col 25)
SELECT * FROM table_name LIMIT 20 OFFSET 4;
RESOURCES:
YOUTUBE video
GIRAFFE ACADEMY codes
W3school
COURSERA COURSE