/r/SQL

Photograph via snooOG

The goal of /r/SQL is to provide a place for interesting and informative SQL content and discussions.

The goal of /r/SQL is to provide a place for interesting and informative SQL content and discussions.

Filter Posts

MySQL

Oracle

MS SQL

PostgreSQL

Posting

When requesting help or asking questions please prefix your title with the SQL variant/platform you are using within square brackets like so:

  • [MySQL]
  • [Oracle]
  • [MS SQL]
  • [PostgreSQL]
  • etc

While naturally we should endeavor to work as platform neutrally as possible many questions and answers require tailoring to the feature set of a specific platform.

Help posts

If you are a student or just looking for help on your code please do not just post your questions and expect the community to do all the work for you. We will gladly help where we can as long as you post the work you have already done or show that you have attempted to figure it out on your own.

Format Your Code

If you are including actual code in a post or comment, please attempt to format it in a way that is readable for other users. This will greatly increase your chances of receiving the help you desire. Something as simple as line breaks and using reddit's built in code formatting (4 spaces at the start of each line) can turn this:

SELECT count(a.field1), a.field2, SUM(b.field4) FROM a INNER JOIN b ON a.key1 = b.key1 WHERE a.field8 = 'test' GROUP by a.field1, a.field2 HAVING SUM(b.field4) > 5 ORDER by a.field.3

Into this:

SELECT count(a.field1),
  a.field2,
  SUM(b.field4) 
FROM a INNER JOIN b 
  ON a.key1 = b.key1 
WHERE a.field8 = 'test' 
GROUP by a.field1, 
  a.field2 
HAVING SUM(b.field4) > 5 
ORDER by a.field3

For those with SQL questions we recommend using SQLFiddle to provide a useful development and testing environment for those who wish to fully understand your problem and help devise a solution.

Learning SQL

A common question is how to learn SQL. Please view the Wiki for online resources.

Note /r/SQL does not allow links to basic tutorials to be posted here. Please see this discussion. You should post these to /r/learnsql instead.

Related Reddit communities


Wiki

We have a Wiki


Acknowledgements

Thanks to ---sniff--- for the awesome header image!

/r/SQL

215,037 Subscribers

1

Importing Excel Sheets into DBeaver and Choosing the Right Database

Hi everyone,

I’m just starting out with data analytics and trying to work with an Excel file that has multiple sheets. I wanted to import the file into DBeaver, but I found that I could only do it by converting each sheet into a separate CSV file. Is this the usual way people handle Excel files in tools like DBeaver, or is there a more convenient method I should be using?

Also, since I didn’t have an actual database set up, I created a SQLite database for this project. During my university course, we mostly used SQL Server, so I was wondering if SQLite is a good choice for this, or if I should have gone with something like MySQL instead. Could someone explain the differences between these databases in the context of learning and small projects?

I’m trying to build these skills to apply for an internship, and I’d really appreciate any advice or tips you might have. Thank you so much for your help!

0 Comments
2024/12/21
05:02 UTC

0

Programar para aprender Python

¿Que herramientas o cursos me recomiendan para iniciar en Python ?

0 Comments
2024/12/21
17:27 UTC

3

SQLite-Editor (open source code ) SQL-SELECT-WIZARD

0 Comments
2024/12/21
16:07 UTC

4

Different data values but matching UpdatedOn timestamps in SQL Server sync - am I missing something?

Hey SQL folks,

I'm working on syncing two databases using MERGE statements, and I noticed something odd. Some records have the exact same UpdatedOn timestamp in both source and target databases, but their actual data values are different.

My MERGE condition is:
WHEN MATCHED AND (source.UpdatedOn != ISNULL(target.UpdatedOn, '')) THEN UPDATE...

Questions:

  1. Is this a common issue you've encountered?
  2. What could cause data to be different when timestamps match?
  3. What's your preferred way to handle database syncs - do you rely on timestamps alone?

Feel like I'm missing something obvious here. Any insights would be appreciated!

1 Comment
2024/12/20
23:28 UTC

3

Save Result from CMS/Registered Server SQL

Hi is it possible to save to a table the query result from registered servers?

I was trying to get each servers versions and save it to a table so i can do this monthly. Thanks!

2 Comments
2024/12/20
22:45 UTC

0

Request for Database Schema Review - Stock Tracker App

Hello everyone,

I’m working on a personal project, an app designed to help distributors track their household stock, monitor product consumption, and manage promotional material distribution. The app needs to support multiple users in a household, with separate accounts for each, while also allowing them to manage product stock, track consumption (for personal use or promotion), and generate quarterly reports to send to their accountant. (I modeled the above to my own personal situation, but I know of some other people who might use this)

I’ve designed the following database schema and would appreciate feedback or suggestions on improvements or potential issues. Here’s the overview of the structure:

Enum Definitions:

  • Role: Defines user roles (admin or member).
  • Registration Type: Defines the type of registration (own use or promotional giveaway).

Tables:

user

  • id (integer, primary key)
  • username (varchar(50), unique, not null)
  • email (varchar(100), unique, not null)
  • password (varchar(255), not null)
  • household_id (int, references household.id, not null)
  • role (enum, defines the role of the user)
  • created_at (date)

household

  • id (integer, primary key)
  • name (varchar(100), not null)
  • created_at (date)

product

  • id (integer, primary key)
  • product_code (varchar(10), unique)
  • name (varchar(100))
  • created_at (date)

price_history

  • id (integer, primary key)
  • product_id (integer, references product.id)
  • price (integer, not null)
  • from (date, not null)
  • until (date, nullable)

stock

  • id (integer, primary key)
  • household_id (integer, references household.id)
  • product_id (integer, references product.id)
  • quantity (integer)
  • price (integer, not null)
  • added_at (date)

registration

  • id (integer, primary key)
  • household_id (integer, references household.id)
  • product_id (integer, references product.id)
  • user_id (integer, references user.id, note: 'to check who made the registration')
  • quantity (integer)
  • type (enum, registration type)
  • price (integer)
  • date (date)

Any feedback is welcome. Anything I might have overlooked or some glaring errors to the trained eye?

2 Comments
2024/12/20
22:17 UTC

2

Needed the best approach to pass content from req headers to sequelize hooks

I’m implementing audit logging for all create, update, and delete operations using Sequelize hooks. The logs are stored in an AuditLog table via a dedicated service (AuditLogService). The challenge is ensuring the userId (sent in the request headers) is captured and passed to the hooks when performing database operations.How can I effectively propagate userId (without passing from all services and controller) to Sequelize hooks without relying on CLS-hooked? Are there other reliable approaches that align with best practices for handling middleware-to-hook context sharing?

Would appreciate any insights or suggestions!

0 Comments
2024/12/20
19:43 UTC

1

I know the advances principles of SQL but I'm still insecure about it

Hey everyone, I would love to speak with anyone that has a lot of experience in SQL.. I learned the basics (SELECT, WHERE, FROM etc) and some advanced concepts (subqueries, CTEs, window functions etc) but I still feel kind of insecure about my level. I have a background marketing so I am very good at conveying a story through analysis, but I'm still kinda scared that I might completely freeze as soon as I have to use SQL in real life. did it ever feel like this for you as well ? How are you doing now ?

Thank you so much to anyone who will take the time to answer :)))

0 Comments
2024/12/20
19:00 UTC

27

Help! Can't decided between these two courses. I'm a beginner

45 Comments
2024/12/20
18:23 UTC

3

SQL Help Request

Hello, I would rate myself as a “middle of the road” SQL user. I’m pretty proficient I guess is a better way to say that. I’ve hit a wall on a query and wanted to reach out here to see if anyone had any ideas or suggestions. I’m limited as to what functions my query can do because it’s inside of a SPROC(it runs as a part of the SPROC). So for example I can’t create a temp table for a set of results and drop it after the query completes.

My dataset is based on an identifier, and also includes a Yes or No flag on each line. The identifier can have an item that is yes and also an item that is no(more than one item for each identifier). Currently I’m able to pull if it’s yes and if it’s no. However, if any of the items in the identifier group is no, I don’t want anything to return for that identifier. That’s where I’m stuck… it will pull back the items in the identifier group that are yes. I don’t even want those to come back if any of the items in the group are no.

Is that even doable? If it is, any suggestions on how to do that? I should note I’m using SSMS, TIA!!

16 Comments
2024/12/20
18:04 UTC

0

How to use SQL in Vscode?

Pls help

3 Comments
2024/12/20
17:37 UTC

0

I'm majoring in cs, but I am interested in sql. Will it be relevant for my career?

.

7 Comments
2024/12/20
17:30 UTC

4

Tutoring Resources

I've recently transitioned into a new role that utilizes a fair amount of SQL Server with up to intermediate knowledge. My role is mostly querying so that all I know. I'm confident in my understanding of RDBs but would like some live tutoring sessions. I'm a hands on learner. Does anyone have some recommendations where I may be able to purchase tutoring sessions?

TYIA 😁

2 Comments
2024/12/20
17:09 UTC

5

SQL

Where can I practice SQL advanced Data analytics questions free of cost.

11 Comments
2024/12/20
13:49 UTC

0

Future of SQL

Hello, does it still make sense to learn sql or will this soon be done by the AI anyway? If so, what skills will be needed in the future for working with customer data? I work in the crm area and with microsoft dynamics (customer insights data, power-bi)

26 Comments
2024/12/20
11:18 UTC

5

fetching one to many relationship data

In a database schema where a student has multiple subjects and present days, represented as JSON arrays, each with attributes like:

  • Student Table: idnamesexgradephonemonthly_pay
  • Subjects JSON Array: Each object containing idid_studentsubjectgroupteacherpricePaidsessionscurrent_session
  • Present Days JSON Array: Each object containing idgroupstudent_iddaysubject_attendedis_presentis_different_group

Which approach is more efficient and maintainable for fetching comprehensive student data (with subjects and present days formatted as JSON arrays)?

  1. Using a single query with JOINs and JSON aggregation to structure the data.
  2. Executing multiple SELECT queries to fetch and aggregate the data separately for subjects and present days.
  3. other method

What are the trade-offs of these methods in terms of performance, readability, and scalability?

and please explain why .

6 Comments
2024/12/20
08:42 UTC

126

DBAs: What’s your top priority today?

23 Comments
2024/12/20
06:45 UTC

6

Can anyone please help me, unable to save queries on navicat

Whenever I try to save a query on navicat this error pops up, sayin error creating directory. Any solutions would be welcome. Thanks.

2 Comments
2024/12/20
06:00 UTC

3

Ajuda no Mysql

Boa tarde,

Sou novato no mysql e estou tentando resolver um problema.

Tenho uma tabela "ipca" com três colunas:

mes_ref - no formato aaaa-mm que é o mês de referência

taxa_mes - float que é o ipca do mês

taxa_acum - float que é a multiplicação de todas as taxa_mes cujo mes_ref seja maior ou igual ao mês em questão.

É aí que empaquei. Se alguém puder ajudar agradeço desde já.

1 Comment
2024/12/19
20:36 UTC

135

Can tunnel visioning on SQL lead to a career?

I've been learning SQL for the past 2 months or so and I'm in love. For context, I'm nearing the end of my undergrad CS degree so I want to focus on learning as much as I can before the job hunt starts in earnest. There is something about SQL and database systems that really speaks to me and honestly I don't want to work with any other programming languages ever again.

I know SQL is often used with ORMs and languages like python or R, but I'm wondering if it's realistically possible to build a career just from SQL and database management? If so, what kinds of projects and books should I be looking at?

53 Comments
2024/12/19
20:31 UTC

3

MySQL in 2025: Easy Download and Installation Guide for Windows!

Hey everyone! 👋

I just uploaded a video where I walk you through how to download and install MySQL on Windows in 2025

✅ How to get the latest MySQL version
✅ Step-by-step installation with selected components
✅ Setting up a secure password 🔒
✅ Running queries in MySQL Workbench

Watch : https://www.youtube.com/watch?v=nWWNcBK5Kjo

0 Comments
2024/12/19
19:11 UTC

10

Seeking Insights: What Does a Sales Engineer Actually Do?

Hi all,

I’m preparing for an interview for a Sales Engineer Intern position, and I’m curious to hear from those of you who have worked as Sales Engineers. • What does a Sales Engineer actually do on a day-to-day basis? • What are the key responsibilities of the role? • What industries or areas do Sales Engineers primarily work in? • How much technical knowledge is usually required vs. soft skills like communication and persuasion? • Any tips for someone starting out in this career path?

I’d love to hear about your experiences or advice. Thanks in advance!

13 Comments
2024/12/19
18:24 UTC

6

Removal of my WHERE clause causes query to break. Why is this and how do I fix it?

So this query executes perfectly:

Select
Cust_Seller_Name,
(CONCAT(Cust_Invoice_Num,Cust_Manufacturer_Part_Num,CAST(ABS(CAST(OTRANSLATE(Cust_Invoice_UOM_Qty,OTRANSLATE(Cust_Invoice_UOM_Qty,'0123456789',''),'') AS INTEGER)) AS VARCHAR(10)))) AS Inv_MFRPart_UOMQty,

(CONCAT(Cust_Original_Invoice_Num,Cust_Manufacturer_Part_Num,CAST(ABS(CAST(OTRANSLATE(Cust_Invoice_UOM_Qty,OTRANSLATE(Cust_Invoice_UOM_Qty,'0123456789',''),'') AS INTEGER)) AS VARCHAR(10)))) AS OrigInv_MFRPart_UOMQty,

CASE WHEN(Cust_PO_Date = '00000000') THEN(null) ELSE(CAST(Cust_PO_Date AS DATE FORMAT 'YYYYMMDD')) END AS Cust_PO_Date
FROM Seller_Invoice_Raw
WHERE Cust_Seller_Name = 'ABC';

However, when I remove the where clause I get this error:
Failed [2666 : 22007] Invalid date supplied for Seller_Invoice_Raw.Cust_PO_Date.

I want to remove the WHERE clause to bring in all rows but when I remove it, it crashes. I tried to add more logic like this but I get a numeric overflow error now:

CASE 
    WHEN (Cust_PO_Date = '00000000' OR Cust_PO_Date IS NULL OR LENGTH(Cust_PO_Date) <> 8 OR Cust_PO_Date NOT BETWEEN '19000101' AND '99991231') 
THEN(null) 
ELSE(CAST(Cust_PO_Date AS DATE FORMAT 'YYYYMMDD')) 
END AS Cust_PO_Date

Any idea on how to remove the WHERE clause without getting an error? In Teradata btw.

22 Comments
2024/12/19
16:45 UTC

1

Beginner Question about JOIN

Hello,

If i have 2 tables:

Table A ○Item_ID ○aproval_ID ○approval_Date ○approved_highest_Slot

Table B ○item_ID ○aprroved_against_slot

I need to return the item_ID, approval_Date, and approved_highest_Slot where the approval_ID exists and where the aprroved_against_slot has a certain condition filled.

What kind of Join would let me check the conditions? My gut says it would be a left join or a full join but im not sure.

5 Comments
2024/12/19
16:19 UTC

2

Potential Stored Procedure

I'm currently working on a project using T-SQL and I'm trying to understand if something is possible, and if maybe I just don't have the right function/words to get what I need moving. Some background on what I'm working on: it's a company software, and all I really know is that it speaks in T-SQL. I'm trying to keep things contained since it's not my own personal database, and I don't like to leave random little things laying around in case someone after me finds it and messes up a report down the line.

What I'm hoping to achieve is to have a named function that I can call back to within a query (hence the title of this post). This would be used to reduce bloat and prevent confusion in the query, since that function would have to happen multiple times.

Stored Procedure sounds right, but all the tutorials and posts I find on it makes it sound like I'm writing a brand new query, and would end up with two queries when I'm trying to keep everything on the same query.

Variables like Declare also feel close to what I'm looking for, but again- tutorials and posts aren't very clear on what I need to do.

Here's the idea of what I'm trying to do:

function = u/testcase
  (RIGHT(   
    (case 
      WHEN db.test = 'beep' THEN 'boop 00'
      ELSE db.test
    END),2)
  )
 
 SELECT
    db.frog,
    db.ribbit,
    CASE
      WHEN ((db.quantity - @testcase) BETWEEN 0 AND 10) THEN '10'
      WHEN ((db.quantity - @testcase) BETWEEN 11 AND 20) THEN '20'
      WHEN ((db.quantity - @testcase) BETWEEN 21 AND 30) THEN '30'
      WHEN ((db.quantity - @testcase) BETWEEN 31 AND 40) THEN '40'
      WHEN ((db.quantity - @testcase) BETWEEN 41 AND 50) THEN '50'
      ELSE '0'
    END AS frog_score

FROM database_v_amphibean

Essentially, as-is that whole procedure under @.testcase is being used on nearly 10 lines in my live query.

Edit- format messed up a little in my example code.

5 Comments
2024/12/19
14:27 UTC

12

Getting data access SQL

So I’ve been working 2 months for this company in sales analytics and the IT guy is reluctant to give me access to SSMS. He has allowed me to get to data tables through Excel query, but I find this very slow and cumbersome. He is the programmer of the ERP system we use (it’s at least 25 years old) and I am trying to figure out if he does not know or does not want me to have access, or he doesn’t know how to.

I have the database name “bacon” and the schema “snr” that get me to the data using my password. In SSMS, would I be able to access with the same credentials? What would be the server type and authentication in SSMS?

TIA

46 Comments
2024/12/19
13:36 UTC

13

Ideas for Standout Data Analyst Projects for My Resume?

Hi everyone!

I’ve done many projects like creating visualizations in Tableau and performing analysis using SQL and Python. While these are great for showcasing on LinkedIn, I feel they might not stand out enough on my resume.

I’m looking for ideas for data analysis projects that could really make an impression on potential employers. What kinds of projects would you suggest that go beyond the basics and demonstrate real value?

Thanks in advance for your suggestions! 😊

4 Comments
2024/12/19
13:16 UTC

Back To Top