Database: SQL Flashcards
What is SQL?
SQL stands for Structured Query Language, is the standard query language for relational databases
How is data structured in SQL databases?
In tables- each table has fields, or columns, and records, or rows, which fill the fields.
How does SQL compare to NoSQL databases?
SQL databases are relational: They can relate different tables to create a join version of them, without duplicating the data, the merge can be made one to one, one to many, or many to many tables;
SQL databases have strong schema requirements, the records need to have all fields filled
Weakness of SQL compared to NoSQL
Relational databases are hard to scale horizontally; (Some cloud services do the scaling in the background).
Lots of requests to highly joined tables can result in long code, and slow processing
NoSQL runs more types of data more easily
NoSQL scales and adapts better
what is mysql 2
mysql2 is a relational database system that uses sql as its query language
downloading mysql 2 client to node
npm/yarn i/add mysql2 –save
creating a connection/pool object
sql.createPool({
user: ‘root’,
password: ‘’,
host: ‘localhost’,
databate: ‘database name’
});
or
sql.createConnection({
user: ‘root’,
password: ‘’,
host: ‘localhost’,
databate: ‘database name’
});
a connection closes as soon as a query is issued, a pool keeps the connection open
executing a mysql2 package command
sql.execute(‘SELECT * FROM (table));
what are the two most convenient things to download in order to host a mysql database?
a mysql server and a workbench
sql2 command to insert records into a table
execute(‘INSERT INTO product (field1, field2) VALUES (?, ?)’, [value1, value2]);
the (?, ?) helps avoiding SQL Injection attacks.
what is sequelize?
its an object-relational mapping library for Node.js, it has inbed commands that maps js commands to SQL so that it is possible to use SQL without writing SQL
creating a pool with sequelize
new require(‘sequelize’)(‘database’, ‘user’, ‘password’, {(options)})
(options) : host: ‘127.0.0.1’ - specifies the host, defaults to localhost;
dialect: ‘mysql’ | ‘postgres’ - specifies the sql dialect, because there are differences in how each engine uses SQL
defining a model with sequelize
new sequelize().define('table', { fieldName: { type: sequelize.STRING, allowNull: false } })
field properties:
sequelize.STRING | NUMBER | BOOLEAN | DATE etc
allowNull:bool - controls whether the field is required
primaryKey:bool - makes the key primary or not, ideal to do searches and relations between tables
synchronizing js models with the database (creating tables if none exists, creating 1-1, 1-many or many-many relationships)
new sequelize().sync((options)).then().catch();
sequelize automatically creates createdAt and updatedAt fields, overwriting tables is also possible.
options:
force: bool - forces DELETE IF EXISTS of tables, good in development version
checking if the connection with the database is OK
sequelize.authenticate().then().catch()