You are on page 1of 12

1_SQL– SYNC( 1 hours 30 min)

Learning ● SQL Introduction


Objectives ● My SQL installation
● MySQL Create Database
● MySQL Table
● MySQL Insert into
● MySQL Where
● MySQL Order By
● MySQL Delete
● MySQL Drop Table
● MySQL Update
● MySQL Join

Time Activity

(5 mins) OPENING
● Review Learning Objectives.
● Review Agenda.

1
1_SQL– SYNC( 1 hours 30 min)
(35 mins) CONTENT & PRACTICE

SQL Introduction:
● Structured Query Language is a standard Database language which is used to create, maintain and retrieve the relational
database.
● SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT, UPDATE, CREATE, etc) in
capital letters and use user defined things (liked table name, column name, etc) in small letters.
● We can write comments in SQL using “–” (double hyphen) at the beginning of any line.
● SQL is the programming language for relational databases (explained below) like MySQL, Oracle, Sybase, SQL Server,
Postgress, etc. Other non-relational databases (also called NoSQL) databases like MongoDB, DynamoDB, etc do not use
SQL.
● Although there is an ISO standard for SQL, most of the implementations slightly vary in syntax. So we may encounter
queries that work in SQL Server but do not work in MySQL.

SQL Installation:
● For different operating system you need to install different MySQL server
● For Windows follow this guide. https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en/windows-installation.html
● For macOs follow this guide. https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en/macos-installation.html
● For Linux follow this guide. https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en/linux-installation.html
● Once you have MySQL up and running on your computer, you can access it by using Node.js.
● To access a MySQL database with Node.js, you need a MySQL driver. This tutorial will use the "mysql" module,
downloaded from NPM.
● To download and install the "mysql" module, open the Command Terminal and execute the following:
$ npm install sql
● Now you have downloaded and installed a mysql database driver.
● Node.js can use this module to manipulate the MySQL database:
var mysql = require('mysql');
● Start by creating a connection to the database.
● Use the username and password from your MySQL database.
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword"

2
1_SQL– SYNC( 1 hours 30 min)
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
● Save the code in a file and run
$ node filename.js

● Which will give you this result:


Connected!
● Now you can start querying the database using SQL statements.
● Use SQL statements to read from (or write to) a MySQL database. This is also called "to query" the database.
● The connection object created in the example above, has a method for querying the database:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
● The query method takes an sql statements as a parameter and returns the result.

Creating a Database:
● To create a database in MySQL, use the "CREATE DATABASE" statement:
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword"
});

3
1_SQL– SYNC( 1 hours 30 min)
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
● Run this fille and it should out put you “Database created”

Creating a Table:
● To create a table in MySQL, use the "CREATE TABLE" statement.
● Make sure you define the name of the database when you create the connection:
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
● Which will give you this result: “Table created”

Insert Into Table:

4
1_SQL– SYNC( 1 hours 30 min)
● To fill a table in MySQL, use the "INSERT INTO" statement.
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
● As soon as query method is called record will entered. You can call this function multiple times to enter multiple records.

Selecting From a Table:


● To select data from a table in MySQL, use the "SELECT" statement.
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;

5
1_SQL– SYNC( 1 hours 30 min)
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

● SELECT [DISTINCT] Attribute_List FROM R1,R2….RM


● SELECT * will return all columns
● You can specify any column name instead of * to return specific column.

Select With a Filter:


● When selecting records from a table, you can filter the selection by using the "WHERE" statement:
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address = 'Park Lane 38'", function (err, result) {
if (err) throw err;
console.log(result);
});
});

● This will return the all the column values where the address value is “Park Lane 30”.

6
1_SQL– SYNC( 1 hours 30 min)
Sort the Result:
● Use the ORDER BY statement to sort the result in ascending or descending order.s
● The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC
keyword.
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers ORDER BY name", function (err, result) {
if (err) throw err;
console.log(result);
});
});
● This query will return you the all the columns in ascending order according to the column “name”.

Delete Record:
● You can delete records from an existing table by using the "DELETE FROM" statement.
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {

7
1_SQL– SYNC( 1 hours 30 min)
if (err) throw err;
var sql = "DELETE FROM customers WHERE address = 'Mountain 21'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});

The Result Object:


● When executing a query, a result object is returned.
● The result object contains information about how the query affected the table.
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}

Delete a Table:
● You can delete an existing table by using the "DROP TABLE" statement:

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

8
1_SQL– SYNC( 1 hours 30 min)

con.connect(function(err) {
if (err) throw err;
var sql = "DROP TABLE customers";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table deleted");
});
});

● If the the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS
keyword to avoid getting an error.

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
var sql = "DROP TABLE IF EXISTS customers";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});

Update a Table:
● You can update existing records in a table by using the "UPDATE" statement:

9
1_SQL– SYNC( 1 hours 30 min)
var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});

Join Tables:
● You can combine rows from two or more tables, based on a related column between them, by using a JOIN statement.
● Consider you have a "users" table and a "products" table:

users
[
{ id: 1, name: 'John', favorite_product: 154},
{ id: 2, name: 'Peter', favorite_product: 154},
{ id: 3, name: 'Amy', favorite_product: 155},
{ id: 4, name: 'Hannah', favorite_product:},
{ id: 5, name: 'Michael', favorite_product:}
]

10
1_SQL– SYNC( 1 hours 30 min)
products
[
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }
]

● These two tables can be combined by using users' favorite_product field and products' id field
● Select records with a match in both tables:

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
var sql = "SELECT users.name AS user, products.name AS favorite FROM users JOIN products ON users.favorite_product =
products.id";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});

Left Join:
● If you want to return all users, no matter if they have a favorite product or not, use the LEFT JOIN statement:
SELECT users.name AS user,

11
1_SQL– SYNC( 1 hours 30 min)
products.name AS favorite
FROM users
LEFT JOIN products ON users.favorite_product = products.id

Right Join:
● If you want to return all products, and the users who have them as their favorite, even if no user have them as their favorite,
use the RIGHT JOIN statement.
SELECT users.name AS user,
products.name AS favorite
FROM users
RIGHT JOIN products ON users.favorite_product = products.id

CLOSING
Ask participants to summarise what they learned in today’s session.
● Let participants know what comes next -

12

You might also like