Help with SQL commands to interact with a MySQL database
# Current Session
export PATH=${PATH}:/usr/local/mysql/bin
# Permanently
echo 'export PATH="/usr/local/mysql/bin:$PATH"' >> ~/.bash_profile
On Windows - https://www.qualitestgroup.com/resources/knowledge-center/how-to-guide/add-mysql-path-windows/
mysql -u root -p
SELECT User, Host FROM mysql.user;
CREATE USER 'someuser'@'localhost' IDENTIFIED BY 'somepassword';
GRANT ALL PRIVILEGES ON * . * TO 'someuser'@'localhost';
FLUSH PRIVILEGES;
SHOW GRANTS FOR 'someuser'@'localhost';
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'someuser'@'localhost';
DROP USER 'someuser'@'localhost';
exit;
SHOW DATABASES
CREATE DATABASE acme;
DROP DATABASE acme;
USE acme;
CREATE TABLE users(
id INT AUTO_INCREMENT,
first_name VARCHAR(100),
last_name VARCHAR(100),
email VARCHAR(50),
password VARCHAR(20),
location VARCHAR(100),
dept VARCHAR(100),
is_admin TINYINT(1),
register_date DATETIME,
PRIMARY KEY(id)
);
DROP TABLE tablename;
SHOW TABLES;
INSERT INTO users (first_name, last_name, email, password, location, dept, is_admin, register_date) values ('Rahul', 'Shetty', '[email protected]', '123456','Mumbai', 'development', 1, now());
INSERT INTO users (first_name, last_name, email, password, location, dept, is_admin, register_date) values ('John', 'Doe', '[email protected]', '123456', 'New York', 'design', 0, now()), ('Joe', 'Don', '[email protected]', '123456', 'New York', 'design', 0, now()),('Will', 'Jackson', '[email protected]', '123456', 'Rhode Island', 'development', 1, now()),('Paula', 'Johnson', '[email protected]', '123456', 'Massachusetts', 'sales', 0, now()),('Tom', 'Spears', '[email protected]', '123456', 'Massachusetts', 'sales', 0, now());
SELECT * FROM users;
SELECT first_name, last_name FROM users;
SELECT * FROM users WHERE location='Massachusetts';
SELECT * FROM users WHERE location='Massachusetts' AND dept='sales';
SELECT * FROM users WHERE is_admin = 1;
SELECT * FROM users WHERE is_admin > 0;
DELETE FROM users WHERE id = 6;
UPDATE users SET email = '[email protected]' WHERE id = 2;
ALTER TABLE users ADD age VARCHAR(3);
ALTER TABLE users MODIFY COLUMN age INT(3);
SELECT * FROM users ORDER BY last_name ASC;
SELECT * FROM users ORDER BY last_name DESC;
SELECT CONCAT(first_name, ' ', last_name) AS 'Name', dept FROM users;
SELECT DISTINCT location FROM users;
SELECT * FROM users WHERE age BETWEEN 20 AND 25;
SELECT * FROM users WHERE dept LIKE 'd%';
SELECT * FROM users WHERE dept LIKE 'dev%';
SELECT * FROM users WHERE dept LIKE '%t';
SELECT * FROM users WHERE dept LIKE '%e%';
SELECT * FROM users WHERE dept NOT LIKE 'd%';
SELECT * FROM users WHERE dept IN ('design', 'sales');
We can use WHERE dept='design' AND dept='sales'
but imagine if there are a lot of departments.
Whenever we want a faster query result, we need to index the column. For example, if we know location is something quite frequently searched by users, then we can index it. LIndex
is a name provided to the index. It means Location Index
.
CREATE INDEX LIndex On users(location);
DROP INDEX LIndex ON users;
Default is used to provide a default value. In our case, it's the current time.
CREATE TABLE posts(
id INT AUTO_INCREMENT,
user_id INT,
title VARCHAR(100),
body TEXT,
publish_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
INSERT INTO posts(user_id, title, body) VALUES (1, 'Post One', 'This is post one'),(3, 'Post Two', 'This is post two'),(1, 'Post Three', 'This is post three'),(2, 'Post Four', 'This is post four'),(5, 'Post Five', 'This is post five'),(4, 'Post Six', 'This is post six'),(2, 'Post Seven', 'This is post seven'),(1, 'Post Eight', 'This is post eight'),(3, 'Post Nine', 'This is post none'),(4, 'Post Ten', 'This is post ten');
INNER JOIN gets all records that are common between both tables based on the supplied ON clause.
LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.
RIGHT JOIN is like the above but gets all records in the RIGHT table.
FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.
SELECT
users.first_name,
users.last_name,
posts.title,
posts.publish_date
FROM users
INNER JOIN posts
ON users.id = posts.user_id
ORDER BY posts.title;
CREATE TABLE comments(
id INT AUTO_INCREMENT,
post_id INT,
user_id INT,
body TEXT,
publish_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id),
FOREIGN KEY(user_id) references users(id),
FOREIGN KEY(post_id) references posts(id)
);
INSERT INTO comments(post_id, user_id, body) VALUES (1, 3, 'This is comment one'),(2, 1, 'This is comment two'),(5, 3, 'This is comment three'),(2, 4, 'This is comment four'),(1, 2, 'This is comment five'),(3, 1, 'This is comment six'),(3, 2, 'This is comment six'),(5, 4, 'This is comment seven'),(2, 3, 'This is comment seven');
This will fetch you call the comments with it's respective post titles. Notice that if you change the join to right, it'll fetch you all the posts even if it doesn't have the comment.
SELECT
comments.body,
posts.title
FROM comments
LEFT JOIN posts ON posts.id = comments.post_id
ORDER BY posts.title;
SELECT
comments.body,
posts.title,
users.first_name,
users.last_name
FROM comments
INNER JOIN posts on posts.id = comments.post_id
INNER JOIN users on users.id = comments.user_id
ORDER BY posts.title;
SELECT COUNT(id) FROM users;
SELECT MAX(age) FROM users;
SELECT MIN(age) FROM users;
SELECT SUM(age) FROM users;
SELECT UCASE(first_name), LCASE(last_name) FROM users;
SELECT age, COUNT(age) FROM users GROUP BY age;
SELECT age, COUNT(age) FROM users WHERE age > 20 GROUP BY age;
SELECT age, COUNT(age) FROM users GROUP BY age HAVING count(age) >=2;
const express = require('express');
const mysql = require('mysql');
const app = express();
const db = mysql.createConnection({
host: 'localhost',
user: 'root'
password: '<password>',
database: 'test_database'
});
db.connect();
app.get('/users', (req, res) => {
const sql = 'SELECT * FROM users';
db.query(sql, (err, result) => {
if(err) return err;
return res.send(result);
});
});
app.listen(4000, () => console.log('Server is running at port 4000'));
Use ORM rather than directly handling the queries by yourself: https://sequelize.org/