Database: SQL Flashcards

1
Q

What is SQL?

A

SQL stands for Structured Query Language, is the standard query language for relational databases

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How is data structured in SQL databases?

A

In tables- each table has fields, or columns, and records, or rows, which fill the fields.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does SQL compare to NoSQL databases?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Weakness of SQL compared to NoSQL

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is mysql 2

A

mysql2 is a relational database system that uses sql as its query language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

downloading mysql 2 client to node

A

npm/yarn i/add mysql2 –save

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

creating a connection/pool object

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

executing a mysql2 package command

A

sql.execute(‘SELECT * FROM (table));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

what are the two most convenient things to download in order to host a mysql database?

A

a mysql server and a workbench

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

sql2 command to insert records into a table

A

execute(‘INSERT INTO product (field1, field2) VALUES (?, ?)’, [value1, value2]);

the (?, ?) helps avoiding SQL Injection attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

what is sequelize?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

creating a pool with sequelize

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

defining a model with sequelize

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

synchronizing js models with the database (creating tables if none exists, creating 1-1, 1-many or many-many relationships)

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

checking if the connection with the database is OK

A

sequelize.authenticate().then().catch()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Solving the intellisense bug with sequelize that would make instantiated classes from it not be suggested?

A

const Sequelize = require(‘sequelize’).Sequelize;

importing it to other files still keeps it working there

17
Q

Creating a instance of a model with sequelize

A

model.build({record});

18
Q

Saving a model to the database

A

model.save();

19
Q

Shortcut function to create and save a model at the same time

A

model.create({record});

20
Q

Finding one record by the primary key

A

model.findByPk((pk)): Promise

21
Q

Updating a record

A

model.findByPk().then(result => {
result.(Var) = (value);
result.save();
})

22
Q

deleting a record

A

record.deleteByPk((id));
or
record.findByPk … then(record => record.destroy());

23
Q

How are table relations declared with sequelize and how to declare one?

A

Table relations are declared throught its model representatives such as a Product, Cart or User model.

User.hasMany((model))
or Product.belongsTo((model), (options))

options:
constraints: bool - ??
onDelete: ‘CASCADE’ | ‘SET NULL’ - ??

24
Q

When creating a User.hasMany(Product), give 2 examples of relational methods that can be used in the User model

A

User.createProduct((product));
User.getProducts({where: {field: val}})
User.addProduct(product.id)
User.addProducts()

25
Q

how to create one model that stores Pks belonging to two other models (intermediate table)?

A

model1. belongsTo(model2, {through: intermediateModel});

model2. belongsTo(model1, {through: intermediateModel});

26
Q

When using a relational method from a model, how to pass additional options to an intermediate table

A

Model.createModel2({(options)}, {through: {property: value}})

27
Q

deleting an intermediate table through another model

A

model.intermediateTable.destroy();

28
Q

assigning new table values to an intermediate table through another model

A

model. intermediateTable = {key: val}
model. intermediateTable.prop = val ?

apparently only works after calling a related table with another related table.

29
Q

relational function to set the value of multiple records at the same time

A

Model.setModel2(model.id)

30
Q

what does the concept of ‘eager loading’ means in SQL and how to apply it using Sequelize?

A

eager loading means fetching one/multiple records along with one or more relational record(s) associated with one record on one query.

Applying it in Sequelize:

since it works for relational stuff only, it can only be called by relational functions such as Model.getModel2({includes: [‘product’]})

31
Q

relational method in sequelize to remove a relation from model A to model B

A

modelA.removeModelB(id);

// This will remove only the relation, not the actual product.

32
Q

can you write “model.intermediateTable = {key: val}”

and then “model.save()” ?

A

Yes, it will automatically create an intermediate table with the assigned field

33
Q

updating more than one field with sequelize

A

model.update({values}, {options})

options:
validate: bool - if false, validation wont be run, default: true.

34
Q

creating a getter and setter function in sequelize.define(), in a property level.

A
sequelize.define("name", {prop: {
        .....,
        get(){
            //do something and return
        },
        set(value){
            //do something and set a value
        }
   }
})
35
Q

complete the code:

sequelize.define(“name”, {prop: {type: Sequelize.STRING,
…..,
get(){
return (a prop from this model);
}
}
})

A

completion:

return this.getDataValue(“string”);

this context offers getDataValue(“string”), to get values in get() functions and make them pseudo properties when returning.

And also setDataValue(“prop name”, value) to set a value in a setter of a sequelize model.

36
Q

creating a getter and setter function in sequelize.define(), in a model level.

A

sequelize.define(“name”, {attributes}, { getterMethods:{}, setterMethods{}});

getterMethods: { func(){}, func2(){} } - allows to set getters on a model level. accessing this.getDataValue(“prop name”) is also possible.

setterMethods: { func(){}, func2(){} } - same thing, but with setters and you wont return anything.

  • both setter and getter should probably have the same name, since the difference between setter and getter is
    model. prop and model.prop = something.
37
Q

difference between this.getDataValues(“prop”) and this.prop?

A

the first returns the raw value, the second returns the getter value if available.

38
Q

calling a sequelize model pseudo property vs a modified property

A

model.prop | model.prop

defining getters and setters in different levels(property and model level) doesnt change how you call them.