Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I created a index called `abc` on a table called `table` with a `PRIMARY KEY` called `id` and three others `INT` columns `a`, `b` and `c` that can be `NULL`. Now I need this index to be UNIQUE, so I tried : ``` ALTER TABLE table DROP INDEX abc, ADD UNIQUE abc (a, b, c); ``` But I have duplicates, so MySQL answers : ...
No need to eliminate duplicates first, just use the [`IGNORE` option for `ALTER TABLE`](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html) to do exactly what you want; ``` ALTER IGNORE TABLE table DROP INDEX abc, ADD UNIQUE abc (a, b, c); ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!2/3a98f/1). > If ...
``` SELECT a,b,c FROM table GROUP BY a,b,c HAVING count(*)>1 ```
Find duplicates on multiple columns in a SQL table in order to create UNIQUE index
[ "", "mysql", "sql", "indexing", "duplicates", "" ]
The background of this question is that I have a column with the following definition: ``` FirstName VARCHAR(100). ``` I can insert a THAI/Chinese/European value if I change the column datatype to NVARCHAR and when inserting a value I need to Prefix it with N, as ``` Insert into table ([FirstName]) value(N'THAI/Chin...
> Is there a way I can make a change at the database level where I can accommodate this change. I don't believe there is any way to force SQL Server to handle all varchars as unicode nvarchars. They are simply different datatypes. If you are using literals in your SQL code, you will have to use `N''`. Any columns, pa...
While I agree with @TimLehner that I do not know of a way to force SQL Server to handle all `varchar` columns as `nvarchar` columns, there are a few things that could make *your transition* to Unicode strings in the column easier: 1. To support Unicode values in the column one-off or in an upgrade script, use `ALTER T...
Inserting Unicode string without prefix ' N....'
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Hello i am using Microsoft SQL server manager with visual studio and i kinda stuck with Select command i am trying to achive. ``` SELECT ... FROM ... WHERE (t .companyID = @companyId) AND (DATEDIFF(DateInterval.Day, @start, r.date) >= 0) AND (DATEDIFF(DateInterval.Day, @end, r.da...
I'd suggest not doing it this way at all, and instead using an `IF/ELSE` block: ``` IF @Status = 'show all' BEGIN SELECT ... FROM ... WHERE t .companyID = @companyId AND DATEDIFF(DateInterval.Day, @start, r.date) >= 0 AND DATEDIFF(DateInterval.Day, @end, r.date) ...
``` (CASE WHEN @status != 'show all' THEN r.poStatus = @status END) ``` is equivalent to ``` IF @status = 'show all' THEN ;// no additional conditions ELSE // so @status != 'show all' r.poStatus = @status END IF; ``` So you can put it in standard logical condition: ``` AND (@status = 'show all' OR (@status...
SQl select statement - putting Case inside the Where part
[ "", "sql", "case", "" ]
I need to select two fields but with different conditions, I tried this: ``` SELECT (select my_field from my_table where another_field=1) as column_one, (select my_field from my_table where another_field=2) as column_two; ``` but I got this error: `Subquery returns more than 1 row` is there a way to make this work...
In its current form, you can make it work by adding `limit` clause like this: ``` SELECT (select my_field from my_table where another_field=1 limit 1) as column_one, (select my_field from my_table where another_field=2 limit 1) as column_two; ``` However, logically it would not make any sense because `limit` clause ...
it can return more than 1 row so you should use limit 1 ``` SELECT (select my_field from my_table where another_field=1 limit 1) as column_one,(select my_field from my_table where another_field=2 limit 1) as column_two; ``` the query should be like this ``` select t1.my_field as column_one,t2.my_field as column_two...
Select a field twice with different conditions
[ "", "mysql", "sql", "field", "" ]
I have this query that shows how many hours, minutes and seconds a worker has done for a day: ``` SELECT Employee_Number, CAST([DateTime] as Date) as 'DateTime', MIN([DateTime]) as 'MIN', MAX([DateTime]) as 'MAX', [Hours Worked] = CAST((DATEDIFF(HOUR , min([DateTime]), max([DateTime])) % 24 ) AS VARCH...
``` CONVERT(NVARCHAR, MAX([DateTime]) - MIN(DateTime]), 108) AS [Hours Works] ```
use like this ``` [Hours Worked] = CONVERT(VARCHAR(15),CAST((DATEDIFF(HOUR , min([DateTime]),108) ``` or simply ``` [Hours Worked] = CONVERT(VARCHAR(15),min([DateTime]),108) ``` [Here](http://www.sqlusa.com/bestpractices/datetimeconversion/) are the different formats
How to change the string using convert in ms sql?
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am trying to solve this "issue", however still without success. What I'd like to achieve is, create a query that will select all friends of specific actor. Let's say I want to get list of First name, Last name and age of Jason Statham's friends. Below is an image of tables. PS: Are those tables correctly organized ?...
Does this do what you're looking for? ``` SELECT actors.first_name, actors.last_name FROM actors WHERE actors.login IN ( SELECT friendslist.loginf FROM friendslist WHERE friendslist.logina = 'xstad' ) ```
You'll need to include the Actors table twice - once for the focus person (Jason Statham) and once for his friends. ``` SELECT CONCAT(A.first_name," ",A.last_name) AS Actor, CONCAT(B.first_name," ",B.last_name) AS Friend FROM Actors AS A JOIN [Friends List] AS F on A.login=F.loginA JOIN Actors AS B on F.loginB=B.login...
Mysql query for selecting friends
[ "", "mysql", "sql", "database", "select", "foreign-keys", "" ]
We have a log table where user processes log entries (`success`/`failure`/`timeout`) each time they run. For e.g. ``` +----+----------+---------+ | id | username | status | +----+----------+---------+ | 1 | saqib | success | | 2 | mary | timeout | | 3 | scott | timeout | | 4 | saqib | success | | 5 ...
[**SQL Fiddle**](http://sqlfiddle.com/#!2/cddc6/2/0) ``` SELECT DISTINCT m1.username FROM ( SELECT s1.username, s1.ids FROM ( SELECT username, MAX(id) as ids FROM MyTable GROUP BY username ) AS s1 INNER JOIN MyTable AS s2 ON s1.ids = s2.id WHERE s2.status = 'timeout' ) AS m1 INNER JOIN M...
You can retrieve the latest `id` for each `username` and then `JOIN` it with the original table checking if there were entries for each user with `status` `success` and `id` less then maximum. ``` SELECT t.* FROM ( SELECT username , MAX(id) as ind FROM tbl GROUP BY username ) x JOIN tb...
SQL query to compare earlier values in the Table
[ "", "mysql", "sql", "join", "subquery", "" ]
I have rails application and its using mysql. I have a piles table with two columns that I care for. The columns are name\_he\_il and name\_en\_us I don't have a problem doing these ``` select name_he_il from piles; select name_en_us from piles; ``` I need to insert data into the name\_he\_il column into the piles...
Do UPDATE and not INSERT: ``` UPDATE piles SET name_he_il = 'לא מאפיין כלל' WHERE name_en_us = "Extremely Uncharacteristic"; ```
You want to use `UPDATE ... WHERE` INSERT is for creating new records only.
insert statement sql inserting values into a table in mysql with a where clause condition
[ "", "mysql", "sql", "" ]
I am very much a beginner and I completely get what `NOT IN` does, but don't really get `EXISTS` or `NOT EXISTS`. Even more, I don't understand what this does: ``` SELECT TOP 1 1 FROM tblSomeTable ``` What does this query actually do? For reference, I have been working with something like this: ``` SELECT COUNT(E_...
Your first query will get you only top most record (very first record) out of the total rows in result set. So, if your query returns 10 rows .. you will get the first row. Read more about [TOP](http://msdn.microsoft.com/en-us/library/ms189463.aspx) ``` SELECT TOP 1 FROM tblSomeTable ``` In your Second query the part...
The question that I think would actually need answering is whether `EXISTS (SELECT TOP 1 1 FROM MyTable)` is actually necessary. `Top 1 1` is telling the query to pick the constant "1" for any answer. The `Top 1` part is telling it to stop as soon as it finds a match and returns "1". Wouldn't `EXISTS (SELECT TOP 1 F...
NOT IN vs NOT EXISTS and select 1 1?
[ "", "sql", "sql-server", "exists", "not-exists", "" ]
I have a custom crystal report which retrieves invoices from a database. There is a formula in the report that has the following code: ``` V6AttachmentsGetAttachment ({Command.AttachmentID},{?ReportAttachmentChannel} ) ``` From my understanding, the formula has a function called 'V6AttachmentsGetAttachment' which tak...
It could either be a custom function or one contained in a user-function library (UFL). **Custom Function** * Edit a formula (any formula will do) * Assuming that it is a custom function, it will be listed below the Report Custom Functions node: ![enter image description here](https://i.stack.imgur.com/f7vb2.png) *...
This is a custom function created by Viewpoint Construction Software (V6). It is used to connect with Construction Imaging, a document management system, to return images of things like invoices. I believe the custom function is available if you have the Viewpoint client installed.
How do I determine what a Crystal Reports function does?
[ "", "sql", "function", "crystal-reports", "formula", "" ]
I have the following sample data in an Oracle table (`tab1`) and I am trying to convert rows to columns. I know how to use Oracle pivot on one column. But is it possible to apply it to multiple columns? Sample data: ``` Type weight height A 50 10 A 60 12 B 40 8 C 30 15 ``...
As [the documentation shows](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_10002.htm#SQLRF55129), you can have multiple aggregate function clauses. So you can do this: ``` select * from ( select * from tab1 ) pivot ( count(type) as ct, sum(weight) as wt, sum(height) as ht for type in ('A' as A...
The second approach to name the columns is even better and solves more problems. I had a requirement where I wanted to sum up the data returned from PIVOT so having column names I could simply add 2 and get the required result in third one - ``` select a_ct, b_ct, c_ct, a_wt, b_wt, c_wt, a_ht, b_ht, c_ht, a_wt + b_wt ...
Using pivot on multiple columns of an Oracle row
[ "", "sql", "oracle", "oracle11g", "pivot", "" ]
For example, I have a table like this: ``` ---------------------- | id | Name | Parent | ...................... | 1 | Joe | '' | | 2 | Alice| '' | | 3 | Manny| '' | | 4 | kid1 | 1 | | 5 | kid2 | 1 | | 6 | kid3 | 3 | ``` and I want to display it in a hierarchy manner like this: ``` |...
If the `''` in the Parent column mean empty string then ``` SELECT * FROM table1 ORDER BY Concat(Parent, ID) , ID ``` will return a resultset with the order the OP want (if there is only only level of hierarchy)
You didn't mention a database in particular, so allow me to provide a solution using Oracle. In Oracle you can perform START WITH and CONNECTED BY: `select id, Name, Parent from your_table start with parent is null connect by prior id = parent;` Not all database have connected by, such as MySQL, but you can simulate...
SELECT the table in hierarchy manner
[ "", "mysql", "sql", "" ]
i have two database with same number of tables & table structure. I want to copy data from one table into another with where condition. I have tried this below query, Is the below query is correct, ``` INSERT INTO db2.table (SELECT * FROM db1.table t where t.restaurant_id=12); ``` Please help **update**: i am loo...
`v_db` and `f_db` databases are located in same server and it is work for me `INSERT INTO v_db.app_user (SELECT * FROM f_db.app_user AS t WHERE t.user_id = 100003083401232)`
Please try this query ``` select *into destination_database.dbo.destination table from _ source_database.dbo.source table where 1 = 2 ```
copy table data from one db to another with where condition
[ "", "mysql", "sql", "" ]
Suppose I have 2 years of data. From January 2010 to Dec 2011. I want to classify each of the months as periods. So January 2010 will be my 1, February 2010 my 2, and so on until December 2011 my 24 period. I know I could do it something like: ``` select year,mn, case when year=2010 and mn=01 then 1 e...
``` select year, mn, row_number() over (order by year, mn) as period from t ```
A cheap version for this particular case: ``` SELECT year, mn, (year - 2010) * 12 + mn AS period FROM tbl; ``` This would also account for months that may be missing in your data. And it would give you consistent numbers even when only selecting *some* rows.
Classifying months in periods
[ "", "sql", "postgresql", "row-number", "" ]
Probably this will be really easy, but I can't figure out, how to get necessary values from my DB with one query. Just can't figure it out now. I'm going to make this query inside CodeIginiter system. Table 'information' construction: ``` CREATE TABLE information ( planid int(11) NOT NULL, production_nr int(1...
``` select planid, production_nr from information inf1 where not exists (select 1 from information inf2 where inf1.planid = inf2.planid and status < 3) ``` You might consider amending the select clause (first row) according to your needs: * Add distinct (if the table PK includes ...
Try this, ``` SELECT planid , production_nr FROM information WHERE production_nr IN(SELECT production_nr FROM information) AND STATUS >=3 ```
SQL algorithm with three identifiers from one table
[ "", "sql", "database", "algorithm", "codeigniter", "" ]
# Setup Rails' `where` method can take a range in a hash to generate a query that will search for a value that is within the range. For example: ``` User.where(cash_money: 10..1000) #=> SELECT `users`.* FROM `users` WHERE (`users`.`cash_money` BETWEEN 10 AND 1000) ``` This can also be used with timestamps like ```...
# Edit 2 5/9/20 If you are using Ruby 2.6 you can do this with endless ranges and in Ruby 2.7 you can use begin-less ranges. E.g.: ``` # Ruby >= 2.6 User.where(last_deposit: 10.days.ago..) ``` generates ``` SELECT "users".* FROM "users" WHERE "user"."last_deposit" >= '2020-04-29 21:58:39.109419'" ``` and ``` # R...
Did you try this?: ``` User.where(last_deposit: Time.at(0)...10.days.ago) ``` SQL: ``` SELECT `users`.* FROM `users` WHERE (`users`.`last_deposit` >= '1970-01-01 00:00:00' AND `users`.`last_deposit` < '2015-01-10 17:15:19') ```
Rails `where` for time less than queries
[ "", "mysql", "sql", "ruby-on-rails", "date", "arel", "" ]
There seems to be a few blog posts on this topic but the solutions really are not so intuitive. Surely there's a "Canonical" way? I'm using Teradata SQL. How would I select 1. A range of number 2. A date range E.g. ``` SELECT 1:10 AS Nums SELECT 1-1-2010:5-1-2014 AS Dates1 ``` The result would be 10 rows (1 - 10...
The "canonical" way to do this in SQL is using recursive CTEs, which the more recent versions of Teradata support. For your first example: ``` with recursive nums(n) as ( select 1 as n union all select n + 1 from nums where n < 10 ) select * from nums; ``` You can do something simi...
In Teradata you can use the existing sys\_calendar to get those dates: ``` SELECT calendar_date FROM sys_calendar.CALENDAR WHERE calendar_date BETWEEN DATE '2010-01-01' AND DATE '2014-05-01'; ``` Note: `DATE '2010-01-01'` is the only recommended way to write a date in Teradata There's probably another custom calenda...
Selecting a sequence in SQL
[ "", "sql", "teradata", "" ]
Anyone got any idea why this doesn't work. Im at a loss ![enter image description here](https://i.stack.imgur.com/MOqgp.jpg) The following ``` SELECT * FROM tblCustomerDetails WHERE AccountNo='STO00900' ``` Returns nothing however if i run the same query with any othe accoutn number it works. and this account wil...
Try ``` SELECT * FROM tblCustomerDetails WHERE AccountNo LIKE '%STO00900%' ``` As there can be hidden characters.
Try as Notulysses suggested, but I would recommend it a bit differently: ``` SELECT * FROM tblCustomerDetails WHERE LTRIM(RTRIM(AccountNo)) = 'STO00900' ``` The `LIKE` operator will likely match more rows than you need (if te `AccountNo` column is not unique), so I'd go with trimming the whitespaces and then checkin...
SIMPLE SQL Select Where Query
[ "", "sql", "sql-server-2008", "" ]
I have a table of table records, call it "game" It has an id and timestamp. What I need to know is unrelated to the table specifically. In order to know the average number of games played per hour, I need to know : * Total games played for each hour over the date range * Number of hourly periods between the date r...
**EDIT**: The following query gets the days, hours, and # of games, giving an output as below: ``` 29 23 100 29 00 130 30 22 140 30 23 150 ``` Then, the outer query adds up the number of games for each distinct hour and divides by the number of hours, as follows ``` 22 140 23 125 00 130 ``` The modified query is b...
If you need something to GROUP BY, you can truncate the timestamp to the level of hour, as in the following: ``` DECLARE @Date DATETIME SET @Date = GETDATE() SELECT @Date, DATEADD(Hour, DATEDIFF(Hour, 0, @Date), 0) AS RoundedDate ``` If you just need to find the total hours, you can just select the DATEDIFF in hours...
Number of specific one-hour periods between two date/times
[ "", "sql", "date", "" ]
I have voting sites where each site is a row in the table. Now on my web server, I need to load all sites, and check for each site if its been voted (Voted means the site id exists in the other tables's row). So if the site id = 5 and row with `site_id` 5 exists in `callback_votes`, then the query will add that id to ...
You're using `INNER JOIN` which will return rows where there is a matching row in each table, what you need is a `LEFT JOIN`. Using `LEFT JOIN` in simplistic terms means "select all rows from the left table, where there are no matching rows in the right table then return null". Here's how your query may look: ``` SE...
Just use left join insted of inner to adquire all data from sites and null values if not in callback\_votes ``` SELECT sites.*, callback_votes.site_id AS voted FROM sites LEFT JOIN callback_votes ON callback_votes.site_id = sites.id; ```
Join two tables in SQL and return result set which includes null values
[ "", "mysql", "sql", "sql-server", "" ]
I am having an issue with the following PostgreSQL query it takes more than 10 seconds to run is there any way to speed this query up to a rational speed, I am simply looking for the most relevant search terms associated with videos on a very large database. ``` SELECT count(*), videoid FROM term_search where ...
If I have a chance to disconnect users for a night I would: * create a new table with `words` from `term_search`, * create reference to the new table, * drop column `word`, something like this: ``` create table words ( word_id serial primary key, word text); insert into words (word) select distinct word...
Let's start by rephrasing the query to explain what it's really trying to do. The query: ``` SELECT count(*), videoid FROM term_search where word = 'tester' OR word = 'question' OR word = 'one' group by videoid order by count(*) desc limit 1800; ``` seems to mean: "In a table of search ...
Issues optimizing postgres search query
[ "", "sql", "postgresql", "query-optimization", "top-n", "" ]
I had a table like ``` ID UserID rupees time 1 1 200 2014-01-05 --------------------------------- 2 1 500 2014-04-06 ---------------------------------- 3 2 10 2014-05-05 ---------------------------------- 4 2 20 2014-05-06 ---------------------------------- ``` I wa...
Please try using `CTE`: ``` ;With T as( select *, ROW_NUMBER() over(partition by UserId order by [time]) RN from tbl ) select UserID, rupees, [time], (select SUM(rupees) from T b where b.UserID=a.UserID and b.RN<=a.RN) CumulativeSum from T a ``` For records with column value tim...
For SQL Server 2012 or later, you can use `SUM()` with an [`OVER` clause](http://msdn.microsoft.com/en-us/library/ms189461.aspx) that specifies a `ROW` clause: ``` declare @t table (ID int,UserID int,rupees int,[time] date) insert into @t(ID,UserID,rupees,[time]) values (1,1,200,'20140105'), (2,1,500,'20140406'), (3,2...
How to maintain cumulative sum for each User in SQL server
[ "", "sql", "sql-server", "" ]
I need to have a column with data taken from a count() function with a subquery. I am working with a temporary table at the moment and it is created by: ``` CREATE TABLE tempfact1 AS ( SELECT coursesloc.courseID, preferences.appid, campuses.campusid FROM coursesloc, preferences, campuses WHERE coursesloc.c...
I have created one small demo for your question... ``` /*Demo table....*/ create table mtp (rno integer,name varchar(max)) /*Demo Data....*/ insert into mtp values (1,'a') insert into mtp values (1,'b') insert into mtp values (2,'c') insert into mtp values (2,'d') insert into mtp values (2,'e') /* Select Result, use...
You may try by removing the `GROUP BY` clause. It will return multiple rows , i.e. count for each campus\_id.
Update column based on aggregate function with sub query
[ "", "sql", "oracle", "" ]
So, I'm aware this isn't exactly a programming question but I felt it was still appropriate. What is the difference between Oracles proprietary RDBMS, that they license, vs MySQL, an open source DBMS they bought? Performance? Support? Security? Features? Also, I read MySQL isn't SQL complaint, yet it is compatible wi...
MySQL supports SQL, but doesn't support all features of SQL. Most databases implement a part of the SQL standard and a bunch of extra features. If a database implements everything of the standard, then queries following those standards are usable in all those databases (provided the table structure is the same. But bot...
One big difference is that MySQL does not support CHECK constraints, which is an important part of maintaining database integrity. See here for an example that you cannot use under MySQL: <https://stackoverflow.com/a/23877154/8454> Also, please don't think that Oracle and MySQL are your only two choices. PostgreSQL i...
Oracle vs MySQL in context
[ "", "mysql", "sql", "oracle", "" ]
I have a table that contains the field as: `doses_given decimal(9,2)` that I want to multiply against this field: `drug_units_per_dose varchar(255)` So I did something like this: ``` CAST(ppr.drug_units_per_dose as decimal(9,2)) * doses_given dosesGiven, ``` However, looking at the data, I notice some odd charact...
You have a rather nasty problem. You have a field `drug_units_per_dose` that a normal human being would consider to be an integer or floating point number. Clearly, the designers of your database are super-normal people, and they understand a much wider range of options for this concept. I say that partly tongue in ch...
The 1/2 symbol is ascii character 189, so to replace: ``` CAST(REPLACE(ppr.drug_units_per_dose,char(189),'.5') as decimal(9,2)) * doses_given dosesGiven ```
Multiplying a varchar and a decimal field together
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
Here is some dummy data: ``` | ID | CREATED AT | | 367 | 2014-05-28 22:55:36 | | 367 | 2014-05-28 22:57:06 | | 369 | 2014-05-28 23:06:02 | | 369 | 2014-05-28 23:08:05 | | 369 | 2014-05-28 23:18:07 | | 350 | 2014-05-28 23:12:56 | | 261 | 2014-05-28 21:17:11 | | 261 | 2014-05-29 22:27:43 | ``` What I'd like t...
slower option ``` SELECT id, TIME_TO_SEC(TIMEDIFF(MAX(created_at),MIN(created_at))) as seconds_difference FROM table GROUP BY id HAVING seconds_difference > 3600*24 ``` faster option ``` SELECT t1.id, TIME_TO_SEC(TIMEDIFF(t2.created_at, t1.created_at) as seconds_difference FROM table t1 INNER JOIN table t2 ON (t2.id...
This should work: ``` SELECT DISTINCT t1.`ID` FROM `tbl` t1 INNER JOIN `tbl` t2 ON t1.`ID`=t2.`ID` WHERE t2.`CREATED_AT` <= t1.`CREATED_AT` - INTERVAL 24 HOUR; ``` Edit: A better query (won't return a result if its min and max are 24 hours apart but there is something in the middle that is less than 24 hours apart):...
How would you select records from a table based on the difference between 'created' dates with MySQL?
[ "", "mysql", "sql", "" ]
I have two table Parent P and Child C **Parent** ``` Id Name 1 AAA 2 BBB 3 CCC ``` **Child** ``` Id ParId Name Value 11 1 XXX 1 12 1 YYY 7 19 1 ZZZ 9 13 2 XXX 1 14 2 YYY 2 20 1 ZZZ 7 15 3 XXX 1 16 3 YYY 2 18 3 ZZZ 8 ``` I want to fetch the parent...
The rules can be checked in the `HAVING` section of a query with a `CASE` statement. If all the name have to be checked, i.e. if the child don't have all the three names it should not be in the resulset, the check for three rules is static ``` SELECT c.ParId, p.Name FROM Child c INNER JOIN Parent p ON c.ParI...
``` select distinct p.id from parent p join child c on p.id=c.parid where (c.name='XXX' and c.value = 1) or (c.name='YYY' and c.value = 2) or ... ```
SQL Query to fetch parent record based on multiple conditions on child record
[ "", "sql", "database", "oracle", "" ]
How can I Find in MS-SQL table values that is max on 3 columns, plus max on a single column. I know to look at [the three](https://stackoverflow.com/questions/11032805/get-result-with-maximum-values-in-multiple-columns-at-once-in-sql-server) columns to get them, and I know to do a self join to get the single value - b...
This is a little bit complicated, but do-able. Since you mentioned that you have the survey\_id, I included that as a parameter. There are two separate thoughts in what you are trying to do. First, you want the max question\_id for the survey\_id. The other thought is that you want the greatest question number for the ...
You can get both using Windowed Aggregate Functions without additional join: ``` SELECT survey_id, max_question_id, chapter, subchapter, question_number FROM ( SELECT survey_id, chapter, subchapter, question_number, MAX(question_id) OVER (PARTITION BY survey_id) AS max_question_id, R...
Find in SQL table values that is max on 3 columns, plus max on a single column
[ "", "sql", "sql-server", "vb.net", "" ]
This is the 3rd edit. Based on all your feedback I was able to generate the following query with multiple search criteria. Please note that this is an existing system and there budget is an issue so I am trying to do all I can to improve existing queries. The search you see was manually done based on arrays and there ...
Making a major assumption that you are interested in contacts in a specified region OR a specified country OR a specified city, and cleaning your code up a bit:- ``` SELECT SQL_CALC_FOUND_ROWS fname, lname, desig, company, region, state, country, add_uid, contacts.`id` as id FROM contacts INNER JOIN contact_to_categor...
This is the part which giving error in your query ``` INNER JOIN contact_professional_details ON contact_professional_details.contact_id = contacts.id AND ( <-- Here INNER JOIN contact_to_categories ON contact_to_categories.contactid = contacts.id AND ( contact_to_categories.catid = '2' ) ``` change this t...
MySQL multiple JOIN clause with multiple WHERE
[ "", "mysql", "sql", "join", "inner-join", "where-clause", "" ]
**I have:** Two schemes `scheme1` and `scheme2`. **I want** To delete something from `scheme1`. **Problem:** `scheme2` have dependencies on `scheme1` so I can't delete what I want. **Question:** Is there a way to print all dependencies in `scheme2` to `scheme1`? How to do that? **Question2:** It would be perfect if...
Answer for second question, if it's tables that are dependent on "some\_table": ``` select TABLE_NAME from information_schema.REFERENTIAL_CONSTRAINTS where REFERENCED_TABLE_NAME = <some_table> ``` of the other way around: ``` select REFERENCED_TABLE_NAME from information_schema.REFERENTIAL_CONSTRAINTS where TABLE_...
If you by dependency mean foreign key you can check that in: ``` select * from information_schema.REFERENTIAL_CONSTRAINTS; ```
MySQL: get all references to another scheme
[ "", "mysql", "sql", "relational-database", "database-schema", "" ]
I have data following data structure.. ``` _ID _BEGIN _END 7003 99210 99217 7003 10225 10324 7003 111111 ``` I want to look through every \_BEGIN and \_END and return all rows where the input value is between t...
This would be the obvious answer... ``` SELECT * FROM <YOUR_TABLE_NAME> a WHERE @theInput between a._BEGIN and a._END ``` If the data is string (assuming here as we don't know what DB) You could add this. ``` Declare @searchArg VARCHAR(30) = CAST(@theInput as VARCHAR(30)); SELECT * FROM <YOUR_TABLE_NAME> a WHERE @...
*Less than* `<` and *greater than* `>` operators work on xCHAR data types without any syntactical error, but it may go semantically wrong. Look at examples: **1** - `SELECT 'ab' BETWEEN 'aa' AND 'ac' # returns TRUE` **2** - `SELECT '2' BETWEEN '1' AND '10' # returns FALSE` Character `2` as being stored in a xCHAR ty...
Search Through All Between Values SQL
[ "", "sql", "" ]
I would like to double the value of column C in a table. Is there a built-in function to achieve this? Current table ``` A B C X 1 2 3 Y 4 5 6 Z 7 8 9 ``` After running the T-SQL or any query table values should be as below ``` A B C X 1 2 6 Y 4 5 12 Z 7 8 18 ```
1. To **select** the data: ``` SELECT A,B,C*2 as C FROM TableName ``` Result: ``` A B C 1 2 6 4 5 12 7 8 18 ``` See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/be42e/1). 2. If you want to **update** the table: ``` UPDATE TableName SET C=(C * ...
Just multiplying C by 2 (I mean `c*2`) makes any problem here ``` select A, B, C * 2 as c from your_table ``` (OR) If you want, create your own scalar UDF which will return the double value as ``` create function doubleval(@val int) returns int as begin return @val * 2; end ``` Then, in your select use it as ``...
How to multiply column values in SQL Server?
[ "", "sql", "sql-server", "" ]
I have a column named **BillsOfMonth** (nvarchar) in which i have only Month and year values in format Jan-2014, Feb-2014 , Mar-2014 I want to convert it to Date Format and order by Date. i have tried ``` select rid , name , billsofmonth from reports order by CONVERT (datetime, "1-" & billsof...
I found what i am doing wrong. In Sql Server we use single inverted comma (') for constant expression not double inverted comma ("). So, It will be SELECT [rid] ,[name], [billsofmonth] FROM [reports] order by CAST ( ('1-' + billsofmonth) as datetime)
You should use single quotes instead of double quotes, and also use `+` not `&` to concatenate strings: ``` ORDER BY CONVERT(DATETIME, N'1-' + billsofmonth); ``` For what it's worth, there is no need to store this as NVARCHAR, VARCHAR would do just fine as there are no non-ascii characters in the format you are using...
Concatenate Constant value in string in where or Order by clause in sql server?
[ "", "sql", ".net", "sql-server", "database", "" ]
Simplify sample of my database is a table which as ``` CN REG# CAPACITY ---------- ---------- ---------- 0 LUCY02 43000 6 QRT834 5550 3 SYF777 3333 12 PKR768 1234 5 SST005 12000 6 KKK007 10000 ...
Hi you could try this, ``` select * from (select count(tp.reg#) as cn,t.reg#, CAPACITY from truck t join trip tp on t.reg# = tp.reg# group by tp.reg#, CAPACITY, t.reg#) where cn = (select min(cn) from (select count(tp.reg#) as cn,t.reg#, CAPACITY ...
If you want to filter your query based on an aggregate function like "count", simply add this filter in "having" statement: ``` select count(tp.reg#) as cn,t.reg#, CAPACITY from truck t join trip tp on t.reg# = tp.reg# group by tp.reg#, CAPACITY, t.reg# having count(tp.reg#) >= 3 ``` and if you want query records...
How to select only records that have minimum number of occurrence in a table?
[ "", "sql", "oracle", "join", "oracle11g", "" ]
I'm going to implement a bookstore database. I have created the table `book`, `author`, and `publisher`. I'd like to make the following two relationships. ``` Book is written by Author. Book is published by Publisher. ``` In order to implement these relationships, I write some SQL statements like: ``` create table b...
You are getting the `duplicate key error` cause there is already a constraint named `ISBN` present in database per your first `alter` statement to `author` table ``` alter table author add constraint ISBN foreign key (ISBN) references book (ISBN); ``` Try using a different name for the constraint in `Publisher` table...
Your data structure is strange. You should have entity tables for `Books`, `Authors`, and `Publishers`. These would have auto-incremented ids as primary keys and additional information. For instance, books have "titles" and "isbn" numbers. Authors have names. Publishers have names and addresses. Then you want junction...
MySQL: ERROR 1022 (23000): Can't write; duplicate key in table '#sql-2b8_2'
[ "", "mysql", "sql", "" ]
Consider the following ``` -- Get all objects from database A use database_a; select o.objectnumber into #temp from EDDSDBO.objects o group by d.objectnumber; -- #temp holds 0001, 0002 -- Get all objects from database B use database_b; select o.objectnumber, case when o.objectnumer in #temp then 1 else 0 end a...
If objectnumber is unique in each table, then you can just use `LEFT JOIN` with a 3 part object name: ``` SELECT b.objectnumber, Match = CASE WHEN a.objectnumber IS NOT NULL THEN 1 ELSE 0 END FROM database_b.EDDSDBO.objects b LEFT JOIN database_a.EDDSDBO.objects a ON a.objectnumber = b....
Change the second part of your query to ``` use database_b; select o.objectnumber, case when o.objectnumer in (select distinct objectnumber from #temp) then 1 else 0 end as Match from EDDSDBO.objects o group by o.objectnumber; ```
Check if an account# exist in another database
[ "", "sql", "sql-server", "sql-server-2008", "" ]
``` ALTER PROCEDURE [dbo].[SP_GetLatestMmdData] AS DECLARE @vReturnVar VARCHAR(10) ,@vRCount VARCHAR(10) BEGIN SET NOCOUNT ON; SET @vRCount =(SELECT Distinct Shift From [dbo].[tblMMDLogEntry] Where Shift Like 'Night ' And Date=(SELECT MAX(Date) FROM [dbo].[tblMMDLogEntry])) IF(@vRCoun...
Shouldn't it include a "COUNT()" ``` SET @vRCount =(SELECT COUNT(Distinct Shift) From [dbo].[tblMMDLogEntry] Where Shift Like 'Night ' And Date=(SELECT MAX(Date) FROM [dbo].[tblMMDLogEntry])) ```
Put ``` DECLARE @vReturnVar VARCHAR(10) ,@vRCount VARCHAR(10) ``` After the `BEGIN` of the stored procedure
Must Declare the scalar variable error in Stored Procedure
[ "", "sql", "sql-server-2008", "" ]
Just wondering if anyone can spot anything obviously wrong here. I'm getting strange results with a SELECT in MySQL. I can't see anything wrong with the query so I wondered if some data is throwing it out, but the data does look ok.. So I guess my sql has gone a bit wrong! I have 2 tables, CITY and WEATHER: ``` CITY:...
This is your query with an explicit join and more sensible table aliases (table abbreviations rather than arbitrary letters): ``` SELECT c.city_name as CITY, DATE_FORMAT(w.sdate, '%M %Y') as MONTH, ROUND(avg(w.temp)) as AVG_TEMP_C, SUM(w.rain) ...
You are sorting by sdate, which is in the aggregated result table, but not subject of an aggregate function. Therefore mysql takes any sdate value which matches the other conditions (probably the first one?) and sorts by this value.
Strange results of mysql query with GROUP BY and ORDER BY
[ "", "mysql", "sql", "group-by", "sql-order-by", "" ]
How do I get the entire query executed in sqldeveloper, which would give me the time taken for execution? As of now, it just fetches 50-100 rows, and fetches the rest as and when I scrolled down. It must be a fairly simple solution, but googling it didn't help me. It would be great if someone could point me in the ri...
Click in your result grid and press `Ctrl-End`.
You will get every thing discussed here : <https://community.oracle.com/thread/449344>
Fetching the complete results in sqldeveloper
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
What's the difference between `is null` and `<=> NULL` ? ``` mysql> SELECT * FROM param WHERE num is null; +-----+------+ | id | num | +-----+------+ | 8 | NULL | | 225 | NULL | +-----+------+ 2 rows in set (0.00 sec) mysql> SELECT * FROM param WHERE num<>NULL; Empty set (0.00 sec) mysql> SELECT * FROM param WHE...
**NEVER** check for nulls using `foo = null` or `foo <> null` or `foo != null` ``` mysql> SELECT 1 <> NULL; -> NULL ``` **Not even NULL is equal to NULL!** ``` mysql> SELECT NULL = NULL; -> NULL ``` Instead use one of the following operators --- The `<=>` is the [Null-Safe Operator](http://dev.mys...
# Theoretical difference **`<=>` Operator** [`<=>`](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to) is a safe null-comparison operator. That means you may use it and do not worry if you'll compare with `NULL` - it will behave properly. To illustrate, here is a simple query: ``` my...
What's the difference between "is null " AND "<=> NULL"
[ "", "mysql", "sql", "null", "isnull", "" ]
Getting this error with the following query in SQL Server 2012. **An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'.** ``` CREATE FUNCTION [dbo].[GetPMResources](@UserResourceNo nvarchar(250)) RETURNS @Resources TABLE ( ResourceNo nvarchar(250) COLLATE Latin1...
That is invalid syntax. You are mixing relational expressions with scalar operators (`OR`). Specifically you cannot combine `expr IN (select ...) OR (select ...)`. You probably want `expr IN (select ...) OR expr IN (select ...)`. Using union would also work: `expr IN (select... UNION select...)`
*An expression of non-boolean type specified in a context where a condition is expected* I also got this error when I forgot to add ON condition when specifying my join clause.
SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Why is '`null * 0 = null`'? There can not be any other result, why is `null*0` not evaluated to `0`? Is it possible that this has to do with some higher level math which i am unfamiliar with, or would it may be have some implications for the dbms?
`NULL` in SQL represents "unknown". When a math operation is performed with an unknown, you could not possibly get anything known, even when you multiply it by zero. Similar situation happens in math: although multiplying any number by zero yields zero, [multiplying an infinity by zero doesn't](https://math.stackexchan...
It's a sane design choice to maintain `NULL`ness through all manners of operation. Making an exception for multiplication by 0 would raise inconsistencies, e.g. ``` 0 * NULL; # 0 1 * NULL; # NULL .5 * NULL; # HALFNULL? ;-) ```
Why is null * 0 = null in sql when it is not in math or other languages
[ "", "sql", "math", "null", "" ]
I try write a SQL sintax for MS SQL 2000 with a row\_number function... SQL 2000 doesn't support row\_number with OVER, so I tried this code.... WHen I wrote this: ``` SELECT P1.*, (SELECT COUNT(*) FROM Persons P2 WHERE P2.Value<= P1.Value ) AS NewValue FROM Persons P1...
You should shift things around and do your counting directly as a subquery in the `SET` clause: ``` UPDATE P1 SET Value= (SELECT COUNT(*) FROM Persons P2 WHERE P2.Value<= P1.Value) FROM Persons P1 WHERE .... ```
It means that SQL Server is unable to determine how to update the actual data. This error may appear in two cases: 1. You're trying to update a constant field. Example: ``` update T set Title = N'New title goes here' from (select 'Old title' as Title) as T ``` 2. You're trying to update a derive...
ms sql 2000 row_number code
[ "", "sql", "sql-server-2000", "row-number", "" ]
A quick Question. I have a query that brings back 2 columns 'Description' and 'Amount' In the Description we have 3 outcomes. 'Gold - owned', 'Bronze - no land' and 'Silver - identified / offered' I would like the result to show in an order of Gold,Silver,Bronze Order By Asc or Desc does not achieve this. Is there a...
Inside of a `CASE`, you may ascribe a numeric value to each and order those ascending. If you will need to query a large table, consider adding an index on `Description` to improve sorting performance. ``` ORDER BY CASE WHEN Description = 'Gold - owned' THEN 0 WHEN Description = 'Silver - identified / offer...
Try to use [CASE](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case) statement: ``` ORDER BY ( CASE Description WHEN 'Gold - owned' THEN 1 WHEN 'Silver - identified / offered' THEN 2 WHEN 'Bronze - no land' THEN 3 ELSE 0 ...
SQL Custom Order By Clause
[ "", "sql", "sql-order-by", "" ]
This query always returns the same amount of rows but, in a different order, every time. Why does this happen? I have more filters to add but I can't get past this step. ``` BEGIN DECLARE @lastStatus Varchar(10) SELECT [Job].[Job], [Job].[Part_Number], [Job].[Rev], [Job_Operation].[Description], [...
Put the `Order By` on the `Select * From #tmpTbl`, not on the `insert`.
You can do initials on your table and you can remove your bracket for non spaces so you can make your code shorter. ``` SELECT j.Job, ,j.[Part_Number] ,j.Rev ,j_O.Description ,j.Customer_PO ,j.[Customer_PO_LN] ,d.[Promised_Date] ,j_o.[Operation_Service] ,j.[Note...
Query returns a different result every time it is run
[ "", "sql", "sql-server", "t-sql", "sql-order-by", "" ]
I have table called 'loan' with constrain `Loan_Date < Return_Date`. I'm unable to insert null values to Return date. Constaint: `CONSTRAINT LOAN_DATE_CK CHECK (Loan_Date < Return_Date)` My SQL statement: ``` INSERT INTO Loan (Borrower_Id, Copy_Id, Loan_Date ,Return_Date) VALUES ('00001','00001','2014-04-01','2014-0...
Either Removed the constraint or add another criteria in the constraint and OR it such ``` CONSTRAINT LOAN_DATE_CK CHECK (Loan_Date < Return_Date OR Return_Date is null) ``` and do insert like this ``` INSERT INTO Loan (Borrower_Id, Copy_Id, Loan_Date ,Return_Date) VALUES ('00001','00001','2014-04-01','2014-04-10'),...
I'm assuming the Loan\_Date ,Return\_Date fields are of type Date/DateTime - You cannot successfully evaluation a Date data type against a null value (2014-01-01 > or < null) this value will always return false I Would suggest add an ISNULL check condition to return a static date that you can check against ``` CONSTR...
SQL query - Unable to insert values with date check constrain -
[ "", "sql", "sql-server", "datetime", "constraints", "sql-insert", "" ]
Consider the following table: ``` MyValue -------------------- 123 122_DELETED 45670 42425 43_NO_VIEW 4365463_CORRUPT 53 4335_NO_VIEW_ALLOWED ``` I'm trying to get only the numbers returned. In other words: string everything after the first underscore (`_`): ``` select left(MyValue, charindex(('_', MyValue)-1) fro...
try this! ``` select myval,case when myval like '%[_]%' then substring(myval,1,patindex('%[_]%',myval)-1) else myval end from t ``` `##DEMO USING PATINDEX` `##DEMO USING CHARINDEX`
``` select SUBSTRING(MyValue,CHARINDEX('_',MyValue)+1,LEN(MyValue)) from DB.Table ```
Select substring of retrieved value
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Here is a table I created to explain what I want to do: ``` create table #test ( PlaceID int, ItemID int, ItemCount int, Amount dec(11,2) ) ``` I would like to get 3 things: 1. sum by Place 2. sum by Place and Item 3. sum by Place and Non-item The first two are simple: ``` sum(Amount) over (part...
``` select t1.PlaceID, t1.ItemID, t1.ItemCount , t1.Amount as 'AmtMe' , SumPlace.sum as 'AmtPlace' , SumPlace.sum - t1.Amount as 'AmtPlaceNoMe' from #test as t1 join (select PlaceID, sum(Amount) as 'sum' from #test group by PlaceID) as SumPlace on t1.PlaceID = SumPlace.Place...
``` SELECT PlaceID, ItemID, ItemCount, Amount, sum(ItemCount) over (partition BY PlaceID) AS PlaceItemCount, sum(Amount) over (partition BY PlaceID) AS PlaceAmount , sum(Amount) over (partition BY PlaceID, ItemID) AS PlaceItemAmount , sum(Amount) over (partition BY PlaceID) - sum(Amount) o...
Is it possible to filter within a windowing function's partition
[ "", "sql", "t-sql", "" ]
I have a table named `Locations` that has column named `effective_date` with many dates from many years, and I want to retrieve only those that are ***not*** on the first day of the month or the last day of that month.
If your `effective_date` columns is of type `date`, then this SQL query will return all rows with a non-null `effective_date` value that is other than the 1st or last day of the month: ``` select t.effective_date , count(*) from dbo.foo t where 1 = 1 -- just for clarity -- after the 1st day of the month and t.effe...
Here is a [SQL Fiddle Demo](http://sqlfiddle.com/#!6/ae56d/3/0) with the detail below. Generate a table and some sample test data: ``` CREATE TABLE Locations( effective_date DATETIME ) INSERT INTO Locations VALUES('2014-01-01') -- First day so we would expect this NOT to be returned INSERT INTO Locations VALU...
Find dates that are not on the first or last day of the month
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Im quite a beginner at SQL and I've been trying to workout for hours now what the problem is with this : ``` select to_char(date_Created, 'MON DD YYYY') as jours, action, count(ID) from Logs group by action, to_char(date_Created, 'MON DD YYYY') union select distinct to_char(date_Created, 'MON DD YYYY'), action, 0 fr...
How about: ``` select to_char(date_Created, 'MON DD YYYY') as jours, action, count(ID) from Logs group by action, to_char(date_Created, 'MON DD YYYY') union select distinct to_char(date_Created, 'MON DD YYYY') as jours, action, 0 from Logs WHERE to_char(date_Created, 'MON DD YYYY') BETWEEN 'AVR 14 2014' AND 'AVR 15 ...
Your problem is caused because Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.You cannnot USE the 'JOURS' label because the where code is not aware of it yet.
SQL - Invalid Identifier,, but where?
[ "", "sql", "oracle", "union", "" ]
This is my table: ``` CREATE TABLE `tab_adasf` ( `adasf_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `adasf_shopId` int(10) unsigned NOT NULL, `adasf_localId` bigint(20) unsigned NOT NULL, `adasf_shopState` varchar(255) DEFAULT NULL, `adasf_shopCity` varchar(255) DEFAULT NULL, `adasf_shopName` varcha...
As others have said, a query like this that reports on the whole table is inherently time-consuming. That being said, here's a suggestion or two. First, eliminate the `UPPER()` function calls in the `GROUP BY` clause. MySQL's collations are case-insensitive anyhow. Second, instead of `GROUP BY` year, month, day, hour...
To speed up the query, you can create an index on `tab_adasf(adasf_shopId)`. This should help performance a lot if you have many shops. If you need to do a lot of queries of this type, then consider splitting the `adasf_createdAt` column into a date component and a time component. Then you can create an index on `tab_...
MySQL query optimization: how can I speed up this query?
[ "", "mysql", "sql", "query-optimization", "" ]
someone please help me with this query, i have 2 tables **Employee** ``` EmployeeID LanguageID 1 1 1 2 1 3 2 1 2 3 3 1 3 2 4 1 4 2 4 3 ``` **Task** ``` TaskID LanguageID LangaugeRequired 1 1 ...
here is another variant to do this: ``` select t1.taskid, t2.employeeid from ( select a.taskid, count(distinct a.languageid) as lang_cnt from task as a where a.LangaugeRequired=1 group by a.taskid ) as t1 left outer join ( select a.taskid, b.employeeid, count(distinct b.languageid) as lang_cnt ...
Another version using `NOT EXISTS` Retrieve all task-employee combinations where a missing language does not exist ``` SELECT t1.EmployeeId, t2.TaskId FROM ( SELECT DISTINCT EmployeeID FROM Employee ) t1 , ( SELECT DISTINCT TaskID FROM Task ) t2 WHERE NOT EXISTS ( SELECT 1 FROM Task t LEFT ...
SQL Server matching all rows from Table1 with all rows from Table2
[ "", "sql", "sql-server", "database", "" ]
I have this `users` table: ![users](https://i.stack.imgur.com/GnUCa.png) and this `relationships` table: ![enter image description here](https://i.stack.imgur.com/FfqRN.png) So each user is paired with another one in the `relationships` table. Now I want to get a list of `users` which are not in the `relationships...
You need to compare to both values in the `on` statement: ``` SELECT u.id FROM users u LEFT OUTER JOIN relationships r ON u.id = r.user_id or u.id = r.pair_id WHERE r.user_id IS NULL; ``` In general, `or` in an `on` clause can be inefficient. I would recommend replacing this with two `not exists` statements...
This is a special case of: [Select rows which are not present in other table](https://stackoverflow.com/questions/19363481/select-rows-which-are-not-present-in-other-table/19364694#19364694) I suppose this will be simplest and fastest: ``` SELECT u.id FROM users u WHERE NOT EXISTS ( SELECT 1 FROM relatio...
How can I get records from one table which do not exist in a related table?
[ "", "sql", "postgresql", "" ]
A misconfigured manual import imported our entire AD into our help desk user database, creating a bunch of extraneous/duplicate accounts. Of course, no backup to restore from. To facilitate the cleanup, I want to run a query that will find users not currently linked to any current or archived tickets. I have three tab...
Do a left join for each relationship where the right table id is null: ``` select user.* from user left join hd_ticket on user.id = hd_ticket.owner_id left join hd_ticket as hd_ticket2 on user.id = hd_ticket2.submitter_id left join hd_archive_ticket on user.id = hd_archive_ticket.owner_id left join hd_archive_ticket a...
How about something like: ``` SELECT id FROM user WHERE id NOT IN ( SELECT owner_id FROM hd_ticket UNION ALL SELECT submitter_id FROM hd_ticket UNION ALL SELECT owner_id FROM hd_archive_ticket UNION ALL SELECT submitter_id FROM hd_archive_ticket ) ```
Find unique values that do not exist in multiple columns and tables
[ "", "mysql", "sql", "" ]
I am trying to fetch data from remote db by using dblink through function but getting an error `query has no destination for result data`. I am using plpgsql language to do the same. **Function**: ``` CREATE OR REPLACE FUNCTION fun() RETURNS text AS $$ begin select dblink_connect( 'port=5432 dbname=test user=...
The stored procedure won't just return the result of the last SELECT. You need to actually return the value: ``` CREATE OR REPLACE FUNCTION fun() RETURNS text AS $$ BEGIN --- .... RETURN(SELECT dblink_disconnect()); END $$ LANGUAGE plpgsql; ``` You're getting the error because Postgres expects the function to...
Use a **plain SQL function instead of PL/PgSQL**, or use `SELECT INTO` and ordinary `RETURN`.
PostgreSQL: Query has no destination for result data
[ "", "sql", "database", "postgresql", "plpgsql", "" ]
I have following query which is join of two tables as you can see From the result I want to avoid data from one column. From below result set I want to avoid Other row ``` IncidentCategory No_Incident Near Miss 25 Road Events 129 Service Strike 150 Other ...
Try adding ``` where BT.Name <> 'Other' ```
In your query you use GROUP BY so it is better to use HAVING COUNT to boost your query performance. HAVING COUNT(IR.ID)>0 is avoid null row in No\_Incident column. ``` SELECT BT.Name AS IncidentCategory, SUM(IR.ID) AS No_Incident From BBTypes BT LEFT JOIN IncidentReports IR ON BT.ID = IR.BbType AND ...
how to avoid data from one column in SQL Server
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
Failed to find the answer in the specs. So, I wonder: Can I do something like that in hive? ``` insert into table my_table with a as ( select * from ... where ... ), b as ( select * from ... where ... ) select a.a, a.b, a.c, b.a, b.b, b.c fro...
With is available in Hive as of version `0.13.0`. [Usage documented here](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select).
I guess you could always use subqueries: ``` insert into table my_table select a.a, a.b, a.c, b.a, b.b, b.c from ( select * from ... where ... ) a join ( select * from ... where ... ) b on a.a = b.a; ```
Is there sql WITH clause equivalent in hive?
[ "", "sql", "hadoop", "hive", "" ]
I am learning SQL with GalaXQL and can't figure out the following question: > Build a query which returns starids from planets. The starids should be selected so that for each starid (x) in the list: > - there should exist a planet with a starid that's three times x but > - there should not exist a planet with starid ...
Easiest is to start with exists/not exists: ``` SELECT starid FROM planets p1 WHERE EXISTS ( SELECT 1 FROM planets p2 WHERE p2.starid = 3*p1.starid ) AND NOT EXISTS ( SELECT 1 FROM planets p3 WHERE p3.starid = 2*p1.starid ) ``` If you want to express this in terms of union/intersect, let A b...
![nice explanation ](https://i.stack.imgur.com/wAA8T.jpg) for more details check link [this help me](http://www.essentialsql.com/learn-to-use-union-intersect-and-except-clauses/)
SQL - UNION, UNION ALL, INTERSECT, EXCEPT
[ "", "sql", "" ]
I am running a query against **MS SQL Server 2008** and am selecting an accountnumber and the max of the column mydate grouped by accountnumber: ``` select AccountNumber, max(mydate), from #SampleData group by AccountNumber ``` I want to add a column to the result that contains the second highest mydate that i...
Something like this should select the second highest: ``` select AccountNumber, max(mydate), (select max(SD2.mydate) from #SampleData SD2 where SD2.AccountNumber=#SampleData.AccountNumber AND SD2.mydate<max(#SampleData.mydate)) from #SampleData group by AccountNumber ```
You didn't specify your DBMS so this is ANSI SQL: ``` select accountnumber, rn, mydate from ( select accountnumber, mydate, row_number() over (partition by accountnumber order by mydate desc) as rn from #SampleData ) t where rn <= 2; ```
SQL Select MAX and 2nd MAX
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have come across some sql that has an inner join right before a left join. ``` From Table t INNER JOIN vw_User i ON t.UserID = i.UserID LEFT JOIN UserTypeTwo it ON t.UserTypeTwoID = it.UserTypeTwoID ``` Can someone please help me visualize how this works. I can visualize the two joins separately, but sinc...
See the following image, don't have enough rep to embed it. <https://i.stack.imgur.com/1S8fF.png>
What will happens is that you are just appending more columns to `Table T`. Basically what happens is that `Table T` has no relationship to `UserTypeTwo`, but it does to `vw_user`. Then you need some data from `UserTypeTwo` but since `Table T` can't join to `userTypeTwo` you need a table to connect them both, which is ...
SQL - inner join before left join
[ "", "sql", "" ]
I've searched, but I can't find quite what I'm looking for. I have two tables: Table1 ``` | d | text | | 101 | 'description 101' | | 102 | 'description 102' | | 103 | 'description 103' | ``` Table2 ``` | id | d1 | d2 | d3 | d4 | | 01 | 104 | 242 | 102 | 222 | | 02 | 423 | 553 | | | | 03 ...
``` SELECT t1.d, ( SELECT COUNT(*) FROM Table2 s2a WHERE s2a.d1 = t1.d ) AS count_d1, ( SELECT COUNT(*) FROM Table2 s2b WHERE s2b.d2 = t1.d ) AS count_d2, ( SELECT COUNT(*) FROM Table2 s2c WHERE s2c.d3 = t1.d ) AS count_d3, ( SELECT COUNT(*) FROM Table2 s2d WHERE s2d.d4 = t1.d ) AS count_d...
You'll have to split this up into 4 queries (1 for each column) ``` SELECT d, sum(Count_d1), sum(Count_d2), sum(Count_d3), sum(Count_d4) FROM ( SELECT d, count(1) AS Count_d1, null AS Count_d2, null AS Count_d3, null AS Count_d4 FROM Table1 LEFT JOIN Table2 on Table1.d=Table2.d1 UNION ALL SELECT d, null AS Count_d1, c...
Count for one value in multiple columns SQL
[ "", "sql", "count", "subquery", "" ]
I want to count unique BOOKING\_NUMBERS, to display the total next to each STAFF\_ID; I'm using the following statement: ``` SELECT c.Staff_Id , c.(COUNT Booking_Number) AS "Number of Lessons" FROM AM_Lessons c JOIN AM_Staff m ON (c.Staff_Id = m.Staff_Id) ORDER BY c.Staff_Id ``` I am getting the following error, desp...
You have `c.COUNT(Booking_Number)`, but should be using `COUNT(c.Booking_Number)` as you need to count an element, not look at a "count" property of an element. The following statement should solve your problem: ``` SELECT c.Staff_Id, COUNT(c.Booking_Number) AS "Number of Lessons" FROM AM_Lessons c JOIN AM_Staff m O...
In your question you have specified that you are looking for UNIQUE Booking Number. In that case here is the query - ``` SELECT c.Staff_Id, COUNT(DISTINCT c.Booking_Number) AS "Number of Lessons" FROM AM_Lessons c JOIN AM_Staff m ON (c.Staff_Id = m.Staff_Id) GROUP BY c.Staff_ID ORDER BY c.Staff_Id ```
SQL count and join statement
[ "", "sql", "oracle", "" ]
Hi guys I have a pl/sql cursor that takes too long to execute. I want to know how can I make the same process but with better performance and probably better code. I am new to PL/SQL. ``` Declare Cursor Cursor1 is select * from table1 where field1 IS NULL or field2 IS NULL or fi...
It's possible to do the same with one `UPDATE` ``` UPDATE table1 SET field1 = COALESCE(field1, 0) , field2 = COALESCE(field2, 0) , field3 = COALESCE(field3, 0) , field4 = COALESCE(field4, 0) , field5 = COALESCE(field5, 0) , field6 = COALESCE(field6, 0) WHERE field1 IS NULL OR field2 IS NULL OR field3 IS NULL OR f...
Here's another take on this: ``` UPDATE TABLE1 SET FIELD1 = NVL(FIELD1, 0), FIELD2 = NVL(FIELD2, 0), FIELD3 = NVL(FIELD3, 0), FIELD4 = NVL(FIELD4, 0), FIELD5 = NVL(FIELD5, 0), FIELD6 = NVL(FIELD6, 0); ``` Rationale: any query which performs this update is going to do a full table scan ...
How can I make this pl/sql cursor more efficient?
[ "", "sql", "oracle", "plsql", "" ]
I have a SQL query that only consists of sub queries, But I cannot run it I get an SQL error, What is the correct Syntax to run query consisting of sub queries only...? Query: ``` SELECT COUNT(id) AS 'totalNumOfCustomers' FROM customers WHERE customers.isDemo =0 AND customers.isLead=0 AND regTime < '2012-01-01' S...
How about this ``` select (SELECT COUNT(id) FROM customers WHERE customers.isDemo =0 AND customers.isLead=0 AND regTime < '2012-01-01') as totalNumOfCustomers, (SELECT COUNT(id) FROM customers WHERE customers.isDemo =0 AND customers.isLead=0 AND regTime >='2012-01-01' AND regTime < '2012-02-01') as totalNum...
I think you get error, because there is no `;` ant the end of each query. No error message, so just guessing
Run a query consisting of subqueries only
[ "", "sql", "" ]
I'm looking for a way to excluding some records before i the left join executes. My sql statement looks as follows: ``` SELECT * FROM users LEFT JOIN (SELECT * FROM premissions WHERE post_id = 1) AS p ON p.user_id = users.id WHERE p.id IS NULL ``` How can I exclude the records with the id 1 and two in the user tabl...
You could add criteria to your `WHERE` clause: ``` SELECT * FROM users LEFT JOIN ( SELECT * FROM premissions WHERE post_id = 1 ) AS p ON p.user_id = users.id WHERE p.id IS NULL AND users.id NOT IN (1,2) ```
Use a subselect ``` SELECT * FROM (select * from users where id not in(1,2)) u LEFT JOIN (SELECT * FROM premissions WHERE post_id = 1) AS p ON p.user_id = u.id WHERE p.id IS NULL ```
How to excluding some records before left join executes
[ "", "mysql", "sql", "left-join", "" ]
I have multiple computers that have the task of sending out emails found in a table on a common SQL Server. Each computer polls the email table to look for messages it can send by looking at a status flag set to 0. If a computer does a ``` SELECT * FROM tblEmailQueue where StatusFlag=0 ``` if it returns a record it i...
Instead of using two queries which may cause a race condition, you can update the values and output the updated rows at once using the [`OUTPUT` clause](http://msdn.microsoft.com/en-us/library/ms177564.aspx). This will update the rows with statusflag=0 and output all of the updated ones; ``` UPDATE tblEmailQueue SET...
You can perform select and send email in the same transaction. Also you can use `ROWLOCK` hint and don't commit transaction until you send email or set new value for `StatusFlag`. It means that nobody (exept transaction with hint `NOLOCK` or `READ UNCOMMITED` isolation level) can read this row as long as you commit tra...
How to guarantee only one process picks up a processing task
[ "", "sql", "sql-server", "" ]
Hey i am using a query like this: ``` INSERT INTO likes( likes_memory_id, likes_comment_id, likes_owner_id, likes_like ) VALUES ( :likes_memory_id, :likes_comment_id, :likes_owner_id, :likes_like) ``` when ever an user click the like butt...
The simplest is to create a unique index on your columns which you want unique; ``` CREATE UNIQUE INDEX uq_mem_own ON likes( likes_memory_id, likes_owner_id ); ``` ...and insert likes using INSERT IGNORE, which will insert the value if it's not prevented by the index, otherwise just ignore it; ``` INSERT IGNORE INT...
``` INSERT INTO likes( likes_memory_id, likes_comment_id, likes_owner_id, likes_like SELECT * FROM (:likes_memory_id, :likes_comment_id, :likes_owner_id ,:likes_like) tmp WHERE NOT EXISTS ( SELECT * FROM `likes` WHERE `likes_memory_id` = :likes_memory_id...
duplicate rows MySQL
[ "", "mysql", "sql", "" ]
I can get it to work in two seperate queries but not in one. Can someone help me out please? I need the output something like this: ``` +-----------------------------------------------------------------------------------------------------+ | PARENT_AK | PARENT_RK |PARENT_RESOURCE_NAME| C_RESOURCE_NAME | ...
You are trying to UNPIVOT your table, but as far as I know MySQL does not have built-in UNPIVOT functionality. Therefore you will have to resort to what you are doing. Note though you can use a union to make a single request to the server as opposed to two ([SQL Fiddle demo](http://www.sqlfiddle.com/#!2/08e6a/14)): ``...
You can use a UNION statement in MySQL: <http://dev.mysql.com/doc/refman/5.0/en/union.html> ``` SELECT 'CONTAINER' as PARENT_AK, 'LOB' as PARENT_RK, 'SYSTEMROLE' as PARENT_RESOURCE_NAME, SYSTEMROLE as C_RESOURCE_NAME, 'CONTAINER' as C_AK, 'LOB Options' as C_RK FROM CMDB GROUP by C_RESOURCE_NAME UNION SELECT 'CONT...
How to get two queries joined. Subqueries?
[ "", "sql", "sql-server", "sql-server-2008", "join", "union", "" ]
Using SQL and Looking at a list provided by w3schools on Date conversion (<http://www.w3schools.com/sql/func_convert.asp>) it looks like there isn't really away to get Hours/Minutes AND AM/PM without getting a whole bunch of stuff in the front of the time. I'm currently using a 24 hour time in my query ``` CONVERT(VA...
BTW - so this post could have a definitive answer - from @Goat CO ``` SELECT CONVERT(VARCHAR(15),CAST(sa.StartDateTime AS TIME),100 ```
Here's a method that adds a leading 0 and inserts a space before the AM/PM: ``` SELECT STUFF(REPLACE(SUBSTRING(CONVERT(VARCHAR(20),sa.StartDateTime,100),13,7),' ','0'),6,0,' '); ``` or just ``` SELECT STUFF(SUBSTRING(CONVERT(VARCHAR(20),sa.StartDateTime,100),13,7),6,0,' '); ``` if you don't need the leading 0 Note...
Change Time to include Hours/Minutes AND AM/PM
[ "", "sql", "time", "" ]
I have the following query: ``` DECLARE @BeginDateQ1 date = '01-01-2010', @EndDateQ1 date = '12-31-2010' BEGIN SELECT H.Type, H.SN, Sum(H.Hours), H.Date as 'Report Date', H.OName, R.ReceivedDate, R.Confirmed, R.Part AS 'Part Number' FROM Hours H INNER JOIN Repair R ON H.SN = R.SN WHERE (R.Confirm...
IF is a control flow statement, not to be used within a query. ``` IF (somecondition) THEN <sql statements> ELSE <sql statements> END ``` You can do that within a stored procedure. To do conditionals within a query, you need to use CASE... ``` SELECT col1, col2, CASE when col1='x' then 'HIT' else 'MISS' END f...
A case construct might be what you are after. Something like this. ``` , case when R.ReceivedDate BETWEEN @BeginDate1 AND @EndDate1 then count(r.confirmed) else sum(0) end confirmations ``` **Edit Starts Here** Note that this answer only shows the general idea. Since the OP mentioned later that the result is to be ...
SQL: How Do I Correctly Use Keyword 'BETWEEN' and Aggregate Function in IF, THEN, Else SQL Statements
[ "", "sql", "sql-server", "t-sql", "if-statement", "aggregate", "" ]
I want to format my date column in SQL Server like this **Wed, 23** from given date format **4/23/2014**. ![Exactly like this in image below](https://i.stack.imgur.com/ZjGPU.jpg) Is there any way to do this...? SQL Server version is 2008
Try like this ``` SELECT LEFT(DATENAME(dw, GETDATE()), 3) + ' , ' + CAST(Day(GetDate()) AS Varchar(10)) ``` **[Fiddle Demo](http://sqlfiddle.com/#!6/d41d8/18011)** Query would be like this ``` SELECT mydate,LEFT(DATENAME(dw, mydate), 3) + ' , ' + CAST(Day(mydate) AS Varchar(10)) As Date From tbl ``` [**SQL FIDDLE...
Try this! ``` declare @a table(a date) insert into @a values('4/21/2014'),('5/21/2014'),('6/21/2014') select left(DATENAME(dw,a),3)+','+convert(varchar(10),datepart(day,a)) from @a ``` # [DEMO](http://www.sqlfiddle.com/#!6/d41d8/18012)
SQL Server - Change Date Format
[ "", "sql", "sql-server-2008", "date", "datetime-format", "" ]
Hello I'm trying to migrate from MySQL to Oracle. So far so good until I came across this query: ``` INSERT INTO waiting ( dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, dbcolumn, ...
it should be something like this `(case WHEN NVL(max(dbcolumn), '0') = 0 THEN max(dbcolumn1) + 1 when NVL(max(dbcolumn), '0') = 1 then 3 end)` In oracle, the value you intend to match comes after `when`.
Do `NVL(max(dbcolumn),0)` instead of `NVL(max(dbcolumn))` Don't use parenthesis for `CASE` : ``` SELECT case NVL(max(dbcolumn),0) when 0 then max(dbcolumn)+1 when 1 then 3 end, ``` And I'm not sure but use single quote `'` instead of double quote `"`.
Oracle insert into query with 2 select cases
[ "", "mysql", "sql", "oracle", "" ]
I have a table like: ``` product_id | attribute_id | text -------------------------------- 52 | 16 | 1.0 Inch - 2.9 Inches 52 | 15 | Radio 52 | 14 | Simple Phones 134 | 16 | 1.0 Inch - 2.9 Inches 134 | 15 | Wifi 134 | 14 ...
Use `HAVING` clause: ``` select * from product_attribute where text IN('1.0 Inch - 2.9 Inches','Simple Phones') group by product_id having count(product_id)=2 ``` See example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/8d57fd/5). **EDIT:** For getting all records: ``` select * from product_attribute T1 LEFT ...
Here each row is considered as a separate entity, so even though they are having the same product\_id, the 2 matching entries for product\_id 52 would be considered differently. Better to group by the rows on product\_id and then apply the in condition Eg. SELECT id, com\_string from (SELECT id, GROUP\_CONCAT(string S...
Specifying "AND" Condition with more than 1 time for same column in MYSQL
[ "", "mysql", "sql", "" ]
``` UPDATE edw.dbo.load_control SET ROW_COUNT=?, end_time=getdate() WHERE package_name=? AND load_control_id=( SELECT MAX(load_control_id) FROM edw.dbo.load_control ) ``` I'm more concerned about the WHERE clause. Would it just select the max id and return that or would it evaluate the max id with the an...
The specifications in your where clause are not conditional, sql server interprets exactly what you tell it. Everything not equal to your package\_name would be filtered out. Then, everything that has a load\_control\_id not equal to the max would also be filtered out. Sql server has no problem with returning an empty ...
The `UPDATE` statement will update a row that * has a `package_name` that matches the parameter passed in * has `load_control_id` equal to the `max(id)` **without** taking into account that `package_name` (after all, there's **no condition** for `package_name` in that subquery!) Since in your case, there is no row wi...
How would this query be evaluated (nested)
[ "", "sql", "sql-server", "" ]
Need some best-practice wisdom as I'm new to database architecture. This is for a marketplace type app. The main issue I'd like advice on is handling users. What I'd like to achieve is buyer and seller accounts share login/signup functionality and some characteristics, but seller accounts have the ability to sell, rec...
You can represent this kind of relationship using database supertypes and subtypes. For your example, I would split the data model into two groups: *users* and *roles*. A role can be either a buyer or a seller, and a user can have zero or more roles. I would then create the following logical entities to represent the...
Have you heard about **polymorphism** ? You can create a 'mother' class `User` (with [devise](https://github.com/plataformatec/devise) for example) and create two 'children' classes `Buyer` and `Seller` ! Good tutorial [here](http://robots.thoughtbot.com/back-to-basics-polymorphism-and-ruby)
User database design for marketplace-style app
[ "", "sql", "ruby-on-rails", "database", "database-design", "" ]
Here is how my data looks like ``` CompanyName | CompanyCode ----------- ----------- B190 ARBOT B213 INFRA A946 MichalesTest B207 MyCompany Alerf MyCompany lerf SNELSY A857 SNELSY A954 ``` I want to sort the li...
When I face this kind of situation, I generally do this: ``` SELECT [CompanyName] , [CompanyCode] , SortOrder = case when CompanyName is null then 3 when CompanyName = 'MyCompany' then 1 else 2 end FROM [dbo].COND_ORDERBY_TEST ORDER BY 3 ...
I would add a column in the select to solve this problem and then sort using that column ``` SELECT [CompanyName], [CompanyCode], (CASE WHEN COMPANYNAME='MyCompany' THEN 0 ELSE 1 END) AS SortCol FROM [dbo].COND_ORDERBY_TEST ORDER BY SortCol, CompanyName, CompanyCode ```
SQL Query with conditional order by for a specific condition
[ "", "sql", "sql-server", "" ]
I'm Working with Sql Server 2008.There are 3 tables table1,table2,table3 table 1, ``` Id Name group 1 ddd a 2 aaa b 3 sss a ``` table2 Contains: ``` Id Name group 1 fff c 2 gg a 3 saa b ``` table 3, ``` Id group 1 a 2 b 3 c ``` I want to get the Following Result, ``` g...
Try this: ``` SELECT T3.[group], COUNT(T1.[group]) as Count1, COUNT(T2.[group]) as Count2 FROM Table3 T3 LEFT JOIN Table1 T1 on T3.[group]=T1.[group] LEFT JOIN Table2 T2 on T3.[group]=T2.[group] GROUP BY T3.[group] ``` Result: ``` GROUP COUNT1 COUNT2 a 2 2 b 1 1 c ...
You can try like this ``` SELECT group, (SELECT COUNT(*) FROM table1 WHERE group=G.group) AS table1count, (SELECT COUNT(*) FROM table2 WHERE group=G.group) AS table2count FROM table3 G ```
Get Count values from 2 different table
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "sql-server-2008-r2", "" ]
Currently working with a Firebird 1.5 database and attempting to pull the data in the correct format natively with SQL. Consider the following database: ``` ID | Full Name 1 Jon Doe 2 Sarah Lee ``` What I am trying to achieve is a simple split on the full name field (space) within a query. ``` ID | First Name...
For Firebird 1.5, a solution is to find a UDF that either combines both functions, or provides the position (I don't use UDFs, so I am not sure if one already exists). If none is available, you might have to write one. The other solution is to write a stored procedure for this functionality, see for example: [Position...
I also wanted to split a full name string to first and last name and I used the following SQL statements in firebird 2.1 Database: **Patients** is the table name. The **Name** field holds the full name string e.g.: "Jon Doe". The **FIRST\_NAME** field will store the first name and the **LAST\_NAME** field the last nam...
Firebird Database Split String on Field
[ "", "sql", "firebird", "" ]
I feel like this is a common problem, but it seems that none of the answers that I have found on SO or other sites seem to address the issue of a while loop with a counter. Let's say that I am trying to write a stored procedure in SQL that will populate a user's timesheet by inserting a row for each day for the remain...
I saw many examples of populating data. First you create dates from starting to ending dates in cte and then you can insert it into table. One of them is with cte: ``` DECLARE @StartDate DateTime = '2014-06-01' DECLARE @EndDate DateTime = '2014-06-29' ;WITH populateDates (dates) AS ( SELECT @StartDate as dat...
As a general case, you can increment values without using cursors by assigning values and incrementing the variable in the same select, like this: ``` DECLARE @i INT = 0 DECLARE @table TABLE ( ID INT , testfield VARCHAR(5) ) INSERT INTO @table ( testfield ) VALUES ( 'abcd'), ( '...
Avoiding while loops in SQL when a counter is required
[ "", "sql", "sql-server", "loops", "while-loop", "" ]
I have the following regex that checks for a list of valid characters: ``` ^([a-zA-Z0-9+?/:().,' -]){1,35}$ ``` What I now need to do now is search for any existing columns in our DB that invalidates the above regex. I'm using the oracle SQL `REGEXP_LIKE` command. The problem I have is I can't seem to negate the abo...
You can match it against the following regex which uses the `[^...]` negation character class: ``` ([^a-zA-Z0-9+?/:().,' -]) ``` This will match any single character that is not part of the list of characters that are allowed.
Try this: ``` where not regexp_like(col, '^([a-zA-Z0-9+?/:().,'' -]){1,35}$') ``` or ``` where regexp_like(col, '[^a-zA-Z0-9+?/:().,'' -]') ```
Regular Expression to return when invalid character found
[ "", "sql", "regex", "" ]
Environment: Ruby 2.0.0, Rails 4.0.3, Windows 8.1, PostreSQL, Datatable 1.12.2, Will\_Paginate 3.0.5 I’ve successfully implemented the Railscast 340 solution, thanks to help provided here. However, my table has columns that are not native to the displayed table. These columns are polymorphic relationships using has\_m...
I ended up using a bit of a hack to solve this problem. Database gurus may want to look away... The problem is more complex than originally stated. Any non-native column was not sorting correctly, whether or not it was polymorphic. It was sorting by the foreign key, not by the value of the foreign column being display...
``` products = Product.all.joins(:location).order("location.product.readable_loc {sort_direction}") ``` This won't work, as you discovered. The argument to `order` must be SQL snippet, you can't call instance methods, associations, etc. from the model. So you need to use the value of a column, or write custom SQL to ...
How do I sort a “foreign” column using datatable/will_paginate as in Railscast 340?
[ "", "sql", "ruby-on-rails", "postgresql", "sorting", "activerecord", "" ]
I have two tables, `sites` and `callback_votes` where sites holds the available sites to vote on, and `callback_votes` holds the votes that has been done on each site. callback\_votes is structured like this: [![img](https://i.stack.imgur.com/04pEz.png)](https://i.stack.imgur.com/04pEz.png) (source: [gyazo.com](htt...
Get the number of sites that are not in distinct number of sites in callback where ip is user's ip: ``` Select count(*) From sites Where site_id NOT IN (Select DISTINCT site_id From callback_votes Where ip='1.0.0.127') ``` This will return count of sites not yet voted by this ip. If count is 0, then user has voted a...
Check the count is 0 from ``` select Count(*) from Sites where Site_id NOT IN (select Site_id from Votes where votes.user_ip = '127.0.0.1') ``` You can get the list of non voted sites too with the same cost by using ``` select Site_id from Sites where Site_id NOT IN (select Site_id from Votes where votes.user_ip = '...
Selecting if all row ids exists in other table with column check
[ "", "mysql", "sql", "" ]
I am Having table like this: ``` id candid candname status date time location jobcode 1 12 hhhhhhhhhh Introduce 2014-05-21 14:0 NewYork 10JN 3 12 hhhhhhhhhh Reject 2014-05-21 15:0 AM London 10JN 4 12 hhhhhhhhhh Interview 2014-05-21 ...
You can try ``` select status, count(*) from [tablename] where jobcode = 'AQW-06' group by status ``` Edit: You can try use something like this ``` select count(x.candid) numofcandidates, x.statusnum from (select candid, max(case when status = 'Reject' then 3 when status = 'Interview' then ...
Try this: ``` ;with reftable as (select 1 'key', 'Introduce' 'val' union select 2 'key', 'Interview' 'val' union select 3 'key', 'Rejected' 'val' ), cte as (select e.candid, e.[status], row_number() over (partition by e.candid order by r.[key] desc) rn from yourtable e inner join reftable r on e.[status] = r....
Find count from specific table by specific filter sql server
[ "", "sql", "sql-server-2008", "" ]
I have this data: ``` | bid_id | created | auction_id | user_id | bid_credits | bid_credits_free | bid_rating | balance | bidded_price | last_for_user | bid_ip | bid_type | +--------+---------------------+------------+---------+-------------+------------------+------------+---------+--------------+--...
You're looking to SUM them, COUNT is just counting rows. Try this: ``` select user_id, sum(bid_credits), sum(bid_credits_free) from bids_history where auction_id = 9438 and user_id in (62323,76201) group by user_id; ```
use a sum instead of count when grouping.. should work I also reformatted so its easier to read :) ``` SELECT user_id, SUM(bid_credits), SUM(bid_credits_free) FROM bids_history WHERE auction_id = 9438 AND user_id IN (62323,76201) GROUP BY user_id; ``` the reason why you want to use a sum instead of...
MySQL Query select count where in group by
[ "", "mysql", "sql", "" ]
I have a site that posts articles, and certain articles are assigned a location and a profile so only people in that location and relevant profile can see it. I have a query which returns the location and the count of articles assigned to that location ``` SELECT locations.id, locations.location, COUNT( DISTINCT arti...
You can use a `LEFT JOIN` for this purpose, as below. The parentheses were not located properly, which have been corrected below. ``` SELECT locations.id, locations.location, COALESCE(COUNT( DISTINCT article.id), 0) AS Number FROM ar.locations JOIN ar.articleLocation ON articleLocation.locationId = locations.i...
Use Left Join on Article table. That will add NULL into rows where you expect to see 0. And to see 0, just you ISNULL(0,)
SQL to return rows where one column is 0
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I would like to select every row from a table which includes a faulty social security number. In this simple example the social security number has to be exactly 4 numbers long, using the numbers 0-9. The table looks something like this: ``` |SSN |Name |Favorite Food| |1345|Mark |Meatballs | |1458|Connor|Tacos ...
Not sure which database you are using but using the LIKE statement ... ``` select * from Table Where SSN not Like '[0-9][0-9][0-9][0-9]' ``` Check you database help for exact syntax
you can use `Length` function to get char. count.. ``` select * from Table Where LENGTH(SSN)<>4 ``` for ms-sql use `LEN`
SQL - Select everything that does not follow proper format
[ "", "mysql", "sql", "select", "" ]
I have question in SQL (MySQL environment). I have two tables: ``` Airports -------------------- id type city_id 1 2 1 2 3 1 3 4 2 City ---------- id name 1 Paris 2 Lyon ``` I want cities with airports whose type is 2 and 3. I have try: ``` SELECT * FROM city c INNER JOI...
If you need cities where type 1 and 2 airports exist both then try to use this query: ``` SELECT * FROM CITY JOIN ( SELECT CITY_ID FROM Airports WHERE type in (1,2) GROUP BY CITY_ID HAVING COUNT(DISTINCT type) =2 ) as A ON City.ID=a.City_id ```
If you are after the record paris which has two different types(1 and 2), try this: ``` SELECT c.* FROM city c INNER JOIN airports a ON a.city_id = c.id WHERE a.type IN (2,3) HAVING COUNT(DISTINCT a.type)>1 ``` Result: ``` ID NAME 1 Paris ``` See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/57bf...
SQL: Get parent Join child where child type = 1 AND child type = 2
[ "", "mysql", "sql", "join", "" ]
I am aware of what the problem is with my query, but am really struggling to find a solution here. **[SQL Fiddle](http://sqlfiddle.com/#!3/a992e/1)** I guess I'm not even really sure how to ask this. What I'm trying to achieve sum all tracking numbers for a date range grouped by branch, but (and this is the kicker) i...
You can pre-project the overall (non date-range bound, unfiltered) totals in a separate derived table or cte and then join back to it: ``` WITH totals AS ( SELECT demo.Tracking, SUM(demo.NegotiatedRate) as NegotiatedRate from demo group by demo.Tracking ) select demo.Branch, MIN(tota...
As a bit of a simpler answer, you can do something like: ``` SELECT demo.Branch, SUM(demo.NegotiatedRate) AS NegotiatedRate, demo2.BillRate FROM demo JOIN demo2 on demo2.Tracking = demo.Tracking WHERE demo.Tracking IN ( SELECT Tracking ...
T-SQL Group By and Sub Query
[ "", "sql", "sql-server", "t-sql", "group-by", "" ]
I have this PL/SQL piece of code RESTALLSEQUENCENUMBERLIST contains value '2,3,4' which i am converting this into '2','3','4' for the in clause in the third line by the second statement. But my update query is giving me invalid number. Can anybody help with this ``` restAllSequenceNumberInList varchar2(100); SELECT ...
The `in` clause does not take a string argument that represents multiple values. It is as simple as that. If you pass a single string to `in` it behaves the same as `=`. You can do what you want using `like`: ``` UPDATE THIRD_PARTY_LOOKUP SET ADDRESS_ID = firstSequenceNumber WHERE ','||ADDRESS_ID||',' LIKE ...
You cannot pass comma separated list in a variable and assume SQL to treat them as separate values, try this ``` --replace with " not ' SELECT REPLACE '''' || REPLACE( RESTALLSEQUENCENUMBERLIST, ',', '","' ) || '''' into restAllSequenceNumberInList FROM DUAL; --use xml to split them into rows UPDATE THIRD_PARTY_LO...
Variable inclause is not working for the PL/SQL
[ "", "sql", "oracle", "" ]
I'm having trouble creating a table using RODBC's sqlSave (or, more accurately, writing data to the created table). This is different than the existing sqlSave question/answers, as 1. the problems they were experiencing were different, I can create tables whereas they could not and 2. I've already unsuccesfully incor...
After re-reading the RODBC vignette, here's the simple solution that worked: ``` sqlDrop(db, "df", errors = FALSE) sqlSave(db, df) ``` Done. After experimenting with this a lot more for several days, it seems that the problems stemmed from the use of the additional options, particularlly `table =` or, equivalently, ...
After hours of working on this, I was finally able to get sqlSave to work while specifying the table name--deep breathe, where to start. Here is the list of things I did to get this to work: * Open 32-bit ODBC Administrator and create a User DSN and configure it for your specific database. In my case, I am creating a ...
RODBC sqlSave table creation problems
[ "", "sql", "sql-server", "r", "sql-server-2008", "rodbc", "" ]
We have a lot of databases and a lot of tables within those databases. I'm searching for a specific one. I know the name of the table but it wouldn't be easy to search through every database manually. What SQL statement could I used to find the table by name? Btw, we're using Microsoft SQL Server Management Studio. Ma...
Thought I would update with the solution I use now to find a table among many dBs. After some searching around I found this query: ``` /*Finds a table across multiple dBs and returns the dB(s) in which the table was found*/ SELECT DISTINCT DB_NAME(database_id) FROM [sys].[dm_db_index_operational_stats](NULL,NULL,NUL...
You said you did a search which should've led you to this article: <http://blog.sqlauthority.com/2008/04/29/sql-server-find-table-in-every-database-of-sql-server/> If not, follow that. Basically what he creates is a stored procedure which will search for every table name you specify in every database. If you were to...
SQL statement to find a table by its name
[ "", "sql", "sql-server", "database", "find", "tablename", "" ]
I have a requirement to get a start time and end time in the condition where `val = 'Y'` and `col_val < 5`. I have a table named temp\_vvv structure like ``` date_time | val | col_val ------------------------------------------------------------------------- 03/06/2014 08:58:00 Y 4...
You can use `ROW_NUMBER()` analytic function to group the records based on `COL` and `COL_VAL`. Try with the below query, ``` SELECT MIN(date_time) start_date_time, MAX(date_Time) end_date_time FROM( SELECT date_time, val, col_val, CASE WHEN val = 'Y' AND col_val < 5 THEN 1 ELSE 0 END col_val_limit, ...
``` select min(date_time), max(date_time) from ( select date_time, sum(new_group) over (order by date_time) group_ from ( select date_time, val, col_val, case when case when lag(val ) over (order by date_time) = 'Y' and lag(col_val) over (order by...
Grouping data with in time range
[ "", "sql", "oracle", "oracle11g", "oracle10g", "" ]
I have two tables, in the first table the course id is stored and in the second table the course id and different subject areas description are stored as shown below. ``` Table PA_CPNT CPNT_ID( Course ID) Course Title 06201826 AAAA 06201827 BBBB 06201828 CCCC Table PA_CPN...
You can use row\_number to give each subject in a course a number, then show subject #1, #2 and #3. ``` select pa_cpnt.cpnt_id, pa_cpnt.cpnt_desc, min(case when subj.rn = 1 then subj.subj_id end) as subj_id1, min(case when subj.rn = 2 then subj.subj_id end) as subj_id2, min(case when subj.rn = 3 then subj.su...
``` select DISTINCT a.cpnt_id, a.cpnt_desc, b.subj_id as subj_id1, c.subj_id as subj_id2, d.subj_id as subj_id3 from PA_CPNT a left join PA_CPNT_SUBJ b on a.cpnt_id=b.cpnt_id left join PA_CPNT_SUBJ c on a.cpnt_id=c.cpnt_id and b.subj_id < c.subj_id left join PA_CPNT_SU...
How to show spaces in columns which do not have data in oracle
[ "", "sql", "oracle", "" ]
I have a SQL Server 2008 table with data like this: ``` Contract_No Property_No Start_Dte End_Dte 12345 123 01/01/2014 01/31/2014 12345 123 01/15/2014 02/15/2014 12345 123 03/01/2014 03/31/2014 12345 124 01/01/2014 01/31/2014 ``` I cann...
The following query will show all records that have conflicting date ranges with other records ([**SQL Fiddle**](http://sqlfiddle.com/#!6/bae6e/6/0)): ``` WITH x AS ( SELECT *,ROW_NUMBER() OVER (ORDER BY Contract_No, Property_No, Start_Dte) AS r FROM MyTable ) SELECT * FROM x m1 INNER JOIN x m2 ON m2.Contract_No ...
(Edited) The following query will generate a list of contract/property pairs for which there are two or more overlapping periods: ``` SELECT distinct t1.Contract_No, t1.Property_No, t1.Start_Dte, t1.End_Dte from MyTable t1 inner join MyTable t2 on t2.Contract_No = t1.Contract_No and t2.Property_No = t1.Prop...
Check for overlapping date ranges based on a compound key
[ "", "sql", "sql-server", "join", "" ]
I am new to SQL Server, having two select statements - and i am trying to Put UNION to combine the two. But i am getting error message = **A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations**. how do i assign @NEWComments variable ?? ``` DECLARE @NEWComments ...
You can also try with this ``` DECLARE @NEWComments VARCHAR(max); SELECT TOP 2 @NEWComments = @NEWComments + COALESCE(comments,'') FROM [ChildTableComments] where CommentsID = 1234; select @NEWComments AS Comments, cast(Comments1 as varchar(max)) AS com1, cast( Comments2 as varchar(max))...
If you want to merge all child comments into one row, you can do it like this: ``` DECLARE @NEWComments VARCHAR(max); SET @NEWComments = ''; SELECT TOP 2 @NEWComments = @NEWComments + COALESCE(comments,'') FROM [ChildTableComments] where CommentsID = 1234; select cast(Comments1 as varchar(max)) AS com1, ...
Trying to Add two sql statements and getting error with SELECT Statements
[ "", "sql", "sql-server", "sql-server-2005", "select", "" ]
I am using the following schema: ``` CREATE TABLE person ( person_name VARCHAR PRIMARY KEY ); CREATE TABLE pet ( animal_name VARCHAR, person_name VARCHAR REFERENCES person(person_name), PRIMARY KEY (animal_name, person_name) ); ``` I wish to create a table where, for each `person_name`, I get an array with t...
The most simple way of doing this, is to use the [`ARRAY` constructor's sub-query variant](http://www.postgresql.org/docs/current/static/sql-expressions.html#SQL-SYNTAX-ARRAY-CONSTRUCTORS): ``` SELECT person.person_name, ARRAY(SELECT animal_name FROM pet WHERE person.person_name = pet.person_name) AS pets FROM p...
I just wanna add tho this is 6 years old > array[]::varchar[]
Create an empty array in an SQL query using PostgreSQL instead of an array with NULL inside
[ "", "sql", "arrays", "database", "postgresql", "null", "" ]
Lets say i have a Moder `User` that has many `Posts`. So now for example i choose the Users who are male: ``` SELECT "users".* FROM "users" WHERE (gender = 'male') ``` How can i extend my search query and select only the male User who have a Post with a tagging `[sport,holiday]`? If i only had to use `Posts` i woul...
Try `GROUP BY` `GROUP BY users.id` or `DISTINCT`
``` SELECT DISTINCT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "posts"."tag" IN ('sport', 'holiday') AND gender = 'male' ``` Will return unique rows or as the first comment said use a group by ``` SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "user...
Find all male User with specific Posts SQL
[ "", "sql", "postgresql", "" ]
I have an SQL table called messages, it has three columns ``` 1. UserFrom uniqueidentifier 2. UserTo uniqueidentifier 3. Messagen varchar(50) ``` This table is used to store messages sent from one user to another, it stores the `UserId` from the `aspnet_Users` instead of the `username`, now I need to create a view th...
You need to join aspnet\_Users table twice with different alias names: ``` SELECT U1.Username as UserFrom,U2.Username as UserTo, M.Message FROM Messages M JOIN aspnet_Users U1 ON U1.UserId=M.UserFrom JOIN aspnet_Users U2 ON U2.UserId=M.UserTo ``` **Explanation:** Here aspnet\_Users table it joined twice wi...
Just join with the user table twice. ``` SELECT t2.name AS userFrom, t3.name AS userTo, t1.Message FROM messages t1 LEFT JOIN aspnet_Users t2 ON t1.UserFrom = t2.UserId LEFT JOIN aspnet_Users t3 ON t1.UserTo = t3.UserId ```
How to join two columns to the same table
[ "", "mysql", "sql", "sql-server", "" ]
I've got a stored procedure that I'm passing values to from a C# app. What I need to do is filter the data based on a selection from a dropdown in the app. So, I've got something like this: ``` ALTER procedure [dbo].[usp_AllCompletedTasks] @StDate smalldatetime, @EnDate smalldatetime, @xRole int, @xFun...
Since the `ROLE_ID` and `FUNCTION_ID` columns are integers you have to convert them to one of the character types in order to use the `LIKE`operator. I suggest that when the 'Select All' is selected pass the `NULL` 'value' to the desired parameter and rewrite your conditions like this: ``` AND (@MyRole IS NULL OR ROL...
If I follow correctly, you can get what you want by just adding another condition to your `WHERE` clause: ``` WHERE AND Work_Start >= DATEADD(dd,0,DATEDIFF(dd,0,@strDate)) AND Work_End <= DATEADD(dd,1,DATEDIFF(dd,0,@endDate)) AND ((ROLE_ID = @MyRole AND FUNCTION_ID = @MyFunction) OR (@MyRole = ...
Using If/Then/Else in a stored procedure in SQL Server 2008
[ "", "sql", "sql-server-2008", "" ]
I have two table with different appointment dates. Table 1 ``` id start date 1 5/1/14 2 3/2/14 3 4/5/14 4 9/6/14 5 10/7/14 ``` Table 2 ``` id start date 1 4/7/14 1 4/10/14 1 7/11/13 2 2/6/14 2 2/7/14 3 1/1/14 3 1/2/14 3 1/3/14 ``` If i had set date ranges i can count each appointment da...
Try this out: ``` SELECT id, ( SELECT COUNT(*) FROM table2 WHERE id = table1.id AND table2.start_date >= DATEADD(MM,-6,table1.start_date) ) AS table2records FROM table1 ``` The DATEADD subtracts 6 months from the date in table1 and the subq...
I think what you want is a type of join. ``` select t1.id, count(t2.id) as numt2dates from table1 t1 left outer join table2 t2 on t1.id = t2.id and t2.startdate between dateadd(month, -6, t1.startdate) and t1.startdate group by t1.id; ``` The exact syntax for the date arithmetic depends on the datab...
sql count statement with multiple date ranges
[ "", "sql", "sql-server", "" ]