SQL tricks and cheats, or the obvious nearby. This document discusses various SQL tricks and tips including:
1. Different ways to generate unique IDs for table rows such as UUIDs, sequences, and auto-increment fields.
2. Tips for database design such as using ER diagrams and normalizing data.
3. Examples of DDL tricks like defining foreign keys and column data types.
4. DML tricks including selecting data, concating columns, and handling null values.
The document provides solutions and examples for common SQL problems through various tricks and features to help optimize database and query design. It aims to remind readers of useful SQL features and show flexibility in solutions.
This Doc Consist of ER diagram of University and NHL, Introduction to posgres SQL and installation,DML and its various commands,implementation of constraints with examples,DML Implementation with set operations & Functions,Implementation of nested Queries.
This document provides instructions for experiments in a Database Management System laboratory course. It includes a list of 12 experiments covering topics like Data Definition Language commands, Data Manipulation Language commands, database design using ER modeling and normalization, and implementation of various database applications. It also provides details on the hardware and software requirements for the course, as well as the internal assessment structure including marks distribution.
NoSQL Search Roadshow Zurich 2013 - Polyglot persistence with no sqlMichael Lehmann
The document discusses polyglot persistence, which is using multiple data persistence technologies like both SQL and NoSQL databases together. It notes that while relational databases have long dominated, NoSQL databases offer alternatives to address needs like large volumes of data, high speeds, and flexibility. The document outlines different types of NoSQL databases and considerations for choosing between them, and advocates using different databases based on their strengths and applying principles like separation of layers and reusable services to integrate diverse data stores in a polyglot approach.
The document discusses Structured Query Language (SQL) and its uses. It covers SQL statements like SELECT, INSERT, UPDATE, DELETE to manipulate databases. It also covers SQL data definition language statements like CREATE TABLE to create tables, ALTER TABLE to modify tables, and DROP TABLE to delete tables. Additionally, it discusses SQL data types, constraints like PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK constraints.
The document discusses dynamic websites using PHP with an Oracle database. It begins by defining what a relational database is and the advantages of using a database over files, including centralization of data, high performance, reduced data redundancy, better security and integrity. It then discusses database structure, explaining that a database consists of logical tables that contain columns, indexes, foreign keys etc. and that a table stores data in rows and columns. It provides an example table to demonstrate this. It further explains concepts like primary keys, unique constraints, not null constraints and foreign keys and how they maintain data integrity. The document concludes by discussing how to design the database using concepts learned and provides SQL examples to demonstrate creating, reading, updating and deleting data from
This file work is made for the purpose of learning and to get knowledge about programs in big data. Relevant information is taken from various sources. This file was for acadmic purpose and it is shared for learnig purposes
This document provides an overview and introduction to MySQL. It begins with a comparison of MySQL to Microsoft Access, noting MySQL's open source nature, cross-platform availability, and emphasis on fast query processing. Basic commands for connecting to a MySQL server and exploring database and table structures are presented. The document then covers SQL data definition and manipulation languages, including creating and modifying tables, inserting and selecting data. Joins between tables and use of aggregate functions are also summarized. Overall, the document provides a high-level tour of MySQL's basic features and capabilities.
SQL DDL: tricks and tips (JProf#27, Minsk, 24th September)Mikalai Sitsko
This document summarizes an SQL DDL presentation covering IDs, domains, calculated columns, constraints, and triggers. It discusses various techniques for each topic, such as using sequences or auto-increment for IDs, domains for standardizing data types, views or generated columns for calculations, primary keys, foreign keys, unique constraints and checks for data integrity rules, and DML, DDL, and database triggers for logging and validation. The presentation provides pros and cons of each approach and concludes that thinking low-level and writing high-level code are important principles for working with SQL DDL.
This Doc Consist of ER diagram of University and NHL, Introduction to posgres SQL and installation,DML and its various commands,implementation of constraints with examples,DML Implementation with set operations & Functions,Implementation of nested Queries.
This document provides instructions for experiments in a Database Management System laboratory course. It includes a list of 12 experiments covering topics like Data Definition Language commands, Data Manipulation Language commands, database design using ER modeling and normalization, and implementation of various database applications. It also provides details on the hardware and software requirements for the course, as well as the internal assessment structure including marks distribution.
NoSQL Search Roadshow Zurich 2013 - Polyglot persistence with no sqlMichael Lehmann
The document discusses polyglot persistence, which is using multiple data persistence technologies like both SQL and NoSQL databases together. It notes that while relational databases have long dominated, NoSQL databases offer alternatives to address needs like large volumes of data, high speeds, and flexibility. The document outlines different types of NoSQL databases and considerations for choosing between them, and advocates using different databases based on their strengths and applying principles like separation of layers and reusable services to integrate diverse data stores in a polyglot approach.
The document discusses Structured Query Language (SQL) and its uses. It covers SQL statements like SELECT, INSERT, UPDATE, DELETE to manipulate databases. It also covers SQL data definition language statements like CREATE TABLE to create tables, ALTER TABLE to modify tables, and DROP TABLE to delete tables. Additionally, it discusses SQL data types, constraints like PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK constraints.
The document discusses dynamic websites using PHP with an Oracle database. It begins by defining what a relational database is and the advantages of using a database over files, including centralization of data, high performance, reduced data redundancy, better security and integrity. It then discusses database structure, explaining that a database consists of logical tables that contain columns, indexes, foreign keys etc. and that a table stores data in rows and columns. It provides an example table to demonstrate this. It further explains concepts like primary keys, unique constraints, not null constraints and foreign keys and how they maintain data integrity. The document concludes by discussing how to design the database using concepts learned and provides SQL examples to demonstrate creating, reading, updating and deleting data from
This file work is made for the purpose of learning and to get knowledge about programs in big data. Relevant information is taken from various sources. This file was for acadmic purpose and it is shared for learnig purposes
This document provides an overview and introduction to MySQL. It begins with a comparison of MySQL to Microsoft Access, noting MySQL's open source nature, cross-platform availability, and emphasis on fast query processing. Basic commands for connecting to a MySQL server and exploring database and table structures are presented. The document then covers SQL data definition and manipulation languages, including creating and modifying tables, inserting and selecting data. Joins between tables and use of aggregate functions are also summarized. Overall, the document provides a high-level tour of MySQL's basic features and capabilities.
SQL DDL: tricks and tips (JProf#27, Minsk, 24th September)Mikalai Sitsko
This document summarizes an SQL DDL presentation covering IDs, domains, calculated columns, constraints, and triggers. It discusses various techniques for each topic, such as using sequences or auto-increment for IDs, domains for standardizing data types, views or generated columns for calculations, primary keys, foreign keys, unique constraints and checks for data integrity rules, and DML, DDL, and database triggers for logging and validation. The presentation provides pros and cons of each approach and concludes that thinking low-level and writing high-level code are important principles for working with SQL DDL.
An introduction to the different types of NoSQL and some guidance on when to choose them, and when to use plain old SQL. Focuses on developer productivity, intuitive code, and system issues including scaling and usage patterns. As delivered at JavaOne 2014 in San Francisco
This document provides an overview and introduction to MySQL. It begins with a comparison of MySQL to Microsoft Access, noting MySQL's open source nature, availability on multiple platforms, and emphasis on fast query processing. It then covers how to connect to the MySQL server from the command line. The document spends the majority of its time reviewing SQL, including data definition commands to create tables and define data types, as well as data manipulation commands to select, insert, update and delete data. It also covers joining multiple tables, ordering and grouping results, and using aggregate functions. In summary, this document serves as an introduction and primer to the basics of MySQL and SQL.
This document provides an introduction to Microsoft SQL Server and basic SQL statements. It discusses that MS SQL Server is a relational database management system developed by Microsoft that stores and retrieves data. It has several editions for different workloads and audiences. It then covers key SQL statements like CREATE TABLE, SELECT, INSERT, UPDATE, and DELETE and provides examples of how to use each statement to interact with database tables in MS SQL Server.
The document discusses Structured Query Language (SQL) and its basic statements. It covers:
- SQL is used to request and retrieve data from databases. The DBMS processes SQL queries and returns results.
- SQL statements are divided into DDL (data definition language) for managing schema, DML (data manipulation language) for data queries/modification, and DCL (data control language) for managing transactions and access control.
- The document provides examples of using SQL commands like CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE, DELETE, SELECT and indexes. It also covers data types, constraints and operators used in SQL queries.
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
How fast can you modify your data collection to include a new field, make all the necessary changes in data processing and storage, and then use that field in analytics or product features? For many companies, the answer is a few quarters, whereas others do it in a day. This data agility latency has a direct impact on companies' ability to innovate with data. Schema-on-read has been a key strategy to lower that latency - as the community has shifted towards storing data outside relational databases, we no longer need to make series of schema changes through the whole data chain, coordinated between teams to minimise operational risk. Schema-on-read comes with a cost, however. Errors that we used to catch during testing or in early test deployments can now sneak into production undetected and surface as product errors or hard-to-debug data quality problems later than with schema-on-write solutions.
In this presentation, we will show how we have rejected the tradeoff between slow schema change rate and quality to achieve the best of both worlds. By using metaprogramming and versioned pipelines that are tested end-to-end, we can achieve fast schema changes with schema-on-write and the protection of static typing. We will describe the tools in our toolbox - Scalameta, Chimney, Bazel, and custom tools. We will also show how we leverage them to take static typing one step further and differentiate between domain types that share representation, e.g. EmailAddress vs ValidatedEmailAddress or kW vs kWh, while maintaining harmony with data technology ecosystems.
1. The document describes a midterm exam for a C++ programming course that consists of multiple choice questions and has a time limit of 2 hours.
2. It provides sample exam questions about C++ concepts like functions, variables, conditionals, and data types.
3. The student completed the exam, scoring 64 out of 100 points within the 2 hour time limit.
SQL Server 2000 Research Series - Essential KnowledgeJerry Yang
This document provides an agenda for a training on SQL Server 2000, covering the SQL Server 2000 environment including tools like Service Manager and Enterprise Manager, fundamental database operations including tables, indexes and DDL/DML/DCL commands, and recommended references for further reading on SQL Server and database fundamentals.
Development time is wasted as the bulk of the work shifts from adding business features to struggling with the RDBMS. MongoDB, the leading NoSQL database, offers a flexible and scalable solution.
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docxDIPESH30
L1 Intro to Relational DBMS LP.pdf
Intro to Relational
Databases
CS 2215 Introduction to Databases
1
2
What Is a DBMS?
Database: A collection of information.
Eg ?
Examples: Library, University
Database Management System (DBMS) :
software package designed to store
and manage databases.
Eg: Oracle, SQL server, MySQL, Access
Files vs DBMS : Why bother with
databases ?
Why not just store all the data in a big file
and write C or Java programs to manipulate
the data. 2
3
Why Use a DBMS?
Naïve users sheltered from messy
details
Data integrity:
Eg: if Bob works in Marketing, make
sure there is a dept. called Marketing.
Reduced application development
time: Avoid writing special programs
from scratch each time to access
data.
Standard Application Interface:
increased reliability
3
4
Why Use a DBMS?
Data independence: easier
to make changes
If how data is stored changes,
don’t have to change views.
Forms, etc.
Security: easier to control
how data is shared
Concurrent access: allow
multiple users to access
simultaneously
But in a controlled way !
4
5
Different people involved
DBMS implementers: who build the DBMS like
Oracle, MS SQL server
End users: Use forms & reports, might write SQL
queries
DB application programmers: write programs
to make life easier for end users.
Eg: person who creates forms for library.
Must know how databases work
DB administrator (DBA):
Handles security and authorization
Crash recovery
Database tuning as needs evolve
5
6
Overview of course: Relational Model:
Student Database, Fig 1.2
6
STUDENT
Name StudentNumber Class Major
Smith 17 1 CS
Brown 8 2 CS
7
Overview of course:
Data Models:
High level : Entity Relation (E.R.) model
Intermediate level : relational model
Student database
Low level: physical database -
Covered in CSCI 4524 Advanced
Databases
Relational databases:
Integrity constraints
Good design : normalization
Query languages: Relational
algebra, SQL
Views, Assertions, Triggers
7
8
Relational Data Model
Relation: 2-dimensional table
All info stored in tables
Eg: student, course
See Elmasri Fig 1.2
Rows (or tuples): student : 2 rows
Records: a row may correspond with a
record in a file
Commonly used if we are talking about the
physical storage of databases
Columns (or attributes): student : 4
columns
8
9
Relational Data Model
Relational model proposed by E. F.
Codd 1970
Dominant model in commercial DBMS
products.
Eg: Oracle, SQL server, MySQL, Access.
Compared to previous models
(network, hierarchical etc):
Easier to understand info in tables
Casual user can write simple SQL queries
Complex queries much easier to
understand compared to previous models.
9
10
Basic Terminology
Relational Schema (or head): set of all the
column names i.e. what info is bei ...
The document discusses new developer features introduced in SQL Server 2012-2016, including SSDT tools, T-SQL improvements like THROW and sequences, in-memory OLTP, common table expressions, and features in SQL Server 2016 such as dynamic data masking, row-level security, always encrypted, temporal tables, and JSON support. SQL Server 2016 also introduced the DROP IF EXISTS statement to drop objects and the ability to insert rows using merge statements with common table expressions.
Data Modeling, Normalization, and De-Normalization | PostgresOpen 2019 | Dimi...Citus Data
As a developer using PostgreSQL one of the most important tasks you have to deal with is modeling the database schema for your application. In order to achieve a solid design, it’s important to understand how the schema is then going to be used as well as the trade-offs it involves.
As Fred Brooks said: “Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts; they’ll be obvious.”
In this talk we're going to see practical normalisation examples and their benefits, and also review some anti-patterns and their typical PostgreSQL solutions, including Denormalization techniques thanks to advanced Data Types.
SQL Server 2000 provides database functionality including tables, indexes, queries, and stored procedures. It allows for structured storage and retrieval of data. Key objects in SQL Server include databases, tables, indexes, and queries. Databases can be designed in normal forms to avoid data duplication and inconsistencies.
Introduction to MariaDB. Covers the history of Structured Query language, MySQL and MariaDB, shows how to install on Windows, Mac or Linux desktop, and practical examples.
Reducing Development Time with MongoDB vs. SQLMongoDB
Buzz Moschetti compares the development time and effort required to save and fetch contact data using MongoDB versus SQL over the course of two weeks. With SQL, each time a new field is added or the data structure changes, the SQL schema must be altered and code updated in multiple places. With MongoDB, the data structure can evolve freely without changes to the data access code - it remains a simple insert and find. By day 14, representing the more complex data structure in SQL would require flattening some data and storing it in non-ideal ways, while MongoDB continues to require no changes to the simple data access code.
The document provides an overview of a webinar on transitioning from SQL to MongoDB. It introduces the presenter Buzz Moschetti and his background. It then discusses how developers currently spend their time integrating with different components and systems like databases, and how the mismatch between data at the business level versus the database level has been a long-standing problem. The document uses examples to show how MongoDB can help by allowing richer data structures and a more direct match between data in code and the database.
This document discusses techniques for efficient pagination over large datasets using MySQL. The typical solution of using LIMIT and OFFSET can degrade performance as the offset increases. The document proposes using additional criteria like a "last seen" value combined with ordering to page through data without large offsets. It demonstrates how this approach avoids reading unnecessary rows and allows pagination to be handled with a single indexed query, improving throughput by over 5x compared to the offset approach. Drawbacks like links becoming stale and search engine optimization are also discussed.
This document discusses techniques for efficient pagination over large datasets using MySQL. The typical solution of using LIMIT and OFFSET can degrade performance as the offset increases. The document proposes using additional criteria like a "last seen" value combined with ordering to retrieve the next page without an offset. This allows fetching the next results set using an index scan. Testing showed a 6x improvement in query throughput over using large offsets. Additional enhancements like secondary indexes and caching are discussed to further optimize pagination.
Apache Spark - Dataframes & Spark SQL - Part 1 | Big Data Hadoop Spark Tutori...CloudxLab
Big Data with Hadoop & Spark Training: http://bit.ly/2sf2z6i
This CloudxLab Introduction to Spark SQL & DataFrames tutorial helps you to understand Spark SQL & DataFrames in detail. Below are the topics covered in this slide:
1) Introduction to DataFrames
2) Creating DataFrames from JSON
3) DataFrame Operations
4) Running SQL Queries Programmatically
5) Datasets
6) Inferring the Schema Using Reflection
7) Programmatically Specifying the Schema
Hidden Gems of Performance Tuning: Hierarchical Profiler and DML Trigger Opti...Michael Rosenblum
In any large ecosystem, there are always areas that stay in the twilight, outside of the public’s attention. This deep dive attempts to change the trend regarding two, at first glance, unrelated PL/SQL topics: hierarchical profiler (HProf) and database triggers. But if you look closer, there’s something in common: they’re significantly underused! HProf because nobody heard about it, database triggers because of decades-old stigma. Let’s put both of them back into our development toolset!
Part #1. One of the most critical FREE SQL and PL/SQL performance tuning tools is almost totally unknown! If you ask, how much time is spent on routine A? How often is function B called? Most developers would hand-code something instead of using the Oracle PL/SQL HProf. This isn’t because the provided functionality is disliked, but because developers aren’t aware of its existence! This presentation is an attempt to alter this trend and reintroduce HProf to a wider audience.
Part #2. There isn’t anything “evil” about database triggers; they just have to be used where they can actually solve problems. In this presentation, various kinds of triggers will be examined from a global system optimization view, including tradeoffs between multiple goals (e.g., depending upon the available hardware, developers can select either CPU-intensive or I/O-intensive solutions). This presentation will focus on the most common performance problems related to different kinds of DML triggers and the proper ways of resolving them.
The document discusses problems with traditional mutable databases like losing history data when records are updated and the inability to retrieve past states. It introduces Datomic as an immutable database that can retrieve past states using its "as-of" operator similar to a git checkout. It also explains that Datomic improves scalability by running queries on clients instead of the server and uses transactions through data forms instead of SQL to prevent injection attacks. Workarounds without Datomic include using as-of in SQL 2011, Kafka with CQRS/event sourcing, or wrapping SQL in APIs. Overall, Datomic provides lessons on separating reaction from perception and solving impedance mismatch through an alternative approach of decomposing databases.
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
WWDC 2024 Keynote Review: For CocoaCoders AustinPatrick Weigel
Overview of WWDC 2024 Keynote Address.
Covers: Apple Intelligence, iOS18, macOS Sequoia, iPadOS, watchOS, visionOS, and Apple TV+.
Understandable dialogue on Apple TV+
On-device app controlling AI.
Access to ChatGPT with a guest appearance by Chief Data Thief Sam Altman!
App Locking! iPhone Mirroring! And a Calculator!!
An introduction to the different types of NoSQL and some guidance on when to choose them, and when to use plain old SQL. Focuses on developer productivity, intuitive code, and system issues including scaling and usage patterns. As delivered at JavaOne 2014 in San Francisco
This document provides an overview and introduction to MySQL. It begins with a comparison of MySQL to Microsoft Access, noting MySQL's open source nature, availability on multiple platforms, and emphasis on fast query processing. It then covers how to connect to the MySQL server from the command line. The document spends the majority of its time reviewing SQL, including data definition commands to create tables and define data types, as well as data manipulation commands to select, insert, update and delete data. It also covers joining multiple tables, ordering and grouping results, and using aggregate functions. In summary, this document serves as an introduction and primer to the basics of MySQL and SQL.
This document provides an introduction to Microsoft SQL Server and basic SQL statements. It discusses that MS SQL Server is a relational database management system developed by Microsoft that stores and retrieves data. It has several editions for different workloads and audiences. It then covers key SQL statements like CREATE TABLE, SELECT, INSERT, UPDATE, and DELETE and provides examples of how to use each statement to interact with database tables in MS SQL Server.
The document discusses Structured Query Language (SQL) and its basic statements. It covers:
- SQL is used to request and retrieve data from databases. The DBMS processes SQL queries and returns results.
- SQL statements are divided into DDL (data definition language) for managing schema, DML (data manipulation language) for data queries/modification, and DCL (data control language) for managing transactions and access control.
- The document provides examples of using SQL commands like CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE, DELETE, SELECT and indexes. It also covers data types, constraints and operators used in SQL queries.
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
How fast can you modify your data collection to include a new field, make all the necessary changes in data processing and storage, and then use that field in analytics or product features? For many companies, the answer is a few quarters, whereas others do it in a day. This data agility latency has a direct impact on companies' ability to innovate with data. Schema-on-read has been a key strategy to lower that latency - as the community has shifted towards storing data outside relational databases, we no longer need to make series of schema changes through the whole data chain, coordinated between teams to minimise operational risk. Schema-on-read comes with a cost, however. Errors that we used to catch during testing or in early test deployments can now sneak into production undetected and surface as product errors or hard-to-debug data quality problems later than with schema-on-write solutions.
In this presentation, we will show how we have rejected the tradeoff between slow schema change rate and quality to achieve the best of both worlds. By using metaprogramming and versioned pipelines that are tested end-to-end, we can achieve fast schema changes with schema-on-write and the protection of static typing. We will describe the tools in our toolbox - Scalameta, Chimney, Bazel, and custom tools. We will also show how we leverage them to take static typing one step further and differentiate between domain types that share representation, e.g. EmailAddress vs ValidatedEmailAddress or kW vs kWh, while maintaining harmony with data technology ecosystems.
1. The document describes a midterm exam for a C++ programming course that consists of multiple choice questions and has a time limit of 2 hours.
2. It provides sample exam questions about C++ concepts like functions, variables, conditionals, and data types.
3. The student completed the exam, scoring 64 out of 100 points within the 2 hour time limit.
SQL Server 2000 Research Series - Essential KnowledgeJerry Yang
This document provides an agenda for a training on SQL Server 2000, covering the SQL Server 2000 environment including tools like Service Manager and Enterprise Manager, fundamental database operations including tables, indexes and DDL/DML/DCL commands, and recommended references for further reading on SQL Server and database fundamentals.
Development time is wasted as the bulk of the work shifts from adding business features to struggling with the RDBMS. MongoDB, the leading NoSQL database, offers a flexible and scalable solution.
L1 Intro to Relational DBMS LP.pdfIntro to Relational .docxDIPESH30
L1 Intro to Relational DBMS LP.pdf
Intro to Relational
Databases
CS 2215 Introduction to Databases
1
2
What Is a DBMS?
Database: A collection of information.
Eg ?
Examples: Library, University
Database Management System (DBMS) :
software package designed to store
and manage databases.
Eg: Oracle, SQL server, MySQL, Access
Files vs DBMS : Why bother with
databases ?
Why not just store all the data in a big file
and write C or Java programs to manipulate
the data. 2
3
Why Use a DBMS?
Naïve users sheltered from messy
details
Data integrity:
Eg: if Bob works in Marketing, make
sure there is a dept. called Marketing.
Reduced application development
time: Avoid writing special programs
from scratch each time to access
data.
Standard Application Interface:
increased reliability
3
4
Why Use a DBMS?
Data independence: easier
to make changes
If how data is stored changes,
don’t have to change views.
Forms, etc.
Security: easier to control
how data is shared
Concurrent access: allow
multiple users to access
simultaneously
But in a controlled way !
4
5
Different people involved
DBMS implementers: who build the DBMS like
Oracle, MS SQL server
End users: Use forms & reports, might write SQL
queries
DB application programmers: write programs
to make life easier for end users.
Eg: person who creates forms for library.
Must know how databases work
DB administrator (DBA):
Handles security and authorization
Crash recovery
Database tuning as needs evolve
5
6
Overview of course: Relational Model:
Student Database, Fig 1.2
6
STUDENT
Name StudentNumber Class Major
Smith 17 1 CS
Brown 8 2 CS
7
Overview of course:
Data Models:
High level : Entity Relation (E.R.) model
Intermediate level : relational model
Student database
Low level: physical database -
Covered in CSCI 4524 Advanced
Databases
Relational databases:
Integrity constraints
Good design : normalization
Query languages: Relational
algebra, SQL
Views, Assertions, Triggers
7
8
Relational Data Model
Relation: 2-dimensional table
All info stored in tables
Eg: student, course
See Elmasri Fig 1.2
Rows (or tuples): student : 2 rows
Records: a row may correspond with a
record in a file
Commonly used if we are talking about the
physical storage of databases
Columns (or attributes): student : 4
columns
8
9
Relational Data Model
Relational model proposed by E. F.
Codd 1970
Dominant model in commercial DBMS
products.
Eg: Oracle, SQL server, MySQL, Access.
Compared to previous models
(network, hierarchical etc):
Easier to understand info in tables
Casual user can write simple SQL queries
Complex queries much easier to
understand compared to previous models.
9
10
Basic Terminology
Relational Schema (or head): set of all the
column names i.e. what info is bei ...
The document discusses new developer features introduced in SQL Server 2012-2016, including SSDT tools, T-SQL improvements like THROW and sequences, in-memory OLTP, common table expressions, and features in SQL Server 2016 such as dynamic data masking, row-level security, always encrypted, temporal tables, and JSON support. SQL Server 2016 also introduced the DROP IF EXISTS statement to drop objects and the ability to insert rows using merge statements with common table expressions.
Data Modeling, Normalization, and De-Normalization | PostgresOpen 2019 | Dimi...Citus Data
As a developer using PostgreSQL one of the most important tasks you have to deal with is modeling the database schema for your application. In order to achieve a solid design, it’s important to understand how the schema is then going to be used as well as the trade-offs it involves.
As Fred Brooks said: “Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts; they’ll be obvious.”
In this talk we're going to see practical normalisation examples and their benefits, and also review some anti-patterns and their typical PostgreSQL solutions, including Denormalization techniques thanks to advanced Data Types.
SQL Server 2000 provides database functionality including tables, indexes, queries, and stored procedures. It allows for structured storage and retrieval of data. Key objects in SQL Server include databases, tables, indexes, and queries. Databases can be designed in normal forms to avoid data duplication and inconsistencies.
Introduction to MariaDB. Covers the history of Structured Query language, MySQL and MariaDB, shows how to install on Windows, Mac or Linux desktop, and practical examples.
Reducing Development Time with MongoDB vs. SQLMongoDB
Buzz Moschetti compares the development time and effort required to save and fetch contact data using MongoDB versus SQL over the course of two weeks. With SQL, each time a new field is added or the data structure changes, the SQL schema must be altered and code updated in multiple places. With MongoDB, the data structure can evolve freely without changes to the data access code - it remains a simple insert and find. By day 14, representing the more complex data structure in SQL would require flattening some data and storing it in non-ideal ways, while MongoDB continues to require no changes to the simple data access code.
The document provides an overview of a webinar on transitioning from SQL to MongoDB. It introduces the presenter Buzz Moschetti and his background. It then discusses how developers currently spend their time integrating with different components and systems like databases, and how the mismatch between data at the business level versus the database level has been a long-standing problem. The document uses examples to show how MongoDB can help by allowing richer data structures and a more direct match between data in code and the database.
This document discusses techniques for efficient pagination over large datasets using MySQL. The typical solution of using LIMIT and OFFSET can degrade performance as the offset increases. The document proposes using additional criteria like a "last seen" value combined with ordering to page through data without large offsets. It demonstrates how this approach avoids reading unnecessary rows and allows pagination to be handled with a single indexed query, improving throughput by over 5x compared to the offset approach. Drawbacks like links becoming stale and search engine optimization are also discussed.
This document discusses techniques for efficient pagination over large datasets using MySQL. The typical solution of using LIMIT and OFFSET can degrade performance as the offset increases. The document proposes using additional criteria like a "last seen" value combined with ordering to retrieve the next page without an offset. This allows fetching the next results set using an index scan. Testing showed a 6x improvement in query throughput over using large offsets. Additional enhancements like secondary indexes and caching are discussed to further optimize pagination.
Apache Spark - Dataframes & Spark SQL - Part 1 | Big Data Hadoop Spark Tutori...CloudxLab
Big Data with Hadoop & Spark Training: http://bit.ly/2sf2z6i
This CloudxLab Introduction to Spark SQL & DataFrames tutorial helps you to understand Spark SQL & DataFrames in detail. Below are the topics covered in this slide:
1) Introduction to DataFrames
2) Creating DataFrames from JSON
3) DataFrame Operations
4) Running SQL Queries Programmatically
5) Datasets
6) Inferring the Schema Using Reflection
7) Programmatically Specifying the Schema
Hidden Gems of Performance Tuning: Hierarchical Profiler and DML Trigger Opti...Michael Rosenblum
In any large ecosystem, there are always areas that stay in the twilight, outside of the public’s attention. This deep dive attempts to change the trend regarding two, at first glance, unrelated PL/SQL topics: hierarchical profiler (HProf) and database triggers. But if you look closer, there’s something in common: they’re significantly underused! HProf because nobody heard about it, database triggers because of decades-old stigma. Let’s put both of them back into our development toolset!
Part #1. One of the most critical FREE SQL and PL/SQL performance tuning tools is almost totally unknown! If you ask, how much time is spent on routine A? How often is function B called? Most developers would hand-code something instead of using the Oracle PL/SQL HProf. This isn’t because the provided functionality is disliked, but because developers aren’t aware of its existence! This presentation is an attempt to alter this trend and reintroduce HProf to a wider audience.
Part #2. There isn’t anything “evil” about database triggers; they just have to be used where they can actually solve problems. In this presentation, various kinds of triggers will be examined from a global system optimization view, including tradeoffs between multiple goals (e.g., depending upon the available hardware, developers can select either CPU-intensive or I/O-intensive solutions). This presentation will focus on the most common performance problems related to different kinds of DML triggers and the proper ways of resolving them.
The document discusses problems with traditional mutable databases like losing history data when records are updated and the inability to retrieve past states. It introduces Datomic as an immutable database that can retrieve past states using its "as-of" operator similar to a git checkout. It also explains that Datomic improves scalability by running queries on clients instead of the server and uses transactions through data forms instead of SQL to prevent injection attacks. Workarounds without Datomic include using as-of in SQL 2011, Kafka with CQRS/event sourcing, or wrapping SQL in APIs. Overall, Datomic provides lessons on separating reaction from perception and solving impedance mismatch through an alternative approach of decomposing databases.
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
WWDC 2024 Keynote Review: For CocoaCoders AustinPatrick Weigel
Overview of WWDC 2024 Keynote Address.
Covers: Apple Intelligence, iOS18, macOS Sequoia, iPadOS, watchOS, visionOS, and Apple TV+.
Understandable dialogue on Apple TV+
On-device app controlling AI.
Access to ChatGPT with a guest appearance by Chief Data Thief Sam Altman!
App Locking! iPhone Mirroring! And a Calculator!!
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...kalichargn70th171
In today's business landscape, digital integration is ubiquitous, demanding swift innovation as a necessity rather than a luxury. In a fiercely competitive market with heightened customer expectations, the timely launch of flawless digital products is crucial for both acquisition and retention—any delay risks ceding market share to competitors.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Drona Infotech is a premier mobile app development company in Noida, providing cutting-edge solutions for businesses.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
Preparing Non - Technical Founders for Engaging a Tech AgencyISH Technologies
Preparing non-technical founders before engaging a tech agency is crucial for the success of their projects. It starts with clearly defining their vision and goals, conducting thorough market research, and gaining a basic understanding of relevant technologies. Setting realistic expectations and preparing a detailed project brief are essential steps. Founders should select a tech agency with a proven track record and establish clear communication channels. Additionally, addressing legal and contractual considerations and planning for post-launch support are vital to ensure a smooth and successful collaboration. This preparation empowers non-technical founders to effectively communicate their needs and work seamlessly with their chosen tech agency.Visit our site to get more details about this. Contact us today www.ishtechnologies.com.au
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...XfilesPro
Wondering how X-Sign gained popularity in a quick time span? This eSign functionality of XfilesPro DocuPrime has many advancements to offer for Salesforce users. Explore them now!
Consistent toolbox talks are critical for maintaining workplace safety, as they provide regular opportunities to address specific hazards and reinforce safe practices.
These brief, focused sessions ensure that safety is a continual conversation rather than a one-time event, which helps keep safety protocols fresh in employees' minds. Studies have shown that shorter, more frequent training sessions are more effective for retention and behavior change compared to longer, infrequent sessions.
Engaging workers regularly, toolbox talks promote a culture of safety, empower employees to voice concerns, and ultimately reduce the likelihood of accidents and injuries on site.
The traditional method of conducting safety talks with paper documents and lengthy meetings is not only time-consuming but also less effective. Manual tracking of attendance and compliance is prone to errors and inconsistencies, leading to gaps in safety communication and potential non-compliance with OSHA regulations. Switching to a digital solution like Safelyio offers significant advantages.
Safelyio automates the delivery and documentation of safety talks, ensuring consistency and accessibility. The microlearning approach breaks down complex safety protocols into manageable, bite-sized pieces, making it easier for employees to absorb and retain information.
This method minimizes disruptions to work schedules, eliminates the hassle of paperwork, and ensures that all safety communications are tracked and recorded accurately. Ultimately, using a digital platform like Safelyio enhances engagement, compliance, and overall safety performance on site. https://safelyio.com/
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
How Can Hiring A Mobile App Development Company Help Your Business Grow?ToXSL Technologies
ToXSL Technologies is an award-winning Mobile App Development Company in Dubai that helps businesses reshape their digital possibilities with custom app services. As a top app development company in Dubai, we offer highly engaging iOS & Android app solutions. https://rb.gy/necdnt
How Can Hiring A Mobile App Development Company Help Your Business Grow?
SQL: tricks and cheats
1. SQL: tricks and cheats,
или очевидное рядом
Java meetup, Chernihiv, 8th June 2019
Mikalai Sitsko
2. About me
Mikalai Sitsko – a developer, more than 15 years of IT experience, main
subject is developing application at Java, Delphi, SQL, works for
Andersen
2
3. A. Contents
I. Introduction
II. Database Design
III. DDL Tricks & Tips
IV. DML Tricks & Tips
V. Useful Features
VI. Table Security Issues
VII.References
3
4. I. Introduction
1. Short summary
2. Brief history
3. SQL is not dead!
4. Acronyms&abbreviations
4
5. Short summary
• Consider typical mistakes using SQL for RDBMS
• Consider typical problems and issues
• Remind useful features
• Show multiple ways and solution flexibility
• Backend vs RDBMS (similar but different)
5
8. History (brief)
1960s
CODASYL (network)
IMS (hierarchical)
1970s
E.F. Codd (Relation model)
P. Chen (E-R),
RDBMS:
Ingres (1974),
DB2 (1983),
System R,
SQL/DS,
Allbase,
Oracle (1980)
file-server DBMS
dBase (1979)
1980s
J. Gray, A. Reuter, T. Härder
(ACID)
SQL standards
Parallel & distributed DBMS
client-server RDBMS
Interbase (1984),
Informix (1984),
SAP ASE (1987)
MSSQL (1989)
PostgreSQL (1989)
file-server DBMS
Paradox (1985)
1990s 2000s
Web commerce
MySQL (1995)
OODBMS
Cache (1997)
NoSQL
- Key value
- Wide column
- Document
GraphDB
Flexibility,
XML
Firebird (2000)
2010s
BigData
TSDB
Temporal
JSON
8
9. SQL is not dead!
Main consideration
• Standard (SQL:86, 89, 92, 99, 2003, 2006, 2008, 2011, 2016)
• New elements (XML, JSON, more flexibility)
• Declarative style
• Family of [XXX]QL based on SQL
• Universal architectural pattern
9
10. Acronyms and abbreviations
SQL – Structured Query Language
ERD – Entity-Relation Diagram
DML – Data Manipulation Language
DDL – Data Definition Language
NF – Normal Forms
ID – identifier
FK – foreign key
PK – primary key
UUID – Universal unique identifier
ANSI – American National Standard Institute
ISO – International Organization for Standardization
DBMS – database management system
10
16. ID
Problem: we would like to insert a row with an artificial unique key
Possible solutions:
1. UUID
2. Generator tables
3. MAX + 1
4. Autoincrement/Identity
5. Sequence
16
17. ID
Problem: we would like to insert a row with an artificial unique key
Solution: #1 uuid
DDL
----
CREATE TABLE person (
id uniqueidentifier,
…
);
Supported in:
PostgreSQL -- UUID_GENERATE_V4(),
MSSQL – NEWID()
Firebird -- GEN_UUID(),
Oracle – SYS_GUID(),
MariaDB – UUID(),
Supported in:
PostgreSQL -- uuid
MSSQL – uniqueidentifier
Firebird, Oracle, MariaDB – supported implicitly
as varchar(16/32/36) or binary(16)
DML
----
INSERT INTO person (id, …)
VALUES(NEWID(),…);
17
18. ID
Problem: we would like to insert a row with an artificial unique key
Solution: #2 generator table DML
----
START TRANSACTION;
SELECT
seq
FROM generators
WHERE seq_name = 'seq_person'
INTO :pId
FOR UPDATE;
INSERT INTO PERSON(id,…) VALUES(:pID,…);
UPDATE
SET
seq = seq + 1
WHERE seq_name = 'person';
COMMIT;
DDL
----
CREATE TABLE generators
( seq int not null default 1,
seq_name varchar(32) unique);
INSERT INTO
generators(seq_name)
VALUES
('seq_person'),
('seq_company');
18
19. ID
Problem: we would like to insert a row with an artificial unique key
Solution: #3 MAX+1
DML 1
----
START TRANSACTION;
SELECT
COALESCE(MAX(id), 0) + 1
FROM person
INTO :pId
WITH LOCK;
INSERT INTO PERSON(id,…)
VALUES(:pId,…);
COMMIT;
DML 2
----
START TRANSACTION;
INSERT INTO PERSON(id,…)
SELECT
COALESCE(MAX(id), 0) + 1,
'Name',
…
FROM person
GROUP BY …;
COMMIT;
19
20. ID
Problem: we would like to insert a row with an artificial unique key
Solution: #4 Autoincrement/IDENTITY
DML
----
START TRANSACTION;
INSERT INTO
PERSON(first_name,…)
VALUES(…);
COMMIT;
DDL
----
CREATE TABLE person (
id int IDENTITY NOT NULL PRIMARY KEY,
…)
Supported in:
MSSQL – identity
MySQL, MariaDB – auto_increment
Firebird – generated by default as identity
PostgreSQL – serial
Oracle – generated by default on null as identity
20
21. ID
Problem: we would like to insert a row with an artificial unique key
Solution: #5 Sequence
DML
----
START TRANSACTION;
INSERT INTO PERSON(id, first_name,…)
VALUES(NEXT VALUE FOR seq_person, ?
…);
COMMIT;
DDL
----
CREATE SEQUENCE seq_person;
CREATE TABLE person (
id int NOT NULL,
…)
Supported in all RDBMS
MySQL – not supported
21
22. Columns
Problem: we would like to get full name (simplify operations with columns)
Possible solutions:
1. At client side
2. In select table
3. In select view
4. Generated column
22
23. Columns
Problem: we would like to get column full name (simplify often calculations with columns)
Solution: #2 select table
DML
----
SELECT
p.last_name || ', ' || p.first_name
FROM
person p
WHERE
p.id = ?
23
24. Columns
Problem: we would like to get column full name (simplify often calculations with columns)
Solution: #3 select view
DDL
-----
CREATE VIEW v_person
AS
SELECT
p.last_name || ', ' || p.first_name
as full_name
FROM
person p
DML
-----
SELECT
p.full_name
FROM
v_person p
24
25. Columns
Problem: we would like to simplify often calculations with columns
Solution: #4 generated column
DDL
----
ALTER TABLE person ADD
full_name GENERATED ALWAYS AS
p.last_name || ', ' || p.first_name;
Supported in:
Firebird -- virtual only
MSSQL, Oracle, MariaDB/MySQL -- virtual, stored
DML
----
SELECT
p.full_name
FROM
person p
WHERE
p.id = ?
25
26. Constraints/Foreign key
Problem: we would like to create dependency between tables
Solution: #1 FK typical syntax
ALTER TABLE work
ADD CONSTRAINT fk_work_person
FOREIGN KEY (person_id)
REFERENCE person (id);
26
27. Constraints/Foreign key
Problem: we would like to create dependency between tables
Solution: #2 FK syntax with actions
ALTER TABLE work
ADD CONSTRAINT fk_work_person
FOREIGN KEY (person_id)
REFERENCE person (id)
ON DELETE CASCADE ON UPDATE CASCADE;
Type of actions
------------------
NO ACTION
CASCADE
SET NULL
SET DEFAULT
27
28. IV. DML
1. Operation with NULL
2. Select
1. Select
2. From clause
3. Order clause
3. Insert
4. Update or Insert
28
29. Operation with NULL
SELECT
p.first_name,
p.last_name,
p.iq + 10 as expected_result,
'Mr/Mrs ' || p.last_name as official_name
FROM
person p
WHERE
p.nick = NULL
ORDER BY
p.iq + 10;
Multi-behaviour:
Firebird, PostgreSQL – independent
MSSQL – depend on CONCAT_NULL_YIELDS_NULL, ANSI_NULLS (deprecated)
MariaDB – depend on SQL_MODE
Problem: we would like to get data which have null nickname
Solution: #1 direct comparison
29
30. Operation with NULL
SELECT
p.first_name,
p.last_name,
COALESCE(p.iq + 10, 0) as expected_result,
CASE
WHEN p.last_name IS NOT NULL
THEN 'Mr/Mrs ' || p.last_name
ELSE 'Sir/Madam'
END AS official_name
FROM
person p
WHERE
p.nick IS NULL
ORDER BY
3;
Problem: we would like to get data which have null nickname
Solution: #2 protective syntax
30
31. ANSI/ISO NULL
Boolean condition
-------
not NULL -> NULL
NULL or false -> NULL
NULL or true -> true
NULL or NULL -> NULL
NULL and false -> false
NULL and true -> NULL
NULL and NULL -> NULL
Comparison conditions
-------
10 is NULL -> false
10 is not NULL -> true
10 = NULL -> NULL
10 <> NULL -> NULL
10 > NULL -> NULL
10 < NULL -> NULL
NULL = NULL -> NULL
Operators
-------
value NULL -> NULL
Built in Functions
---------
func(NULL, value2) ->
NULL
SQL NULL is not the same as backend null!
31
34. Select exactly one row
SELECT
CURRENT_TIMESTAMP,
CURRENT_USER
FROM
person
LIMIT 1;
Problem: we would like to get current server datetime and username
Solution: #1 select with limit
34
35. Select exactly one row
DML 1
----
SELECT
CURRENT_TIMESTAMP,
CURRENT_USER;
Supported in:
PostgreSQL,
MariaDB, MySQL,
MSSQL, …
DML 2
----
SELECT
CURRENT_TIMESTAMP,
CURRENT_USER
FROM
dual
Supported in:
Firebird -- RDB$DATABASE
Oracle -- DUAL
Problem: we would like to get current server datetime and username
Solution: #2 select without FROM
35
36. Select table and column list
Problem: to make sure that table person exists in database
Solution: #1 try-catch
Client side
----
try{
…
SELECT
*
FROM
person
WHERE
1=0
…
}
catch(){
}
36
37. Select table and column list
Problem: to make sure that table person exists in database
Solution: #2 information_schema
DML
-----
SELECT
t.table_name,
t.table_type
FROM
INFORMATION_SCHEMA.TABLES t
WHERE
t.TABLE_TYPE = 'BASE TABLE'
AND t.table_name = 'person'
Supported in:
PostgreSQL,
MariaDB, MySQL,
MSSQL, … 37
38. Select table and column list
Problem: to make sure that table person exists in database
Solution: #3 system (metadata) tables
DML
-----
SELECT
t.name as table_name,
s.name as column_name
FROM sys.tables t
INNER JOIN sys.columns s ON t.object_id = s.object_id
WHERE
t.name = 'person'
Supported in all RDBMS
but native naming
38
39. class Person{
…
public String getFullName(){
String fullName = "";
…
if (lastName != null){
fullName = fullName + lastName;
}
…
if (firstName != null){
fullName = fullName + firstName;
}
…
return fullName;
}
}
Select concated string
Problem: combine several columns into one (first_name, middle_name, last_name)
Solution: #1 Concat columns at client side (class, streams)
39
40. SELECT
p.last_name ||
p.first_name ||
p.middle_name
FROM
person p
WHERE
id = ?
Supported:
'||' – Firebird, PostgerSQL, ORACLE, MariaDB
'+' – MSSQL, MariaDB
Select concated string
Problem: combine several columns into one (last_name, first_name, middle_name)
Solution: #2 concat at server side
40
41. SELECT
CONCAT(p.last_name,
p.first_name,
p.middle_name)
FROM
person p
WHERE
id = ?
Supported:
Firebird – not supported,
MariaDB – supported in Oracle mode
ORACLE – supported only 2 params
PostgreSQL, MSSQL – supported any count of parameters
Select concated string
Problem: combine several columns into one (first_name, middle_name, last_name)
Solution: #3 concat at server side
41
43. Select concated string
Supported in all RDBMS
DML
----
SELECT
p.full_name
FROM
person p
WHERE
id = ?
Problem: combine several columns into one (first_name, middle_name, last_name)
Solution: #5 generated column
DDL
----
ALTER TABLE person ADD
full_name GENERATED ALWAYS AS
COALESCE(p.last_name, '')
|| COALESCE(p.first_name, '')
|| COALESCE(p.middle_name, '');
43
44. Select not null column
Problem: get first not null columns into one (nick, first_name, last_name)
Solution: #1 client side (class, streams)
class Person{
…
public String getName(){
String name;
if (nick != null){
name = nick;
}elseif(firstName != null){
name = first_name;
}else{
name = last_name;
}
return name;
}
}
44
45. Select not null column
Problem: get first not null several columns into one (nick, first_name, last_name)
Solution: #2 check if null
SELECT
IFNULL(p.nick,
IFNULL(p.first_name,
IFNULL(p.last_name)))
FROM
person p
WHERE
id = ?
Supported in:
Firebird, PostgresSQL -- dont have
MySQL – IFNULL
MSSQL – ISNULL
Oracle – NVL
45
46. Select not null column
Problem: get first not null several columns into one (nick_name, first_name, last_name)
Solution: #3 Coalesce
SELECT
COALESCE(p.nick,
p.first_name,
p.last_name)
FROM
person p
WHERE
id = ?
Supported in all RDBMS
46
48. ORDER clause
Problem: sort columns by last_name and null values should be last
Solution: #1 add sort expression
DML
----
SELECT
p.first_name,
p.last_name
FROM
person p
ORDER BY
iif(p.last_name IS NULL, 1, 0),
p.last_name ASC
48
49. ORDER clause
Problem: sort columns by last_name and null values should be last
Solution: #2 null order
DML
----
SELECT
p.first_name,
p.last_name
FROM
person p
ORDER BY
p.last_name ASC NULLS LAST
Supported in:
PostgreSQL, Firebird, Oracle -- supported
MSSQL -- not supported
49
50. ORDER clause
Problem: sort by calculated column
Solution: #1 repeat expression
DML
----
SELECT
p.first_name,
p.last_name,
p.iq * 10 – p.rating*0.5
FROM
person p
ORDER BY
p.iq * 10 – p.rating*0.5 DESC
50
51. ORDER clause
Problem: sort by calculated column
Solution: #2 by number
DML
----
SELECT
p.first_name,
p.last_name,
p.iq * 10 – p.rating*0.5
FROM
person p
ORDER BY
3 DESC
51
52. Insert
DML
----
SELECT LAST_INSERT_ID;
Supported in:
MariaDB, MySQL -- LAST_INSERT_ID
MSSQL -- SCOPE_IDENTITY, IDENT_CURRENT(), and @@IDENTITY
Problem: we would like to know id (primary key) for an inserted row after insertion
Solution: #1 if Id is auto increment/identity
52
53. Insert
Supported in:
PostgreSQL, Firebird, Oracle – supported
MSSQL – OUTPUT (works for non-identity columns)
INSERT INTO person (first_name, last_name)
VALUES('Tony', 'Hoare')
RETURNING id INTO ?;
Problem: we would like to know id for a inserted row after insertion
Solution: #2 returning clause
53
55. Insert
Problem: we would like to know id for a inserted row before insertion
Solution: #2 simulation generators
DML
----
START TRANSACTION;
UPDATE generators
SET
seq_value = seq_value + 1
WHERE
seq_name = ?
RETURNING seq_value INTO :pSeq;
INSERT INTO person(id, …) VALUES(:pSeq);
COMMIT;
55
56. Insert
Problem: we would like to know id for a inserted row before insertion
Solution: #3 Sequence
DML 1
----
SELECT
nextval(seq_person);
Supported in:
PostgreSQL,
Firebird,
Oracle, …
MSSQL, MariaDB
DML 2
----
NEXT VALUE FOR seq_person;
DDL
----
CREATE SEQUENCE
seq_person;
INSERT INTO person(id,…) VALUES(?);
56
57. Insert
Problem: we would like to know id for a inserted row before insertion
Solution: #4 uuid
Client code
----
UUID id = UUID.randomUUID();
DML
----
SELECT NEWID();
Supported in:
PostgreSQL -- UUID_GENERATE_V4(), type support
Firebird -- GEN_UUID(),
Oracle – SYS_GUID(),
MSSQL – NEWID() , type support
MariaDB – UUID(),
57
58. Update or Insert
String queryInsert = "INSERT INTO person (id, …) VALUES (?, …)";
String queryUpdate = "UPDATE person SET first_name =?, … WHERE id = ?";
try {
Statement stmt = con.createStatement();
stmt.set…
stmt.executeQuery(queryInsert);
…
}
catch() {
Statement stmtUpdate = con.createStatement();
stmtUpdate.set…
stmtUpdate.executeQuery(queryUpdate);
…
}
Problem: we would like to update row, if not exist – to insert a new one
Solution: #1 try-catch
58
59. Update or Insert
Supported in:
PostgreSQL – INSERT INTO TABLE … ON CONFLICT UPDATE…,
Firebird -- UPDATE or INSERT,
MariaDB – INSERT ... ON DUPLICATE KEY UPDATE
Problem: we would like to update row, if not exist – to insert a new one
Solution: #2 upsert
DML 1
----
UPDATE OR INSERT INTO person
(id, first_name, last_name)
VALUES (?, ?, ?)
MATCHING (id);
DML 2
----
INSERT INTO person
(id, first_name, last_name)
VALUES (?, ?, ?)
ON CONFLICT (id) DO
UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name;
59
60. Update or Insert
Problem: we would like to update row, if not exist – to insert a new one
Solution: #3 merge
DML
----
MERGE INTO person p
USING (SELECT ? as id, ? as first_name, ? as last_name) m
ON p.id = m.id
WHEN MATCHED THEN UPDATE SET
p.first_name = m.first_name,
p.last_name = m.last_name
WHEN NOT MATCHED THEN
INSERT (id, first_name, last_name)
VALUES (m.id, m.first_name, m.last_name)
Supported all RDBMS
60
61. V. Useful features
1. Window functions
2. CTE
3. Functional index
4. Temporary tables
5. Temporal tables
6. Autonomous transaction
7. Context variables
8. Dynamic SQL
61
62. VI. Restrict access to data in table
1. Table level
2. Column level
3. Row level
4. Customizing access level
62
64. Restrict CRUD
Problem: we would like restrict access to table person
Solution: #2 table + column level
Column level
-----
SELECT
UPDATE
INSERT
REFERENCES
…
DDL
----
GRANT UPDATE (id, first, name)
ON person TO Cauchy;
Supported all RDBMS
64
65. Restrict CRUD
Problem: we would like restrict access to table person
Solution: #3 table + column level + row level
Row level security
----
SELECT
UPDATE
INSERT
REFERENCES
…
DDL
----
ALTER TABLE person ENABLE ROW LEVEL SECURITY;
CREATE POLICY person_iq
FOR SELECT, UPDATE, DELETE ON person TO
managers
USING (rating > 90)
WITH CHECK ( rating > 90 and rating < 100);
Supported in:
Oracle, PostgreSQL, MSSQL – supported
Firebird, MariaDB/MySQL – not supported
65
66. Restrict CRUD
Problem: we would like restrict access to table person
Solution: #4 view (row security)
DDL
----
ALTER TABLE person ADD access_level INT;
CREATE FUNCTION has_access (…);
CREATE VIEW v_person
AS SELECT
p.*
FROM person p
WHERE has_access(CURRENT_USER, p.access_level)
66
67. Restrict CRUD
Problem: we would like restrict access to table person
Solution: #5 selectable stored procedure + triggers (table/column/row security)
DDL
----
67
69. Useful links
• RDBMS reference guides
• Web
• sql.ru/forum
• jOOQ.org
• RDBMS Developers: Firebird, PostgreSQL, MariaDB
• Java Champions (Vlad Mihalecia, Thorben Janssen)
• Youtube (HighLoad, Sergey Kuznetsov)
• Test and tutorials
• sql-ex.ru
• leetcode.com/problemset/database/
69
70. References
• Books
• C.J. Date Introduction to Data Base Systems
• M. Graber Understanding SQL
• V. Mihalcea High-Performance Java Persistence
• H. Borrie The Firebird Book: A Reference for Database Developers
• J.Lewis Oracle Core: Essential Internals for DBAs and Developers
• T. Kyte Expert Oracle Database Architecture
• A.Molinaro SQL: Cookbook
• …
70
Итак введение. В Ведении коснемся следующих вопросов. Цель доклада, краткая история SQL и DBMS, исходя из истории нам станет понятна почему SQL до сих пор остается важным ЯП
Цель доклада – рассказать про часто совершаемы ошибки разработчиками и как их избежать.
Рассмотрим типовые задачи и ошибки использования SQL, которые допускают начинающие и опытные бэкэнд разработчики при работе с реляционными СУБД. Зачастую разработчики не представляют всех широких возможностей SQL и ограничивают себя узкими рамками, что приводит к изобретению собственных «ноу-хау» как на стороне Application Server так и на стороне RDBMS, вместо того чтобы использовать уже имеющиеся решения.
В ходе доклада будут рассматриваться следующие RDBMS
Выбраны RDBMS – широко используются
В докладе не стоит ожидать HW подтекста, у каждого инструмента есть + и -
БД – оперативная обработка (хранение, извлечение)
В чем успех SQL и реляционных БД.
Введена стандартизация -- Complaints (full, partial, enhanced, equivalent, similar, none)
Прорабатывается
Стандартизирован
Эволюционирует
Декларативный стиль
Порождаются декларативные языки – базируются HQL, JPQL, LINQ, NoSQL, etc
УПАД – бэкэнд перетаскивает на себя функции СУБД (особенно с ORM)
Дизайн БД зависит от предметной области и требований/применений (!), он может быть разным
Дизайн важен потому что от него зависит:
понимание бизнес логики, насколько будет удобно оперировать бизнес-объектами.
Насколько тяжело рефакторитью
Дизайн БД определяет последующий дизайн приложения, но не наоборот
Эффективность и быстродейстиве.
На что нужно обратить внимание при проектировании БД
ERD как UML для бэкэнда
Checks
Views
Triggers
Stored procedures
Возможные решения – как вести id
Уникально, хорошо для репликаций
UUID – тяжело воспринимается, разная имплементация
Проблема – медленно и коллизии
Локи на основной таблице (пессимистичная блокировка)
-- postgresql
id INT GENERATED ALWAYS AS IDENTITY,
id SERIAL NOT NULL PRIMARY KEY,
Есть ограничения, выглядит как синтаксический сахар на последовательностями
Последние версии MSSQL и MariaDB – тоже поддерживают
Sequence – вне транзакций, самый быстрый способ, самый гибкий
Дублирования, сложно читать
4 экшена
SQL NULL <> Backend null
All columns
Naming collision
Heavy columns
Long names
all rows
unsorted
Table or view? User permission?
Dropped?
Must be at leas 1 row
Table or view?
Heavy operation
Overhead
IDENT_CURRENT('table') returns the last identity value generated for a specific table in any session and any scope.
@@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.