SQL statements Flashcards
What is used to make a db
CREATE DATABASE IF NOT EXISTS mydatabase
Show your dbs
SHOW DATABASES
for x in cursor
Make a table
CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))
Show your tables
SHOW TABLES
for x in cursor
Make a table and key
CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))
Add prim keys to your table
ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY
Add a record
INSERT INTO customers (name, address) VALUES (%s, %s)
cursor.execute(sql,val)
Show number of rows last affected by execute
mycursor.rowcount
Save changes
connection.commit
ADd multiple rows
val = [()]
Show latest record id inserted
mycursor.lastrowid
Print all records from table
result = mycursor.fetchall()
for x in result
Print name and addresses only from your table
SELECT name, address FROM customers
result = cursor.fetchall()
for x in result
Get first row and print
SELECT * FROM customers
result = cursor.fetchone()
Get addresses that have ‘simpson st” as address
SELECT * FROM customers WHERE address=’simpson st’
result = cursor.fetchall()
for x in myresult
Get addresses that contain the word ‘way’
SELECT * FROM customers WHERE address LIKE=”%way%”
result=cursor.fetchall()
for x in result
Sort everything by name in ascending order
Do it for descending
SELECT * FROM customers ORDER BY name
ORDER BY name DESC
Delete records with address ‘mountain 21’
How do you delete everything
DELETE FROM customers WHERE address=’Mountain 21”
DELETE FROM customers
Delete a table
DROP TABLE IF EXISTS customers
EDIT address Canyon 123 to Valley 123
UPDATE customers SET address=”Canyon 123” WHERE address=’Valley 123’
Get first 5 records
SELECT * FROM customers LIMIT 5
Get 5 records starting from record 3
SELECT * FROM customers LIMIT 5 OFFSET 2
You have two tables
One contains users names and a number that correlates to another table that contains favorite icecreams by an id number.
How do you combine fav and id?
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
sql = “SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id”
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
What’s the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN
INNER JOIN only shows the records where there is a match.
If you want to show all users, even if they do not have a favorite product, use the LEFT JOIN statement:
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 statemen
Select all users and their favorite product
sql = “SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id”