Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can i improve performance of this query? ``` DECLARE @Form nvarchar(200) SET @Form=N'mail' select t1.* from dbo.EDWordForms t1 where t1.CanonicForm in ( SELECT CanonicForm FROM dbo.EDWordForms t2 WHERE t2.WordForm=@Form) ``` Thanks for the answers, problem solved - there were no index on fi...
Thanks for the answers, problem solved - there were no index on field "CanonicForm"
In many databases, an explicit `join` or `exists` is more efficient than `in`. I would try: ``` select t1.* from dbo.EDWordForms t1 where EXISTS (SELECT CanonicForm FROM dbo.EDWordForms t2 WHERE t2.WordForm = @Form AND t1.CanonicForm = t2.CanonicForm ); ``` Indexes can also h...
SQL query "select ...where select..." take too long time
[ "", "sql", "performance", "" ]
I'm a beginner in MySQL and I need to write query to select all rows from event table and count how many users are registered on this event (but I need to split users by gender). My tables: **table event:** ``` id event_name ...and another insignificant column ``` **table user:** ``` id username gender (allowed va...
``` select sum(gender = 'male') male_count, sum(gender = 'female') female_count, count(*) total_count from user_on_event uoe join user u on u.id = uoe.user_id ``` if you want counts for a specific event add ``` where uoe.event_id = :event_id ```
maybe I have got it :) is this query looks OK? what do you think? ``` SELECT *, COUNT(user_on_event.user_id) as total_registred_users_on_event, (SELECT COUNT(user.id) FROM user WHERE user.id = user_on_event.user_id AND user.gender = "male") as men, (SELECT COUNT(user.id) FROM user WHERE user.id = user_on_event.user...
MySQL query - count how many user is registred on event (men&women)
[ "", "mysql", "sql", "" ]
I have a question about the basic syntax of joining with derived tables. Is this teh basic syntax that is used: ``` select * from table1 a inner join (select * from table2) as T1 on 1.ID = T1.ID ``` Will that work?
you're asking about joining two subqueries? try: ``` select * from (select * from table1) t1 inner join (select * from table2) t2 on t1.id = t2.id ```
In your posted query change `on 1.ID = T1.ID` to `on a.ID = T1.ID` and it should work fine but why do you even need that? You can directly join with `table1` and no need of inline/derived table like ``` select * from table1 a inner join table2 T1 on a.ID = T1.ID ```
Inner Joins with Derived Tables
[ "", "sql", "inner-join", "derived-table", "" ]
I have 3 tables from which I need to select and summarize data. ``` Table: IDEA REFERENCE SL 128 SL1 200 SL1 201 SL2 205 SL3 Table: ACCT1 IDEA_REF ACCTS 128 5 128 2 200 3 205 4 Table: ACCT2 IDEA_REF ACCTS 201 3 205 4 205 ...
You hare asking for three separate aggregates, but you're trying to compute them all in a single query. To get your `NO` (count of distinct items) you can do ``` SELECT SL, COUNT(*) AS NO FROM IDEA GROUP BY SL ``` To get your `ACCT1` item you can do: ``` SELECT SL, SUM(ACCTS) AS ACCT1 FROM IDEA ...
You can achieve the result by using UNION ALL ``` SELECT COMB.SL AS SL, COUNT(DISTINCT COMB.REFERENCE) AS NO, sum(T1) as ACCT1, sum(T2) ACCT2 FROM ( SELECT I.*,A1.ACCTS as t1,0 as t2 FROM IDEA I LEFT JOIN ACCT1 A1 ON A1.IDEA_REF=I.REFERENCE UNION ALL ...
Summing and counting across multiple tables in SQL
[ "", "sql", "db2-luw", "" ]
I am having so much trouble trying to work this out. Can somebody help me? I have a table with colA and colB and these as the values for each row: ``` colA ColB 2 1 1 2 ``` When selecting in this table, I want to retrieve just one row since the values are inverted. If 2 implies 1, 1 implies 2, so they are e...
If it is only 2 columns: ``` WITH t(colA, colB) AS ( VALUES (1,2), (2,1) ) SELECT DISTINCT least(colA, colB), greatest(colA, colB) FROM t; ``` **EDIT:** As outlined by Daniel, although this might do the job, this approach is not good for filtering as it'll change the original data.
No indication was made as to which version of the tuple is preferred over the other. I.e., we know that `(1,2)` is equivalent to `(2,1)` and in that case one of the two should be display, but which of the two? In this solution, the assumption is that the variant with the lower `ColA` value is preferred over the reverse...
Eliminate rows with columns with inverted values
[ "", "sql", "database", "postgresql", "" ]
Trying to group by the result bellow: ``` +-------------+------+ | ID | Coln1 | Coln2 | +-------------+------+ | 10 | A | NULL | | 10 | NULL | X | | 15 | B | NULL | | 15 | NULL | Y | | 20 | C | NULL | | 20 | NULL | Z | +--------------+-----+ ``` With the following select: ``` SELECT * F...
An `aggregate function` should help you. Aggregate function will eliminate the `NULL` values.Try this ``` SELECT ID, max(Coln1), max(Coln2) FROM tablename GROUP BY ID ``` Update your query like this.. ``` SELECT ID, Max(Coln1), Max(Coln2) FROM (SELECT DB1.dbo.TABLE1.id AS ID, DB1.db...
You just have to change Max function is used to select highest values & this function is very helful for avoiding for NULL values ``` SELECT ID, max(Coln1), max(Coln2) FROM ID, Coln1, Coln2 GROUP BY ID ```
Group by with null values
[ "", "sql", "sql-server", "" ]
I have a Customers table and an orders table. Not all customers placed an order, so not all customer IDs are on the orders table. I want my result to show ONLY the values from the customer table who did not place an order, so the orderID column should show as null. The following code works: ``` SELECT c.CustomerID, c....
This is the nature of an outer join (in this case a left join). A left join takes your main table (Customers), matches it by the criteria to the joined table (Orders). For each row in Customers that doesn't have a match, unlike an inner join, it doesn't remove the row. Instead, it adds all the fields from Orders but pu...
It is important to pont out that the two queries are *very* different. The first query is: ``` SELECT c.CustomerID, c.CustomerName, o.OrderID FROM Customers c LEFT OUTER JOIN Orders o ON c.CustomerID = o.CustomerID WHERE o.OrderID IS NULL; ``` It returns all customers that have no corresponding orders (or `...
Why does this statement only work with a WHERE?
[ "", "sql", "" ]
I have what I imagine is a somewhat basic SQL question and hoping for some help. I'm using MSSQL. I have two tables : ``` Table A Table B ---------------------------------------------- A.ID |A.Date| B.ID|B.Date|B.Number ``` A.ID is unique; no duplicate rows. B.ID is not uniqu...
I would recommend using a correlated subquery or the apply operator. Here is the method: ``` select a.*, b.* from tablea a outer apply (select top 1 b.* from tableb b where b.id = a.id and b.date <= a.date order by b.date desc ) b; ```
Yeah this is a little tricky but this should do it: ``` with equalvalues as ( select b.* from a inner join b on a.ID=b.ID and a.adate=b.bdate ), latestdates as ( select b.id, MAX(b.bdate) as maxbdate from b where b.bdate<=GETDATE() group by b.ID ) select number from equalvalues union all select b.number from b inner j...
Conditional SQL joins
[ "", "sql", "sql-server", "join", "" ]
I want to update the type of a column in an Oracle table from varchar2(50) to varchar2(200). I 've started doing some impact analysis that this change might have with searching in which packages this field is used, but after looking at few it seems that the field length is not specified anywhere. The only thing that i...
1. You just need to make sure that wherever the `column` is being referred in the `TYPE` declaration, you have mentioned as `column%type` and not hardcoded as `VARCHAR(50)`. 2. See if there are any `type` is explicitly created as `database object` referring this column, if it is hardcoded with the size, then it would f...
> When the only thing that you want to change is the field length of a varchar2 type of one specific column, does this impact any underlying packages that this field might be referenced from This is exactly the scenario that the [`%Type` type](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/type_attribute.htm) a...
Updating column type in Oracle
[ "", "sql", "oracle", "plsql", "" ]
I have a table with records in one column which are just different by how they are written. So how can I find those and save the corresponding id's in a new table? e.g. I have the following records in a column for cities. ``` Id name 1 berlin 2 ber lin 3 ber-lin 4 Berlin 5 Hamburg 6 New York 7 NewYork ``` So my firs...
If removing some characters (' ' and '-' in the example) and lower-casing is enough to identify duplicates: ``` CREATE TABLE tbl_folded AS SELECT lower(translate(name, ' -', '')) AS base_name , array_agg(id) AS ids FROM tbl GROUP BY 1; ``` [SQL Fiddle](http://sqlfiddle.com/#!17/28efe7/1) [`translate()`](http...
This could certainly be optimized but it works : ``` CREATE TABLE test (id INT(9) NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL); INSERT INTO test (id, name) VALUES ('', 'berlin'); INSERT INTO test (id, name) VALUES ('', 'ber lin'); INSERT INTO test (id, name) VALUES ('', 'ber-lin'); INSERT INTO test ...
Which search strategy in SQL (postgres) to use in order to find similar strings
[ "", "sql", "postgresql", "pattern-matching", "" ]
I'm using Oracle SQL Developer I have a patient table with fields name and phonenumber. I want to only display the names of people who have the same number as at least someone else. So the patient table is like this: ``` create table PATIENT( name varchar2(9) primary key, phoneNumber varchar2(15) null ...
Self join should work for you. ``` SELECT a.NAME, a.phoneNumber FROM PATIENT a JOIN PATIENT b ON a.phoneNumber = b.phoneNumber AND a.NAME <> b.NAME ```
I think this will give you the expected answer. ``` select parent_q.NAME, parent_q.phoneNumber from PATIENT parent_q where (select count(sub_q.phoneNumber) from PATIENT sub_q where sub_q.phoneNumber = parent_q.phoneNumber) > 1 ```
references in select statements
[ "", "sql", "oracle", "select", "reference", "subquery", "" ]
I use mysql. My table look like this: ![my table](https://i.stack.imgur.com/ZXhhH.png) Last I try to use this query ``` SELECT * FROM movie GROUP BY `group` HAVING cateogry = 'TV' ``` I want with this query result as: show all but only GROUP BY TV category, where category = 'TV' **I want this Result** ![enter ima...
``` SELECT min(ID) as ID, min(Name), `group`, Category FROM movie GROUP BY `group`, Category ORDER BY ID ```
You seem to want this query: ``` select m.* from movie m join (select `group`, min(id) as minid from movie group by `group` ) g on m.id = g.minid; ```
show all data only group by specific rows : Select * from table group by column having column = 'value'
[ "", "mysql", "sql", "phpmyadmin", "" ]
I have a column which returns ``` a:2:{i:0;s:10:"Properties";i:1;s:14:"Movable Assets";} ``` I would like to return only: ``` Properties, Movable Assets ``` How can I use a select statement to retrieve the values between the " symbols
Use `SUBSTRING_INDEX()`. `SUBSTRING_INDEX()` takes a string argument followed by a delimiter character and the number of parts to return. After you break up the string using the delimiter, that number of parts is returned as a single string. ``` select concat( SUBSTRING_INDEX( SUBSTRING_INDEX( ...
these are serialize values, you can use php, to get your desired results. you can use , [unserialize](http://php.net/manual/en/function.unserialize.php) which will return an array then you can use [implode](http://php.net/manual/en/function.implode.php) to get the comma separated values. [example](http://codepad.org/...
MYSQL SELECT multiple values between "" in Column
[ "", "mysql", "sql", "" ]
I have three tables, libraryitems, copies and loans. A libraryitem *hasMany* copies, and a copy *hasMany* loans. I'm trying to get the *latest* loan entry for a copy only; The query below returns *all* loans for a given copy. ``` SELECT libraryitems.title, copies.id, copies.qruuid, loans.id AS loanid, loans.statu...
in the subquery , getting maximum created time for a loan i.e. latest entry and joining back with loans to get other details. ``` SELECT T.title, T.id, T.qruuid, loans.id AS loanid, loans.status, loans.byname, loans.byemail, loans.createdAt FROM ( SELECT C.id, C.qruuid, L.title, MAX(LN.createdAt) as maxCreat...
A self left join on loans table will give you latest loan of a copy, you may `join` the query to the other tables to fetch the desired output. ``` select * from loans A left outer join loans B on A.copyid = B.copyid and A.createdAt < B.createdAt where B.createdAt is null; ```
mySQL Sub Select needed
[ "", "mysql", "sql", "subquery", "" ]
Is it possible to omit the `WHERE` if a variable is a certain value? The following doesn't work and I am struggling to find an answer; ``` DECLARE @rMonth int, @rYear int, @sID int SET @rMonth = 0; SET @rYear = 0; SET @sID= 0; SELECT TCS.bStatus AS jStatus, TCS.ID, TCS.sID, TCS.insDate, TCS.statusLabel, TCS.cID...
This is common scenario to include a clause conditionally check this out: ``` WHERE (@rMonth = 0 OR MONTH(insDate) = @rMonth) AND (@rYear = 0 OR YEAR(insDate) = @rYear) AND (@sID = 0 OR sID = @sID) ``` In above query and for each clause, right hand side of "OR" is applied only if left hand side is false. Ot...
``` WHERE (@rMonth <= 0) OR (month(insDate) = @rMonth AND year(insDate) = @rYear) ```
If Var is certain Value omit the WHERE
[ "", "sql", "sql-server", "if-statement", "case", "" ]
Few columns in my table looks like ``` Id Code date latest 1 T 2014-10-04 0 2 B 2014-10-19 0 2 B 2014-10-26 0 1 S 2014-10-05 0 1 T 2014-10-06 0 1 T 2014-10-08 1 2 P 2014-10-27 1 ``` I am tracking all changes made by each ID. if there is ...
Works in **Postgres**: ``` SELECT DISTINCT ON (t0.id) t0.id, t0.code FROM tbl t0 LEFT JOIN tbl t1 ON t1.code = t0.code AND t1.id = t0.id AND t1.latest = 1 WHERE t0.latest = 0 AND t1.code IS NULL ORDER BY t0.id, t0.date DESC; ``` I use the combination of a `LEFT JOIN...
I believe you should have a data for the current version and you should create another table where you would store previous revisions, having foreign key to the `Id`. Your `Id` does not fulfill the general expectations for a column with such a name. So, ideally, you would: * create a table `Revisions(Id, myTableId, co...
Comparing different rows in PostgreSQL for each Id
[ "", "sql", "postgresql", "greatest-n-per-group", "amazon-redshift", "" ]
I have a token table ``` id | status ------------ 1 | taken 1 | used 1 | deleted 2 | taken 2 | deleted 3 | taken ``` I need to count how many tokens are used ( in use or used). If a token is taken and deleted without being used then it should not be counted. So sql would be sth like ``` SELEC...
A little bit verbose but efficient and still readable and maintainable: ``` SELECT COUNT(DISTINCT id) FROM dbo.Token t WHERE EXISTS ( SELECT 1 FROM dbo.Token t1 WHERE t.id = t1.id AND t1.status = 'used' ) OR ( EXISTS( SELECT 1 FROM dbo.Token t1 WHERE t.id = t1.id AND t1.status = 'ta...
You need to be able to take into account all three conditions, so a naive approach would be to just compare each three with a case statement: ``` WITH grouped as ( select id from #uses group by id ) select grouped.id, used = CASE WHEN used.id is not null THEN 'YES' WHEN taken.id is not n...
sql Select id that matches combination of column
[ "", "sql", "sql-server", "" ]
I have the following query: ``` SELECT dbo.saleDocumentDetails.ID, dbo.saleDocumentDetails.DocumentID, dbo.saleDocumentDetails.invProductID, dbo.saleDocumentDetails.Qty, dbo.saleDocumentDetails.QtyConfirmed, dbo.saleDocumentDetails.AmountPrice, dbo.saleDocumentDetails.AmountUs...
As mentioned JRLambert, move `SUM()` outside `CASE`, and remove `io1.Code` from `GROUP BY`
Move the `SUM()` in your `CASE` statements outside of the `CASE`: ``` SELECT dbo.saleDocumentDetails.ID, dbo.saleDocumentDetails.DocumentID, dbo.saleDocumentDetails.invProductID, dbo.saleDocumentDetails.Qty, dbo.saleDocumentDetails.QtyConfirmed, dbo.saleDocumentDetails.Amo...
How to use aggregate function?
[ "", "sql", "sql-server", "aggregate-functions", "" ]
I have a query where i need to get values in 4 columns but only if the date is greater than today from a 5th column. I have tried the following but it doesn't seem to be working. ``` Select (case when clientplans.END_DATE < convert(date,getdate(,101) then '') else insplans.Desc_upper as PLAN NAME, (case when clientp...
Perhaps something like this does what you want: ``` Select (case when cp.END_DATE > cast(getdate() as date) then insplans.Desc_upper end) as PLAN_NAME, (case when cp.END_DATE > cast(getdate() as date) then insplans.ID_NO end) as ID_NO, (case when cp.END_DATE > cast(getdate() as date) then insplans.cert_N...
Use this to get the start of today: `DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)` For example: ``` SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) ``` And for yours... ``` Select (case when clientplans.END_DATE > DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) then '') else insplans.Desc_upper as PLAN NAME, (ca...
Obtaining columns values only if date > today
[ "", "sql", "sql-server", "" ]
I have a question for you all. I have 'inherited' a DB at work and I have to create a report from a table using different conditions. Please note I'm no sql expert, I hope what I write makes sense. Trying to simplify, I have a HARDWARE table that contains the following: * **HWTYPE** - *type of hardware* * **HWMODEL**...
You can also get your expected Result using below query. This will use self join on Hardware table as well as reduce the length of query syntex. ``` SELECT H2.HWMODEL AS HW,H1.PHONENUM,H1.USERID FROM HARDWARE H1 INNER JOIN HARDWARE H2 ON H1.USERID = H2.USERID WHERE ISNULL(H1.PHONENUM,'') <> '' AND ISNULL(H2.PH...
I dont know that I understood your question or not But i think you just need to write following query for your O/P ``` SELECT HWTYPE, HWMODEL, USERID FROM HARDWARE GROUP BY USERID ,HWTYPE,HWMODEL ORDER BY HWTYPE ```
Retrieving values from two columns based on different conditions
[ "", "sql", "sql-server", "" ]
The conditional drop table line in the code below doesn't seem to work. It executes without error, but then the next line errors saying the object ID already exists - so it's not actually dropping the table. Any ideas? I'm connecting to an MS SQL Server 2005 database through OLE DB (SQLOLEDB provider) using ADO. ```...
Sql creates tables prefaced with the pound sign in a whole other place than your current working database. So if you want to interrogate schema information of a temp table, then you need to explicitly reference that other database. It might be easier to see if you tweaked your code like this ``` .CommandText = "IF OBJ...
Change your temp table drop query to this ``` CommandText = "IF OBJECT_ID('tempdb.." & TEMPTABLE & "') IS NOT NULL DROP TABLE " & TEMPTABLE ```
Temporary table will not drop
[ "", "sql", "sql-server", "ado", "temp-tables", "drop-table", "" ]
I want to use SQL to get the the 5 "best" rated profiles. The problem is, I do not want the ranking solely based on grades. Say there is a profile with a grade 8.1, but with 5 reviews I want it to be so that a profile with a grade 7.9 and 30 reviews will be ranked higher. How can I accomplish that if the grade is a m...
You could do a similar calculation in the `ORDER BY` clause. I'll keep trying to see if I can get *exactly* what you're going for, but to start, you could weight your sorting something like this. ``` SELECT name,reviews,average FROM profiles WHERE average >= 7 AND reviews >= 50 ORDER BY (average*.7 + reviews*.3...
Hmmm, I'm not sure how you implement your specific rule. Often when faced with this task, I often subtract one standard error from the estimated value of the reviews. This gives a lower bound of the rating with some level of confidence. In general, the more reviews, the more confident, so the lower the standard deviat...
SQL complex sorting by two columns
[ "", "mysql", "sql", "sorting", "" ]
I have a table with `opening_hours` for restaurants: ``` SELECT * FROM opening_hours; +----+---------------+------------+----------+-----+ | id | restaurant_id | start_time | end_time | day | +----+---------------+------------+----------+-----+ | 1 | 1 | 12:00:00 | 18:00:00 | 1 | | 2 | 1 ...
Tested, this one works :) you can keep it simple. **Query:** ``` SELECT * FROM ( SELECT oh.* FROM opening_hours oh ORDER BY restaurant_id, `day` + IF(`day` < $current_day, 7, 0) ) sq GROUP BY restaurant_id; ``` **Explanation:** Note though, that this is a bit hacky. To select a column that ...
This is a tricky one. Best I can come up with is this, which seems to work but I might be missing some edge cases. ``` SELECT sub0.restaurant_id, MIN(sub1.day) FROM ( SELECT restaurant_id, MIN( LEAST(ABS(DAYOFWEEK(CURDATE()) - day), ABS(DAYOFWEEK(CURDATE()) - (day + 7)), ABS(DAYOFWEEK(CURDATE()) - (day - 7)))) AS...
SQL "First relevant day"
[ "", "mysql", "sql", "" ]
I am using the below after select in a SQL query. Some of the results have a space at the start so I believe I would need to use ltrim to display as I'd like them. ``` SUBSTRING(mf_mm.DisplayName,8,15) as 'Name' ``` Could someone tell me the syntax to use `ltrim` in this case?
Try this:- ``` LTRIM(SUBSTRING(mf_mm.DisplayName,8,15)) as 'Name' ```
Just `LTRIM(SUBSTRING(mf_mm.DisplayName,8,15)) as 'Name'` in T-SQL
ltrim a substring
[ "", "sql", "" ]
`id | name | elapsed` `1 James 0` `2 John 60` `3 Kerry 60` `4 Janet 60` `5 Katie 60` Based on the results above , how can I select names where the 'elapsed' value total is less than or equal to 120? For those results, that would involve selecting the names 'James', 'John' and 'Kerry'. If I changed the total ...
This should work: ``` SELECT t1.id, t1.name, t1.elapsed FROM your_table t1 INNER JOIN your_table t2 ON (t1.id >= t2.id) GROUP BY t1.id, t1.name, t1.elapsed HAVING SUM(t2.elapsed) <= 120 ```
Here's something to think about... ``` SELECT * FROM ints; +---+ | i | +---+ | 0 | | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | +---+ SELECT i,@x:=@x+i running FROM ints i,(SELECT @x:=0)var ORDER BY i; +---+----------+ | i | running | +---+----------+ | 0 | 0 | | 1 | 1 | ...
Select rows where total elapsed value is less than or equal to
[ "", "mysql", "sql", "innodb", "" ]
So, here's my query: ``` SELECT '$' + CONVERT(VARCHAR (6), Cast(Avg(TotalPrice) AS NUMERIC (6, 2))) AS 'Average Price', '$' + CONVERT(VARCHAR (6), Cast(Min(TotalPrice) AS NUMERIC (6, 2))) AS 'Minimum Price', '$' + CONVERT(VARCHAR (6), Cast(Max(TotalPrice) AS NUMERIC (6, 2))) AS 'Maxi...
The NUMERIC(6,2) indicates total 6 digits and out of which 2 are decimal places. you have a value like 1234.66 then total characters needed is 7 Get the maximum value and use appropriate varchar size, here you need atleast `varchar(7)`
Try this ``` SELECT '$' + CONVERT(VARCHAR (10), Cast(Avg(TotalPrice) AS NUMERIC (8, 2))) AS 'Average Price', '$' + CONVERT(VARCHAR (10), Cast(Min(TotalPrice) AS NUMERIC (8, 2))) AS 'Minimum Price', '$' + CONVERT(VARCHAR (10), Cast(Max(TotalPrice) AS NUMERIC (8, 2))) AS 'Maximum Price...
Arithmetic overflow error converting numeric to data type varchar
[ "", "sql", "sql-server", "" ]
I've checked other similar questions. about repeating commas, error in commands but cant find any in my error. I've also searched examples of create tables to compare with mine, but fail to find any difference :(. Below is the CREATE table statement: ``` CREATE TABLE DRIVER(L# VARCHAR(15) NOT NULL ...
You can't specify `CANDIDATE KEY` like that in Oracle. The right way is to create a `UNIQUE CONSTRAINT` on your Candidate Key(s). Like so. ### Here's a working SQLFiddle: <http://sqlfiddle.com/#!4/b392d/1> ``` CREATE TABLE DRIVER( L# VARCHAR(15) NOT NULL, DNAME VARCHAR(75) NOT NULL, STATUS VARCHAR(50) ...
ORA-00907 pretty much always indicates a syntax error. It happens when the parser finds a word which is not a key word in a position where it is expecting either a keyword or a right-hand bracket to close the current statement (hence `Missing Right Parenthesis`). Although sometime it can just be that we have an unmatch...
SQL Error: Missing Right Parenthesis in Line 1 ORA-00907
[ "", "sql", "oracle", "sqlplus", "create-table", "" ]
I have a requirement for a report and I would like my sql query to repeat each row twice. Example : ``` **Table 1** Id Name 1 Ab 2 Cd 3 Ef ``` I want to write a query which outputs the following : ``` 1 Ab 1 Ab 2 Cd 2 Cd 3 Ef 3 Ef ``` Is there a way I can do it ?...
You can use a `union all`. A `union` will not work, because it will eliminate duplicates. Another way is a `cross join`: ``` select id, name from table1 t1 cross join (select 1 as n union all select 2) n; ```
You can also use `UNION ALL`, put them under `CTE` (Common Table Expression) and `Order By Id`: ``` WITH CTE AS ( SELECT Id, Name FROM Table_1 UNION ALL SELECT Id, Name FROM Table_1 ) SELECT Id, Name FROM CTE ORDER BY Id; ``` As this will **reorder** them and **stacked them** as duplicates
how to repeat each row twice
[ "", "sql", "sql-server", "sql-server-2008-r2", "sql-server-2012", "" ]
I am trying to write a query which will give output as MONTH, YEAR. When I write : ``` select CAST( tbl.MONTH as varchar(2) ) + ', ' + CAST ( tbl.YEAR as varchar(4) ) as [DATE] from TABLE as tbl ``` I get the output as ``` 1,2014 4,2014 (depending upon the input) ``` But, Now, I want to replace 1 with J...
The `case` needs an `end`: ``` SELECT (case when tbl.MONTH = '1' then 'JAN' + ', ' + CAST(tbl.YEAR as varchar(4) )) end) as [DATE1] from TABLE tbl; ``` If the values are being stored as numbers, then don't put single quotes around the constant value.
You are missing the `end`, which is needed to close the `case` statement: ``` case when tbl.MONTH ='1' then ('JAN' + ', ' + CAST ( tbl.YEAR as varchar(4) )) end as [DATE1] from TABLE as tbl ```
Case Statement in SQL giving error
[ "", "sql", "sql-server", "" ]
In the below query i am select the product with currentstock .Now i want to replace 0 if the currrent stock is null.Pls help me to do this. ``` SELECT p.ProductID, p.ProductName, (SELECT ISNULL( CurrentStock,0.00) FROM Productstatus PS WHERE PS.ProductID =p.ProductID ...
``` SELECT p.ProductID, p.ProductName, ISNULL((SELECT ISNULL( CurrentStock,0.00) FROM Productstatus PS WHERE PS.ProductID =p.ProductID AND PS.LocationID = 1 AND PS.StatusDateTime= '2014-08-27' and PS.productid=p.productid),0) CurrentStock FROM Product P LEFT OUTER ...
you can use ``` Select case when (CurrentStock) is null then 0 else (CurrentStock) end from table ```
To make 0 if the value is null in sql server
[ "", "sql", "sql-server", "" ]
Hopefully an easy MS SQL Question! I have four tables: ``` Portfolio: int portfolioId, string portfolioName 1,'PortFolio 1' Trip: int tripId, int portfolioId, int tripType, int maxPeople, string tripName 1, 1, 1, 20, 'Trip A' 2, 1, 1, 21, ’Trip B' 3, 1, 2, 22, ’Trip C' Person: int personId, int personStatus, string ...
You can write a query as: ``` With CTE1 as ( -- Total number of persons on a trip: select count(T.personId) as CountA , tripId from TripPerson T group by T.tripId ), CTE2 as ( -- Total number of people who are on a trip that have also been on -- at least one other trip with type of '2'. select Count (T2....
one option is you can use sub-queries to get the countA and countB, so the query looks like some thing below: ``` select trip.tripId, trip.tripType, trip.tripName, (select count(personId) from TripPerson where tripId = trip.tripId) as countA, (select count(personId) from TripPerson where tripId IN (trip.tripId, 2)) ...
SQL Server join across multiple tables
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have two sql views in sql-server-2008. Both have columns `ITEM_NO`, `QTY`, and `LOCATION`. view\_1: ``` ----------------------------------- | ITEM_NO | QTY | LOCATION | ----------------------------------- | SN-15 | 0 | SEA | ----------------------------------- | XY-45 | 2 | SFO ...
You can use `UNION`.. ``` SELECT ITEM_NO, QTY, LOCATION from View_1 UNION SELECT ITEM_NO, QTY, LOCATION from View_2 ``` **OR**, if you *don't care about duplicates*, a more efficient way is `UNION ALL` ``` SELECT ITEM_NO, QTY, LOCATION from View_1 UNION ALL SELECT ITEM_NO, QTY, LOCATION from View_2 ``` The `UNION` ...
`UNION` is used to combine the result-set of several `SELECT` statements. ``` SELECT * FROM View_1 UNION SELECT * FROM View_2 ``` [Documentation](http://dev.mysql.com/doc/refman/4.1/en/union.html).
Combining 2 SQL Tables with same Columns
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table with one of its column having comma separated values, ( for example: longitude,latitude,longitude1,latitude1,etc).. Now I need to swap the values like ( latitude,longitude,latitude1,longitude1,etc). As for a trial purpose: I have created a table as follows: ``` CREATE TABLE string_table ( ...
Using only regexp\_replace, ``` with string_table(slno, old_string) as ( select 1, '1,2,3,4,5,6' from dual union all select 2, '1,2,3,4,5' from dual union all select 3, 'a,b,c,d,e,f' from dual union all select 4, 'a,b,c,d,e' from dual ) select slno, old_string, r...
You can use the `connect by` syntax to split your comma-separated lists into their separate elements, and put them back together in a different order, all in plain SQL. The two slightly tricky bits are swapping the pairs over, which can be done by adjusting each position up or down by one depending on whether it's odd ...
swapping comma separated values in oracle
[ "", "sql", "plsql", "oracle11g", "" ]
I am having xml as result for webservice api . i need to parse the result and update to database table. my xml is below . it is a response text. ``` <?xml version="1.0" encoding="utf-8"?> <double>1</double> ``` Sqlserver 2008 Code : ``` declare @xml xml, @rate DECIMAL(10,4) set @xml=REPLACE(@ResponseText ,'en...
``` DECLARE @X XML = '<?xml version="1.0" encoding="utf-8"?> <double xmlns="http://www.webserviceX.NET/">1</double>' SELECT @X.value ('declare namespace x="http://www.webserviceX.NET/"; (/x:double)[1]', 'decimal') ``` Updated to reflect your use of namespace; the general point is that you don't need to do string man...
You need to declare the namespace when querying using the value() Method. Change the first parameter of value() from ``` '(/double)[1]' ``` to ``` 'declare namespace x="http://www.webserviceX.NET/"; (/x:double)[1]' ``` So the full example will look like this ``` declare @xml XML DECLARE @responsetext VARCHAR(900...
how to read this xml in sql server
[ "", "sql", "sql-server-2008", "" ]
I have a `users` table in my database and have three kinds of user roles - manager(admin), expert, and student. I have tried storing their role as column `role` in the `users` table, but my question is what is the best way to store it? For example, should I use numbers - 1 for admin, 2 for expert and 3 for student. O...
You might want to have a separate junction table, eg `user_roles` that will have columns: `id`, `user_id` and `role_id`. This way each user can have multiple roles in the future, even if right now they only have 1. And that `role_id` would point to a role in a new `roles` table, which could have all the data associate...
You could create a separate table showing 2 columns: role\_nbr, role with values like: 1, Admin; 2, Expert; 3, Student Then include role\_nbr in your users table and use numbers, linking it to the role table to lookup the role name. That way, if you ever increase your roles, it's easy to add to the separate table. A g...
Best way to store a one-to-many column in database
[ "", "mysql", "sql", "database", "fieldtype", "" ]
I got a form that works amazingly by itself, but the second I attach it to my navigation form. I start to get prompted for user input since this line `[Forms]![frm_addReceiveReportInformation]![cbo_PurchaseOrderID]` no longer works due to the current form becoming subform in the navigation form which was explained in...
To access a field inside a form, which is attached to a navigation tab, you should use the following structure: ``` [Forms]![YourNavigationTab]![NavigationSubform].[Form]![YourField] ``` Note: tested in MS Access 2013
In order for queries that contain form references to work, the form must be fully loaded. I think the problem you are experiencing is that the query in the Row Source of the Part Code combo is being evaluated before the form is loaded and therefore you are being asked to input the parameter value. You can work around ...
Microsoft Access - Navigation form is causing my query to not work
[ "", "sql", "forms", "ms-access", "ms-access-2010", "" ]
I see a lot of ways to find duplicate records and delete them but I could not find the one I am looking for i.e. to delete them based on certain condition. The first SQL code below taken from another post works very well in locating duplicates. However, I am having problem withe the second part. ``` <cfquery datasour...
You can use the Rank() function to rank the data and delete the rows which are not ranked 1. Oracle equivalent of the Rank() query to select the #4 and #6 data: ``` SELECT * FROM ( SELECT USERNAME, EMAIL, START_DATE, RANK() OVER (PARTITION BY EMAIL ORDER BY START_DATE DESC NULLS LAST, ROWNUM DESC) AS RANK FR...
This is your original query: ``` SELECT a.*, b.totalCount AS Duplicate FROM mytable a INNER JOIN ( SELECT email, COUNT(*) totalCount FROM mytable GROUP BY email HAVING COUNT(*) > 1 ) b ON a.email = b.email ``` All you need to do is add: ``` where a.activeDate is...
Find duplicate emails in MySql and delete certain ones based on conditions
[ "", "mysql", "sql", "coldfusion", "duplicates", "" ]
I have the following query: ``` select ad_st_id_state, count(distinct id_visit) as Visits from sf_visit join vr_users on vi_us_id_user = sus_us_id_user join sf_pdv on vi_pdv_id_pdv = id_pdv join sf_address on pdv_ad_id_address = id_address group by ad_st_id_state order by ad_st_id_state ``` and I also have this one:...
Could you use an outer join to sf\_visit\_file\_time and a case statement in your count? Obviously I don't have your schema locally but something like: ``` select ad_st_id_state, count(distinct id_visit) as Visits, count(distinct case when vft_vi_id_visit is not null then id_visit end) as DoneVisits from sf_vis...
If both queries are fast and work nicely and you just need the results in one table, you can use a union select <http://dev.mysql.com/doc/refman/5.0/en/union.html> ``` select ad_st_id_state, count(distinct id_visit) as Visits, '' as DoneVisits from sf_visit join vr_users on vi_us_id_user = sus_us_id_user join sf_pdv o...
MySQL - Conditional Join for a column
[ "", "mysql", "sql", "join", "optimization", "" ]
How to specify multiple conditions in **SQL** joins? I know `A.key = B.key` is mandatory apart from this, is the below correct for specifying multiple conditions in **SQL**? ``` ON (A.key=B.key and/or cond1 and/or cond2 ...etc) ``` **OR** ``` ON (A.key=B.key where cond1 and/or cond2 ..etc) ```
I think your first option is correct. You can use multiple join conditions like: ON (A.key=B.key and/or cond1 and/or cond2 ...etc). For the second one, WHERE should come after the ON clause(all the joins using JOIN clause). Then, this will filter the data after the JOIN. Just close the bracket before WHERE, then it ...
You can specify as many conditions as you like in the join like: ``` ON A.Key=B.Key AND b.value>100 AND (a.value>b.value OR b.value2 IS NULL) ```
Multiple conditions in SQL joins
[ "", "mysql", "sql", "sql-server", "oracle", "" ]
I have a table called `tbl_procie` which has the following structure: ``` CREATE TABLE `tbl_procie` ( `id` int, `price` varchar(25) ); ``` Data: ``` id price 1 $2.5 2 $5.3 ``` I want to be able to `SUM()` the price however it is currently a `varchar` column also containing currency symbols. I should ...
``` SELECT SUM(REPLACE(price,'$','')) AS cr FROM TABLENAME WHERE Valet_Company = "Demo Company" ```
`SELECT SUM(price) AS [Price Total] FROM tbl_temp` Or if that doesnt remove the $ sign automatically try `SELECT SUM(TRIM(LEADING '$' FROM price)) AS [Price Total] FROM tbl_temp`
How do I convert a varchar price column containing a currency symbol and then sum it?
[ "", "mysql", "sql", "aggregate-functions", "string-conversion", "" ]
How to concatenate the row values after joining Table1 and table2. Table 1: ``` ----- Col1 ------ 1 2 ``` Table 2: ``` ----------------- Col1 Col2 ----------------- 1 A 1 B 1 C 2 D 2 E 2 F ``` Desired Result: ``` ...
Try this: ``` create table #table1( col1 int ) create table #table2( col1 int, col2 char(1), ) insert into #table1 select 1 union all select 2 insert into #table2 select 1, 'A' union all select 1, 'B' union all select 1, 'C' union all select 2, 'D' union all select 2, 'E' union all select 2, 'F' select...
Mysql: ``` SELECT group_concat(table2.col2) FROM table2 JOIN table1 ON table1.col1 = table2.col1 GROUP BY table2.col1 ```
Concatenate the row values after join
[ "", "sql", "sql-server", "" ]
please consider table below (TableName: Sale) ``` ID Customer Year Amount 1 A 2012 1000 2 B 2012 2000 3 A 2012 1500 4 C 2013 1000 5 B 2013 2000 ``` I'm looking for a query which groups the data by `Cus...
try this: ``` SELECT Customer,ISNULL([2012],0)as [2012],ISNULL([2013],0)as [2013] FROM ( SELECT Customer,[Year] as [year], Amount FROM Mytest ) as s PIVOT(SUM(AMOUNT) FOR Year IN ([2012], [2013])) AS PVTTable ``` OUTPUT: ``` Customer 2012 2013 A 2500 0 B 2000 20...
``` select Customer, SUM(case when Year = '2012' then Amount else 0 end) as 'Year2012', SUM(case when Year = '2013' then Amount else 0 end) as 'Year2013' from Sale group by Customer; ``` SQL Fiddle - <http://sqlfiddle.com/#!2/f560b/4>
Vertical and Horizontal Group by in sql
[ "", "sql", "" ]
I have two sets of elements, let's say they are these words: * set 1: "nuclear", "fission", "dirty" and * set 2: "device", "explosive" In my database, I have a text column (`Description`) which contains a sentence or two. I would like to find any records where `Description` contains both an element from set 1 followe...
It is possible, but i do not think it will preform well with millions of rows. I have a solution here that handles about 10 000 rows in 2 sec and 100 000 rows in about 20 sec on our server. It also requires the famous [DelimitedSplit8K](http://www.sqlservercentral.com/articles/Tally+Table/72993/) sql table function fro...
I dont know anything about performance, but this could be done with cross apply and two temporary tables. ``` --initialize word set data DECLARE @set1 TABLE (wordFromSet varchar(n)) DECLARE @set2 TABLE (wordFromSet varchar(n)) INSERT INTO @set1 SELECT 'nuclear' UNION SELECT 'fission' UNION SELECT 'dirty' INSERT INTO ...
SQL Server 2012 T-SQL count number of words between elements of two sets
[ "", "sql", "sql-server", "text", "pattern-matching", "" ]
I have this SQL query so far that finds the percentage based on all kinds of "sex" ``` select ( (select count(*) from hw where DISCHARGE_STATUS = 'B') / count(*) * 100 ) as Percentage from hw ``` Lets say my table is ``` SEX DISCHARGE STATUS 1 A 1 ...
Instead of querying hw twice you can do this in one pass and get the sub counts by using SUM: ``` select count(*) as count_total, sum(discharge_status = 'B') as count_b, sum(sex = 1) as count_sex1, sum(discharge_status = 'B' AND sex = 1) as count_b_sex1 from hw; ``` (An expression that results in TRUE is 1, ...
You can try this for sex type 1 ((select sum(sex) from hw where sex=1)/(select sum(sex) from hw)) \* ((select count(DISCHARGE\_STATUS) from hw where (DISCHARGE\_STATUS)=B)/select count(\*) from hw))
SQL Query and Count
[ "", "mysql", "sql", "math", "count", "" ]
Table `Items` : **ItemCode---Name-------Stock** 111-----------Book---------10 112-----------Bag-----------03 113-----------Pen-----------08 114-----------Pencil--------13 Table `INVOICEITEMS(SoldItems)` : **BillNumber---ItemCode-----UnitValue(Qty)** 1005-----------111------------------3 1005---...
One way to investigate problems with update statements is to convert them to select statements. For your update statement, I come up with the following query: ``` SELECT Items.* ,(SELECT SUM(T.UnitValue) FROM INVOICEITEMS T WHERE T.BillNumber LIKE '1005' AND T.ItemCode LIKE ItemCode) FROM Items WHERE ItemCode IN(SE...
`AND T.ItemCode LIKE ItemCode` line in the SQL is not getting executed as `ItemCode` hasn't been specified in the SQL before the execution of the inner SQL statement. Associate `ItemCode` explicitly with the `ITEMS` table and it would work.
Update table from another table in SQL is giving an unexpected result
[ "", "sql", "sql-server", "t-sql", "sql-update", "" ]
I want to get all values from the left table (ignoring the common values from the right table with the same id) and all values from the right table that don't exist in left table. Table 1: ``` ---------------------- | id | value | ---------------------- | 1 | 50 | ---------------------- | 2 |...
You can use `union all` and a `not exists` clause: ``` select id, value from table1 t1 union all select id, value from table2 t2 where not exists (select 1 from table1 t1 where t1.id = t2.id); ```
``` select * from ( select * from tab1 except select * from tab2 UNION ALL select id, value from tab2 t2 where not exists (select 1 from tab1 t1 where t1.id = t2.id))d order by d.id ; ``` **output** ``` id value 1 50 2 150 3 150 4 100 ```
SQL Query get all values from left table and uncommon values from right table
[ "", "sql", "sql-server", "" ]
I have a table ``` | Location | Unit | ... +----------|------+---- | A | 1 | ... | A | 1 | ... | B | 1 | ... | A | 2 | ... | C | 2 | ... | ... | ... | ... ``` and I want to compute a new table with the 'average' location value for each unit, in the following sen...
You'd use `COUNT OVER` for this: ``` select distinct location, unit, cast(count(*) over (partition by unit, location) as decimal) / cast(count(*) over (partition by unit) as decimal) as weight from mytable order by unit, location; ``` ### [SQLFiddle](http://sqlfiddle.com/#!6/2b26b/5)
You want to do a weighted average, with units as the weight. You need both the sum for each location/unit combination and the total for each `location`. To produce your output: ``` select location, unit, (1.0*unit) / sum(unit) over (partition by location) from table1 group by location, unit; ``` The `1.0*` is just a ...
Adding averages to a table
[ "", "sql", "sql-server", "t-sql", "" ]
I am attempting to get the highest system number from a set of rows. The system number is preceded with `SYS`, thus `select SYSTEM_ID from TABLE` would yield, `{SYS901,SYS87,SYS3024.....}` This is the query I'm attempting to use: `select MAX(REPLACE(SYSTEM_ID,'SYS','')) from TABLE` The possible results are `{901,87...
``` select MAX(TO_NUMBER(REPLACE(SYSTEM_ID,'SYS',''))) from TABLE; ``` Use TO\_NUMBER to convert VARCHAR2 to NUMBER otherwise Oracle compares strings using their ASCII codes ('9' > '3')
Of course it is returning the max. It is just returning the max according to the rules of string comparisons, not numbers. To get the numeric max, do a conversion: ``` select MAX(TO_NUMBER(REPLACE(SYSTEM_ID, 'SYS', ''))) from TABLE ```
Oracle SQL MAX function not returning max on VARCHAR to NUMBER conversion
[ "", "sql", "oracle", "" ]
I have a select (MS SQL) where I'm joining a parent with up to 3 children. I'd like to select all the children if ANY of the children meets a criteria (Type <> 'Done'). Performance is very important. I've tried ``` SELECT p.*,c.* FROM Parent p INNER JOIN Child c ON p.Id=c.ParentId WHERE p.Id IN (SELECT DISTINCT c.Par...
**New Answer:** Well then I would create a temporary table with the queries below and use them instead of your nested subqueries and try which combination is the fastest. Update: ``` DECLARE @tmp TABLE(pid INT); INSERT INTO @tmp(pid) SELECT p.Id FROM Parent p WHERE EXISTS (SELECT 1 FROM Child c WHERE c.ParentId=p.I...
The EXISTS variant should normally be the fastest one. Assuming you do have all the relevent indices, there is really no way to optimize this query, other than preparing your data in temp tables. You could make a denormalized table that combines the parent and child table. This should be a massive performance increase...
Select all children if any one meets criteria
[ "", "sql", "sql-server", "select", "parent-child", "" ]
I'm trying to generate an email from full name. Following is what I have and I'm stuck here ``` select distinct tbin.Name ,(SELECT SUBSTRING(tbin.Name, 1, CHARINDEX(' ', tbin.Name) - 1) AS [FirstName]) ,(select SUBSTRING(tbin.Name, CHARINDEX(' ', tbin.Name) + 1, 8000) AS LastName) from tblInitialApplicants tbin ``` N...
You can get the position of a char with CHARINDEX, look for the first space and reverse de name and look for the last. With that you can easly substring first and last name. ``` DECLARE @Fullname VARCHAR(100) = 'Natalie Marine Baily'; select *, firstname+'.'+lastnameINITIAL+'@gamil.com' from ( select ...
``` DECLARE @name VARCHAR(200) = 'Natalie Marine Baily' SELECT LEFT(@name,CHARINDEX(' ',@name,1)-1) + '.'+ LEFT(REVERSE(LEFT(REVERSE(@name),CHARINDEX(' ',REVERSE(@name),1)-1)),1) + '@gmail.com' ``` Result: ![enter image description here](https://i.stack.imgur.com/frLOH.jpg) Just see, whether you can work f...
Split and merge string
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to solve the following challenge: 1) If a patient visits the ER within 48 hours, I want to flag that as `1`. 2) If the same patient visits the ER again after 48 hours, I want to flag that as `2`. 3) Each subsequent visit must be flagged as `3`, `4`, `5` etcetera after the first 48 hours. Here is what my...
You can achieve this easy using [LAG](http://msdn.microsoft.com/en-us/library/hh231256.aspx), [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794.aspx) and [ROWNUMBER](http://msdn.microsoft.com/en-us/library/ms186734.aspx) functions. The `LAG` function helps you to get the previous `ADMIT_DATE` value. Then you ...
you can use DATEDIFF() available in sql-server like ``` SELECT DATEDIFF(hour,startDate,endDate) AS 'Duration' ``` You can visit <http://msdn.microsoft.com/en-IN/library/ms189794.aspx>
How to find the difference between dates within the same column using SQL?
[ "", "sql", "sql-server", "t-sql", "" ]
Ok so i have some specific query i need to do. I have a table "description", and i need to find if there is a picture linked to that description, for that, i made a left join, with the table "files". ``` SELECT D.id, COUNT(*) as haspicture FROM `description`as D LEFT JOIN `files` as F ON D.id=F.id GROUP BY D.id ``...
You can use a `case` statement. Also, because careful what you are counting: ``` SELECT D.id, (CASE WHEN COUNT(f.id) > 0 THEN 1 ELSE 0 END) as haspicture FROM `description`D LEFT JOIN `files` F ON D.id = F.id GROUP BY D.id; ``` You might find that the following performs better, because there is no...
`SELECT IF(COUNT('*') > 0, 1, 0)) as haspicture`
SQL, left join, group by, count(*) as haspicture?
[ "", "mysql", "sql", "count", "group-by", "left-join", "" ]
I have two statements that I want to merge into one output. Statement One: ``` select name from auxiliary_variable_inquiry where inquiry_idbr_code = '063' ``` Returns the following list of names: ``` Name ------------ Affiliates NetBookValue Parents Worldbase ``` Statement Two: ``` select name, value from auxilia...
I'd recommend a self-JOIN using the LEFT OUTER JOIN syntax. Include your 'extra' conditions from the second query in the JOIN condition, while the first conditions stay in the WHERE, like this: ``` select a.name, CASE WHEN b.Value IS NULL THEN 0 ELSE b.Value END AS Value from auxiliary_variable_inquir...
You can do a left join. This ensures that all records from the first table will stay included. Where value is null, no child record was found, and we use coalesce to display 0 in these cases. ``` select i.name, COALESCE(v.Value,0) from auxiliary_variable_inquiry i left join auxiliary_variable_value v on v.inquiry_idbr...
SQL Join / Union
[ "", "sql", "join", "ingres", "" ]
I have a table which looks like this ![enter image description here](https://i.stack.imgur.com/H1BSS.png) For each assessment code I would like to create a query which returns the percentage of marks in certain mark ranges... For example ``` FileYear AssessmentCode MarkRange MarkPercentage 2014 11c...
You can do this calculating the `SUM` of each range and then the percentage of this `SUM` from the whole `SUM`. This is full working example: ``` SET NOCOUNT ON GO DECLARE @DataSource TABLE ( [FileYear] CHAR(4) ,[AssessmentCode] CHAR(8) ,[StudentID] INT ,[Mark] TINYINT ) ...
This not the exact answer but this should help you i am not sure how u got that percentage. so i have commented that part u can tweak a bit bit get the percentage. ``` CREATE TABLE #test ( FileYear INT, AssessmentCode VARCHAR(50), StudentID INT, Mark INT ) INSERT INTO #tes...
Percentage of marks in various mark ranges
[ "", "sql", "t-sql", "percentage", "" ]
I have the following table and some sample records in it: ``` id | attr1_id | attr2_id | user_id | rating_id | override_comment ------+----------+----------+-------------------+-----------+------------------ 1 | 188 | 201 | user_1@domain.com | 3 | 2 | 193 | 201 | user_2...
If I understand correctly, you want pairs of attributes whose ratings are always "1". This should give you the attributes: ``` select least(attr1_id, attr2_id) as a1, greatest(attr1_id, attr2_id) as a2, min(rating_id) as minri, max(rating_id) as maxri from compatibility c group by least(attr1_id, attr2_id), gr...
> My goal is to count the number of rows where `rating_id = 1`, but only > count each combiniation of `attr1_id` and `attr2_id` only once, and > only where there doesn't exist any other row (by other users) that > have `rating_id > 1`. ### Building on your original Your original query was on the right track to exclud...
PostgreSQL - select count(*) for rows where a condition holds
[ "", "sql", "postgresql", "select", "count", "" ]
There is a PhoneNumber table which stores the number as the user has input it (e.g. 555 555 5555, 555-555-5555, 555.555.5555) We register those numbers with a 3-rd party service, which then consumers one our web services, but only provides the number as 10 digits (5555555555). I need to find a match but filtering out...
You are removing all *non* alpha characters, including numbers. Try this variant: ``` Create Function [dbo].[RemoveNonAlphaNumCharacters](@Temp VarChar(8000)) Returns VarChar(800) AS Begin Declare @KeepValues as varchar(50) Set @KeepValues = '%[^a-zA-Z0-9]%' While PatIndex(@KeepValues, @Temp) > 0 ...
``` SELECT COUNT(*) FROM [dbo].[PhoneNumber] WHERE REPLACE([Number],'-','') = '5555555555' ``` You can use this function several times for the needed characters.
Check for equality on a phone number inputted in a variety of formats
[ "", "sql", "sql-server", "" ]
I have two tables Users and Tasks. I need to get the count of tasks grouped by Users.Name and Tasks.Status. I need some help writing query to make my result look similar to the third table. **Users** ``` |- Id -|- Name -| |- 1 -|- Robert -| |- 2 -|- Bob -| |- 3 -|- Vicky -| |- 4 -|- Don -| |- 5 -|- Ron ...
If you want to get zero's in the answer, you need to generate the rows first. Here is a method for getting the results: ``` select u.name, s.status, count(t.userid) as cnt from users u cross join (select distinct status from tasks) s left join tasks t on t.userid = u.id and t.status = s.status group by ...
Select name, status, count(name,status) from users inner join tasks on users.id = tasks.userid group by name,status Something along those lines, I am rusty
SQL Query: Group by multiple columns in different tables
[ "", "sql", "" ]
Consider a table with some rows. by php, I make a SQL query such as "DELETE \* From my\_table". How can I recognize affected rows before running the sql query. On the other words, I want to have the list of affected rows after an sql query and before of its running. All in all, I want to check somethings before runnin...
Suppose you have a DELETE query like: `DELETE FROM my_table WHERE foo='bar'` To see how many records will be deleted you could first run: `SELECT count(*) from my_table where foo='bar'` The result of that query will be the count of records that meet the same condition.
You can perform a `SELECT` query with the same `JOIN` and `WHERE` criteria as the `DELETE` would use. This will return the rows that would have been deleted. If you want perfect safety, you need to use transactions in all the applications that access the tables. The process that's doing the `DELETE` should perform the...
How to check affected rows before an sql query running?
[ "", "mysql", "sql", "" ]
I have 2 tables, 'contacts' and 'job\_titles'. Within the 'contacts' table there is a field named 'position'. With the new 'job\_titles' table, I want to update a field in the 'contacts' table called 'job\_title\_id' if the 'position' fields value is similar to the 'title' field in the 'job\_titles' table and I've come...
The following will match the *shortest* title, on the assumption that is more generic: ``` UPDATE contacts c SET job_title_id = (SELECT id FROM job_titles jt WHERE jt.title LIKE CONCAT('%', c.position, '%') ORDER BY char_length(jt.title) ...
Wildcards query may return more then one records. so the one solution can be if you use the nested query with limit 1. Like ``` UPDATE contacts SET job_title_id = (SELECT id FROM job_titles WHERE job_titles.title LIKE CONCAT('%', contacts.position, '%') limit 1); ``` But here an issue can occur that it may return th...
Sub Query Returns More Than 1 Row LIKE & CONCAT with Wildcards
[ "", "mysql", "sql", "wildcard", "concatenation", "sql-like", "" ]
I am quite new with SQL and loops especially and need some help with the following problem. I have a table like this: ``` SpotID EventID MaxTemp 123 1 45 236 1 109 69 1 18 123 2 216 236 2 29 69 2 84 123 3 91 236 3 457 69 3 280 ``` I would like to generate a new table with the ...
You just need conditional aggregation: ``` select spotid, sum(case when maxtemp > 30 then 1 else 0 end) as over_30, sum(case when maxtemp > 70 then 1 else 0 end) as over_70 sum(case when maxtemp > 100 then 1 else 0 end) as over_100 from likethis group by spotid; ```
One minor change to the previous post, my version only counts within each temp range, else the lower temps will count most temps not temps in that range. ``` DECLARE @DATA TABLE ( SpotID INT, EventID INT, MaxTemp INT ) INSERT INTO @DATA VALUES (123, 1, 45 ), (236, 1, 109), (69 , 1, 18 ),...
Using a loop in SQL to populate the table (SQL Server)
[ "", "sql", "sql-server", "loops", "" ]
I have a need to export the data from the table into .csv file and do it schedulled. I've not work much on SQL developer before, mainly on SQL Server. So what options do i have to do this auto export?
As a Powershell fan, I'd point your attention to this [tutorial](http://blogs.technet.com/b/heyscriptingguy/archive/2012/12/04/use-oracle-odp-net-and-powershell-to-simplify-data-access.aspx "tutorial"). Though SQL Developer not involved.
SQL Developer has a command line interface, SDcli - you'll find it in your SQL Developer BIN directory. You can build a 'cart' in the SQL Developer GUI, and save it to a file. This cart's contents are database objects, including tables. [![enter image description here](https://i.stack.imgur.com/WAH5n.png)](https://i....
Scheduled export from SQL Developer
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I'm using Oracle's APEX and trying to set the default date of one of my columns to '31-dec-2013', but for the life of me, it's not happening. I've tried many syntax variations and gotten a number of errors such as "not a valid month" and "such a unique or primary key exists" something to that effect. Please help! here'...
You can use `to_date` with an explicit date format model as ThorstenKettner shows, which means you won't be relying on the session's NLS\_DATE\_FORMAT. You can also use a [date literal](http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements003.htm#SQLRF51062), which is always in YYYY-MM-DD format: ``` ... ...
Use TO\_DATE to convert a string to date: ``` ... LeaseEndDate date default to_date('31-12-2013','dd-mm-yyyy') ... ```
SQL Create Table Default value as specific date
[ "", "sql", "oracle", "date", "default", "oracle-apex", "" ]
I am trying to find student who has min score which will be the result of the below query. However, I was asked to write the query without using MIN(). Spent several hours but I can't find the alternative solution :'(. ``` select s.sname from student s where s.score = (select min(s2.score) from score s2) ```
This is one way, which will work even if two students have same lowest score. ``` SELECT distinct s1.sname FROM student s1 LEFT JOIN student s2 ON s2.score < s1.score WHERE s2.score IS NULL ``` The below is the method using limit, which will return lowest score student, but only one of them if multiple of them...
Here's a possible alternative to the `JOIN` approach: ``` select sname from student where score in (select score from student order by score asc limit 1) ```
find MIN without using min()
[ "", "sql", "sqlite", "" ]
I have two databases for two companies running on the same software, thus the DB structures are the same. Windows Server 2003, MS SQL Sever 2005. I'm attempting to copy the items list and associated tables from SOURCE to DESTINATION. There are a total of 11 tables, I'm using the same format for the script to do the ...
It seems most likely that the affected tables (and maybe others) have one or more `UNIQUE` constraints (or unique indices) in addition to their PKs. For example, the name of the violated constraint suggests that it might be a constraint such as ``` UNIQUE(ITEMNO, MEAS_TYPE) ``` ... or a unique index on such a collect...
First thing I'd try is making a select statement to see what the conflict is. ``` SELECT * FROM DESTINATION.dbo.ITEM_MEASURE WHERE ITEM_MEASURE_ID IN (SELECT s.ITEM_MEASURE_ID FROM SOURCE.dbo.ITEM_MEASURE s LEFT OUTER JOIN DESTINATION.dbo.ITEM_MEASURE d ON (d.ITEM_MEASURE_ID = s.ITEM_MEASURE_ID) WHERE d.ITEM_MEASURE_...
LEFT OUTER JOIN causing violation of unique key constraint
[ "", "sql", "sql-server", "outer-join", "unique-key", "surrogate-key", "" ]
I have one table called `route_timetables` which contains timetables for bus routes. Each row contains one timetable for one direction(i.e north, south, east, and west) and for one type of day(i.e, weekday, Saturday and Sunday). I need to get the most current timetables for each route. So where route id=X and the rou...
I found an answer here [How to group by 2 fields and order by date at the same time?](https://stackoverflow.com/questions/8082379/how-to-group-by-2-fields-and-order-by-date-at-the-same-time) and re-purposed it. ``` SELECT rt.* FROM route_timetables rt JOIN ( SELECT direction , type , MAX(publish_date)...
You could create a separate table which contains an id (PK), the timetable and direction. Have this new table's id as a FK in your current table and you could call DISTINCT() on this FK. I suggest this as it sounds like you are having repeating values of timetable and/or direction.
Select rows from table where two colmns form a distinct set and order by third field
[ "", "mysql", "sql", "select", "distinct", "" ]
I'm having some difficulty with a query that I'm writing that is meant to display the "makers" that produce laptops with 3 or more DIFFERENT speeds. ``` SELECT DISTINCT Product.maker, Count(Laptop.speed) AS [3+ Different Speeds] FROM Laptop INNER JOIN Product ON Laptop.model = Product.model WHERE type = "laptop" GROUP...
The below query should solve your problem. ``` SELECT maker, COUNT(speed) FROM( SELECT p.maker, l.speed FROM Laptop l INNER JOIN Product p ON l.model = p.model WHERE type = "laptop" GROUP BY 1,2 ) foo GROUP BY 1 HAVING COUNT(1) >= 3 ``` F...
Your query will work fine if you take out the distinct keyword. If you only group by the maker, then that query will bring you back only one record per maker, the distinct is actually redundant.
Writing a Query with Distinct Count in Access
[ "", "sql", "ms-access", "" ]
I have two tables: `data` and `structure` that I am attempting to query to return a recordset with all columns from `data` and a single columns from `structure`. I cannot seem to get the joins figured out. This will be performed in Access 2010, and all fields are strings. `data` contains, among other things, three col...
You can use multiple conditions in a JOIN clause: separate them with boolean operators, just as you would in a WHERE clause (AND, OR, etc.). Your goal is to have all conditions evaluate to TRUE or FALSE, but within that range you can do quite a lot. In your specific case, it's fairly simple - use the Country, State, a...
`SELECT data.*, structure.storeID FROM data LEFT OUTER JOIN structure USING(storeID)`
Multiple column join
[ "", "sql", "join", "ms-access-2010", "" ]
I've got two tables: ``` Researcher (ResId, Fname, Gname) Book (bookID, ResID*, Descr) ``` I need to use `IN` (one of the condition of my assignment) statement to show a list of researchers that have more than 5 books. I've got the following SQL query that seems to be logic but it gives an error. The subquery on its...
``` where ResId in (select Book.ResId, count(*) ``` When you use `IN (Select...`, you can only select one column in the sub query. Change the above to: ``` where ResId in (select Book.ResId ``` only.
Does that work as expected? ``` Select ResId, Fname From Researcher r Inner Join Book b on b.ResId = r.ResId Group By r.ResId, r.FName Having count(b.*) > 5 ```
Group by in nested subquery
[ "", "sql", "" ]
I have tried many combinations i want to convert my Date which is imported from excel and is stored as varchar in 15-Oct-14 format, what i want is to convert it to MSSqlserver datetime format 2014-10-23 00:00:00.000 i have tried all combination from <http://www.sql-server-helper.com/tips/date-formats.aspx> but nothing ...
Check the below script and hope this suits your requirement: ``` Set dateformat ymd Select convert(datetime,'15-Oct-14',105) ```
Try this (solution with guard): ``` set dateformat YMD; select case when isdate(date_column) = 1 then convert(date, date_column, 105) end [converted_date] ```
How to convert 15-Oct-14 varchar to datetime format 2014-10-23 00:00:00.000
[ "", "sql", "sql-server", "datetime", "" ]
I want to find out meter reading for given transaction day. In some cases there won’t be any meter reading and would like to see a meter reading for previous day. Sample data set follows. I am using SQL Server 2008 ``` declare @meter table (UnitID int, reading_Date date,reading int) declare @Transactions table (Tra...
Your SQL Query to get your desired out put will as following: ``` SELECT Transactions_ID, T.UnitID, Transactions_date , (CASE WHEN ISNULL(M.reading,'') = '' THEN ( SELECT MAX(Reading) FROM @meter AS A JOIN @Transactions AS B ON A.UnitID=B.UnitID AND A.UnitID=T.UnitID ) ...
I can think of two ways to approach this - neither of them are ideal. The first (and slightly better) way would be to create a SQL Function that took the Transactions\_date as a parameter and returned the reading for Max(Reading\_date) where reading\_date <= transactions\_date. You could then use this function in a se...
SQL Server 2008 - need help on a antithetical query
[ "", "sql", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
I got some table with hierarchy: ``` create table t_hier (id number primary key, parent number); insert into t_hier (id, parent) values(0, null); insert into t_hier (id, parent) values(1, 0); insert into t_hier (id, parent) values(2, 0); insert into t_hier (id, parent) values(3, 1); insert into t_hier (id, parent) val...
``` with parents as ( select level lvl, id from t_hier start with id = 7 connect by id = prior parent ) select distinct id from t_hier where id != 7 start with id in (select id from parents where lvl > 1) connect by prior id = parent and level <= 2; ``` 1. Find all forefathers 2. Go back and for each forefathe...
This may help : ``` with cte_getHierarchy (id,parent) as ( select t_hier.id,t_hier.parent from t_hier where id = 7 union all select t_hier.id,t_hier.parent from t_hier join cte_getHierarchy on t_hier.id = cte_getHierarchy.parent ), cte_getsibling (id,parent) as ( select cte_getHierarchy.id,cte_getHierarchy....
Get all parents for given element and their siblings
[ "", "sql", "oracle", "hierarchy", "" ]
I have searched both this great forum and googled around but unable to resolve this. We have two tables (and trust me I have nothing to do with these tables). Both tables have a column called `eventId`. However, in one table, data type for `eventId` is `float` and in the other table, it is `nvarchar`. We are selecti...
The problem is most likely because some of the rows have `event_id` that is empty. There are two ways to go about solving this: * **Convert your `float` to `nvarchar`, rather than the other way around** - This conversion will always succeed. The only problem here is if the textual representations differ - say, the tab...
I also received the message "Error converting data type nvarchar to float". This was from a query in SQL Server Management Studio (SSMS) from SQL Server 2019. In my case there were undecipherable characters in the source data, which was exported to CSV from Excel. Some columns were in the "Accounting" format, which ha...
Error unable to convert data type nvarchar to float
[ "", "sql", "sql-server", "" ]
I want to get the 1st of the month following the date the person turns 70. How to achive this in SQL i am calculating age using the formula ``` DECLARE @Date_of_birth DATETIME = '1915-10-02 00:00:00.000' DECLARE @AGE INT SELECT @AGE = FLOOR((CAST (GETDATE() AS INTEGER) - CAST(@Date_of_birth AS INTEGER)) / 365.25) ...
You can use datediff to calculate their age, and then date add to find their 70th birthday. To find the first of the month afterwards, you can use the Month and Year functions. ``` create table #people (name varchar(30), birthdate date) insert into #people values ('Bob', '07/08/1976'), ('Tasha','05/30/1996'),('April'...
``` declare @dob datetime = '1954-06-08' declare @age int = 70 select DATEADD(m, DATEDIFF(m, -1, DATEADD(yy, @age, @dob)), 0) ```
How to calculate age (in years) based on Date of Birth in SQL
[ "", "sql", "" ]
I have an requirement where I need to get a record with min time difference with current record. Let us assume that in a table I have insert date, group Id and Id column. I have selected a record and not want to get another record for which difference between insert date of selected record and another record is min. I...
If you indeed want to find closest insert time for the selected record' group, regardless of the direction, then something like this might help: ``` select t.insert_date, ca.* from B.Emp t outer apply ( select top (1) * from B.Emp e where e.group_id = t.group_id and e.id != t.id ...
``` select * From B.Emp emp Inner Join ( select MAX(emp1.insert_time) maxTime, emp1.id From B.Emp emp1 group by emp1.id ) maxDateRec ON maxDateRec.id = emp.id AND maxDateRec.maxTime = emp.insert_time where emp.id = 5 ``` Try with this second one.
Get record with min time difference
[ "", "sql", "sql-server", "t-sql", "" ]
I want to use to insert a string that has an @ notation in sqlplus, but sqlplus reads the string like i am trying to open an .sql file. Is there a way to stop sqlplus from doing that. ex ``` set define off; DECLARE test CLOB := q'[ @font-face {font-family:Wingdings; panose-1:5 0 0 0 0 0 0 0 0 0;...
Used Oracles Quote operator: `q'[""]`
Interesting, I don't have this issue in sqlplus (SQL\*Plus: Release 11.2.0.1.0 Production): ``` SQL> set serveroutput on SQL> create table tmp1(x varchar2(100)); Table created. SQL> insert into tmp1 values ('@font-face {font-family:"Cambria Math"; panose-1: 2 4 5 3 5 4 6 3 2 4;}'); 1 row created. ``` You can set a...
SQLPlus using at notation @ in a String
[ "", "sql", "oracle", "sqlplus", "" ]
I have +10 million articles(200 to 1000 words) in a `InnoDB` table. I only use this type of query when I'm working with `article` field: ``` SELECT article,title,other_fields from table where id=123; ``` **What is the most "space effective" way to store text in MySQL?** Now the **table size is *say* 100GB, my object...
MyISAM is more space friendly than InnoDB, you can start with that one.
As others have pointed out, innodb [compressed rows](http://dev.mysql.com/doc/innodb/1.1/en/innodb-row-format-dynamic.html) is an option. You need to be sure that your file\_format system parameter is set to Barracuda though. An attempt to alter to make the row format compressed where row format is the default Antelop...
What is the most "space effective" way to store text in MySQL?
[ "", "mysql", "sql", "optimization", "" ]
I want to display all the products that do not have a visibility rule with hidden: true. I cant quite figure out the sql. I have the following 4 tables: ``` products: id: integer name: string role: id: integer name: string user_roles: user_id: integer role_id: integer visibility_rules: hidden: boolean product: inte...
Visible products for a ***given*** `user_id`: ``` SELECT p.* FROM user_roles ur JOIN role r ON r.id = ur.role_id JOIN visibility_rules vr ON vr.role = r.id JOIN spree_products p ON p.id = vr.product WHERE ur.user_id = 123 -- given user_id AND NOT vr.hidden GROUP BY p.id; ...
``` select sp.id,sp.name,svr.hidden from spree_products sp inner join spree_visibility_rules svr on sp.id = svr.product where svr.hidden = 0 ```
Left outer sql join problems
[ "", "sql", "ruby-on-rails", "postgresql", "" ]
I have table `user_groups` and I need to select maximal `int` value of field `time` or `0` if any `user_group` entity has `0` in `time` field. Something like this: ``` SELECT time FROM user_groups WHERE IF (time == 0) THEN time = 0 ELSE MAX(time) ``` I need multiplatform solution. **UPDATED:** I'm usin...
This solution usues abs function to cover also negative time case: ``` SELECT case when min(abs(time)) = 0 then 0 else max(time) end FROM user_groups; ```
How about using case ``` SELECT case when min(time) = 0 then 0 else max(time) end FROM user_groups; ``` or if time could be < 0 but only time 0 or more should be considered then adding a where clause can help ``` SELECT case when min(time) = 0 then 0 else max(time) end FROM user_groups where time >= 0; ```
SELECT MAX field value OR zero value
[ "", "mysql", "sql", "select", "max", "" ]
``` SELECT Field1 FROM Table WHERE Field1 BETWEEN "A%" AND "D%" ``` Example Data: ``` A432434324324 B435435435 C5654664546 D5465465546546 A768677687 B8768678768 A65446456546 B876867877868 ``` Query outcome won't include "D" line, any ideas how to deal with it? ( I need to operate on text, not numbers).
Leave out the wildcard and try: ``` WHERE Field1 >= 'A' AND Field1 < 'E' ``` Or: ``` WHERE LEFT(Field1, 1) BETWEEN 'A' and 'D' ``` The `'%'` wildcard is used for `LIKE`, not for other string comparisons. Two notes: * The first version is better because it would allow MySQL to use an index on `Field1`. * Use singl...
You can't use wildcard in the "between" function. With you Query you get all values between A and the % sign and D and the % sign. Where the % sign is before the numbers.
SQL BETWEEN missing data
[ "", "mysql", "sql", "csv", "" ]
I'm trying to write a SQL query that uses CASE and STRING together and getting an error. This is what I'm trying to work on. Any help is greatly appreciated. I tried adding in STRING function as well but also does not work. ``` SELECT Case when sn.1_code = 1 then 'Attended -- ' , ...
As other answers have pointed out, you need to concatenate your string values together. From the very very very little I know of Intersystems Cache SQL (I just looked it up), you will [**need to use `||`**](http://docs.intersystems.com/ens20141/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_stringmanipulation) to concatenate...
It looks like you're trying to concatenate strings. The actual operator may vary depending on your server software, but the idea would be: ``` SELECT Case when sn.1_code = 1 then 'Attended -- ' + sn.mult_1 + 'and' + sn.dict_2 + ' also acted with ' + sn.dict_3 + '.' when sn.1_code = 3 then 'left bec...
SQL using CASE with STRING function
[ "", "sql", "string", "case", "intersystems-cache", "" ]
I would like to update a column of type DATETIME such that it takes year, month, and date from a parameter `@date` (in a stored procedure for Microsoft SQL Server 2012) but retains hours, minutes, seconds, etc. from its present value. Is there a concise SQL expression for combining dates in such a manner (similar to w...
Get the date part from the @date parameter and the time part from the existing value in the column. ``` UPDATE mytable SET mydatetimecolumn = CAST(CONVERT(date, @date) as datetime) + CONVERT(time, mydatetimecolumn) WHERE <my_where_clause> ```
I might suggest just adding complete days: ``` select dateadd(day, datediff(day, col, @date), col) ``` If you want this in an `update`: ``` update table t set col = dateadd(day, datediff(day, col, @date), col); ```
SQL expression for combining dates such that year/month/date comes from 1st, hours/etc. from 2nd
[ "", "sql", "sql-server", "datetime", "calendar", "" ]
Let's say that I have a customer table: ``` CustomerID | FirstName | LastName 1 | John | Smith 2 | John | Adams 3 | Kevin | Smith 4 | Kevin | Adams ``` Now imagine that this table has 200k+ rows. Would it increase performance to create a separate FirstName a...
It depends on your query workload. This is a simple form of data compression. Reducing the set of data that is needed to answer a given query can improve performance. On the other hand you introduce overhead in many places. It is a trade-off. If you want to retrieve the values of those columns you now need to join. DM...
Whether such a move would increase performance depends on what queries you perform, but it is likely to do the opposite for many of the queries that I envision you wanting to perform.
First and Last name tables to increase performance?
[ "", "sql", "sql-server", "" ]
I am struggling trying to learn a Django query against two models: ``` class Invoice(models.Model): contact = models.ForeignKey(Contact) dateCreated = models.DateTimeField(auto_now_add=True) jobName = models.CharField(max_length=30) jobAddress = models.CharField(max_length=30, blank=True) class Conta...
So basically what you want is all information for the invoice and associated contact for the invoice having the id 5; to do this: ``` # Fetch the invoice with id = 5 invoice = Invoice.objects.get(id=5) ``` Now, to fetch information about the related contact, simply "follow" the foreign key: ``` print(invoice.contact...
you would rather set your models in this way: (Contact first, then invoice..) ``` class Contact(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) address = models.CharField(max_length=30) class Invoice(models.Model): contact = models.ForeignKey(Contact, re...
django relationship query
[ "", "sql", "django", "" ]
[**SQL Fiddle.**](http://sqlfiddle.com/#!12/1483a/1) I'm having a slow start to the morning. I thought there was a more efficient way to make the following query using a join, instead of two independent selects -- am I wrong? Keep in mind that I've simplified/reduced my query into this example for SO purposes, so let...
You don't need to join to `customers` at all (given relational integrity). Generally, this is a case of **relational division**. We assembled an arsenal of techniques under this related question: * [How to filter SQL results in a has-many-through relation](https://stackoverflow.com/questions/7364969/how-to-filter-sql...
And here another option, don't know what the fastest one would be on large tables. ``` SELECT customers.* FROM customers JOIN customers_cars USING(customer_id) WHERE car_make = ANY(ARRAY['BMW','Ford']) GROUP BY customer_id, name HAVING array_agg(car_make) @> ARRAY['BMW','Ford']; ``` --- vol7ron: [Fidd...
Making simple SQL more efficient
[ "", "sql", "postgresql", "relational-division", "" ]
When I read about inner or outer joins in SQL, all examples and descriptions are about 2 tables being joined. What if there are more than 2 tables in the query? Is that still considered a join? I think inner join still makes sense even if it is between multiple tables; but I'm not sure outer joins makes sense between ...
Inner joins and outer joins are perfectly reasonable to use with more than 2 tables. Inner joins force the result to display only data that has whatever row you joined on, whereas outer joins display all data no matter what. Let us say you wanted to join 4 tables together... ``` select * from testtable inner join t...
Most examples of joins will include two tables. However, joins can be done on any number of tables. You can read more about joins all over the interwebs, but you might want to start with: <http://www.w3schools.com/sql/sql_join.asp> <http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/> The w3schools arti...
SQL Join: Are selects between more than 2 tables still joins?
[ "", "mysql", "sql", "oracle", "join", "" ]
I am having a little issue inserting the date time into a database table name (TestTable) in SAS EG. The date fields in the TestTable are defined as ``` Name = EnteredDate Type = Date Length = 8 Format = DATETIME22.3 Informat = DATETIME22.3 Name = LastUpdateDate Type = Date Length = 8 Format = DATETIME22.3 Inform...
There are a few different issues here. First off, `&sysdate9.` and `&sysdate.` are only [defined at system startup](http://support.sas.com/documentation/cdl/en/mcrolref/68140/HTML/default/viewer.htm#n0psau13pzzhf2n1mndr75gw7vc8.htm). To get the current date, you need `%sysfunc(today(),date9.)` or `%sysfunc(datetime(),...
Joe's answer covers it, but here is a solution using your SQL. You almost have it. Try this ``` %let today_dttm=%sysfunc(datetime()); INSERT INTO LIBNAME.TestTable (Statuscode, EnteredDate, LastUpdateDate) VALUES ('2', &today_dttm,&today_dttm); ```
Inserting date/time in a SQL table in SAS
[ "", "sql", "sas", "" ]
So I'm trying to print all the comments from my database, but only if they have been approved. I recently heard that you can use if statements in your SQL, but I'm not exactly sure how it works. This is what I tried: ``` SELECT name, created, comment IF('approved' = 1) FROM table_example WHERE id = 3 ``` It should ...
``` SELECT name, created, comment FROM table_example WHERE id = 3 AND approved = 1 ``` Or am I missing something ??
you could do something like this: ``` SELECT name, created, CASE WHEN approved = 1 THEN comment ELSE NULL END as comment FROM table_example WHERE id = 3 ``` you could replace NULL for the default value you want showed if the comment is not approved.
Only execute SELECT statement IF something
[ "", "mysql", "sql", "" ]
I have the following contacts table ``` id | date_registered 1 2014-08-07 2 2014-08-13 3 2014-08-14 4 2014-10-08 5 2014-10-08 ``` I want to run a query which says tell me the number of users that were registered in the months August, September and October. Hence for the above data the query would retur...
Do a full join to a Table containing the months. Filter to those datasets having the registerdate older than this rows "all-month-list"-date. You get a list with one entry per user per month since his registration. Thereover you may group as said before.
You can do what you want by explicitly listing the months and using `left join`: ``` SELECT m.mon AS month, count(c1.date_registered) as ContactsOnSystem FROM (select 2014 as yr, 8, 201408 as yyyymm as mon union all select 2014, 9, 201409 union all select 2014, 10, 201410 ) m left join contacts c...
Mysql How To Get Total Number Of Registered Users At Each Month
[ "", "mysql", "sql", "" ]
in Oracle ApEx I have a table like this: ``` CREATE TABLE "ATTENDANCE_HOURS" ("ID" NUMBER NOT NULL ENABLE, "PERSON_ID" NUMBER, "PROJECT_ID" NUMBER, "FROM_X" DATE NOT NULL ENABLE, "TO_X" DATE NOT NULL ENABLE, "NOTE" VARCHAR2(300), "APPROVED" NUMBER DEFAULT 0 NOT NULL ENABLE, "APP...
Total hours for each person in a week would look something like this: ``` select person_id, to_char(day, 'YYYY-WW') as week, sum(to_x - from_x) as hours_worked from #OWNER#.ATTENDANCE_HOURS group by person_id, to_char(day, 'YYYY-WW') order by person_id, week; ``` I have no idea what the extra logic is on the p...
The following query gives you the sum of worked hours minus breaks for each person (provided project 21 means break and all others mean work): ``` select person_id, sum(case when project_id = 21 then -1 else 1 end * (to_x - from_x)) * 24 from #OWNER#.ATTENDANCE_HOURS group by person_id; ``` To get this per day can...
Select sum of hours grouped by a day first and then by a week
[ "", "sql", "oracle", "select", "oracle-apex", "" ]
I am trying to figure out all of the records that only have the value null in two columns. The problem I am running into is that I have 565 ROWS with Columns including ID, Allegation1, allegation 2, date, concatenatedalleg12 so it shows up as ``` ID ALLEG1 ALLEG2 DATE CONCATENATED 1 NULL NULL ...
``` SELECT ID, MAX(ALLEG1) AS ALLEG1, MAX(ALLEG2) AS ALLEG2, MAX([DATE]) AS [DATE], MAX(CONCATENATED) AS CONCATENATED FROM @TBL GROUP BY ID HAVING SUM(CASE WHEN ALLEG1 IS NULL THEN 0 ELSE 1 END + CASE WHEN ALLEG2 IS NULL THEN 0 ELSE 1 END) = 0 ```
``` WITH idswithonerow AS ( SELECT ID FROM ( SELECT ID, COUNT() OVER (PARTITION BY ID) AS CN FROM tablename ) as tmp WHERE CN = 1 ) select ID, ALLEG1, ALLEG2, DATE, CONCATINATED FROM tablename WHERE ALLEG11 is null and ALLEG2 is null AND ID IN SELECT ID FROM idswithoner...
Showing DISTINCT cases where NULL
[ "", "sql", "sql-server", "" ]
I'm trying to find the most efficient way to concatenate text in PL/SQL. My system scans five variables, and does something along these lines: ``` return_value := '' IF variable_a is null THEN return_value := 'Error: Variable A null'; END IF; IF variable_b is null THEN IF return_value ...
There are plenty of ways to do this I'm sure. One possibility is to concatenate all the errors in the same way, as 'Variable ? null, ', then if necessary prefix with 'Error: ' and remove the redundant comma and space at the end. ``` return_value := ''; IF variable_a is null THEN return_value := 'Variable A null, ...
You can define a function that simulate ternary operator, this makes more readible your code in my opinion. The final presentation of error obviously can be improved. ``` declare return_value varchar2(4001); variable_a varchar2(1) := null; variable_b varchar2(1) := 'B'; variable_c varchar2(1) := 'C'; func...
Concatenating text in PL/SQL in a more concise way
[ "", "sql", "oracle", "plsql", "concatenation", "" ]
I have a table "Store" with the attributes "name" of type String (indexes checked for sort query and search). I want to execute a SQL like query to find all stores with name beginning with a substring. So I tried this predicate : ``` NSPredicate *pred = [NSPredicate predicateWithFormat:@"ANY name BEGINSWITH %@",subst...
My guess is that you need to get rid of the "ANY". > The ANY and SOME aggregate operators may be combined with the IN and > CONTAINS operators to perform list membership tests. So ANY is for lists (Arrays). Since 'name' is a String, it is not a list, hence the mismatch error: "Field value type mismatch in query predi...
Wild guess...try: ``` [NSPredicate predicateWithFormat:@"ANY {'name','category'} BEGINSWITH %@",substring]; ``` That may be an incorrect reversal of key/value but it might work.
NSPredicate and BEGINSWITH with CloudKit : Field value type mismatch
[ "", "ios", "sql", "nspredicate", "cloudkit", "" ]
I have a table which has `transaction_id` as the primary key and also contains `customer_id` which is a foreign key. Now there is a column `type` which has two values: `'Card'` and `'cash'`. Now some of the customers have used both the methods for payment. I want to add a new column and classify the customers as "Onl...
Rather than adding a column to the table, if what you want to do is analyze the payment methods, then doing something like this might be better: ``` SELECT DISTINCT Table1.[Customer ID], T1.* FROM Table1 CROSS APPLY (SELECT SUM(CASE WHEN [Type] = 'Cash' THEN 1 ELSE 0 END) AS Cash, SUM(CASE WHEN [Type] = 'Ca...
You can use window functions: ``` select t.*, (case when min(type) over (partition by customerid) = max(type) over (partition by customerid) then 'Only ' + min(type) over (partition by customerid) else 'both' end) from transactions t; ```
SQL: Add a column and classify into categories
[ "", "sql", "sql-server", "join", "" ]
I am trying to write a case statement inside the IN clause. The Channel column contains three values ACT, REN, REP. I want to select more than 1 values, but I get result with only one value. ``` select * from tbl WHERE tbl.Channel IN (select case when @ACT =1 then 'ACT' ...
This will work fine. [SQL Fiddle](http://www.sqlfiddle.com/#!6/7f5b1/1) The only change is removing the `select` so the input to the in clause is 3 values rather than a single row with three columns. The implicit `else null` if the variable is not 1 does not cause a problem in an `in` clause. ``` SELECT * FROM tb...
Don't end your case. You are returning 3 columns. You only want one. ``` select * from tbl WHERE tbl.Channel = case when @ACT =1 then 'ACT' when @REN =1 then 'REN' when @REP =1 then 'REP' else NULL END ```
Case Statement in 'IN' clause in SQL
[ "", "mysql", "sql", "sql-server", "" ]
![Word Replacement Table ScreenShot](https://i.stack.imgur.com/eQMdp.png) Hi, I have a table "tbl\_address\_replacement", attached is the screen shot of the data in it. My Input string is @input = 'Auriga Building 4' I want to replace the above input string by matching values in "word\_contains" column in the above...
I wrote something like this a little while ago whilst doing a system migration. Here's the applicable code: ``` DECLARE @rowcount int; -- Repeat until there are no iterations left (lazy recursive method) SET @rowcount = 937; WHILE (@rowcount > 0) BEGIN UPDATE addresses SET address_line_1 = Replace(x.add...
This will be helpful to you. **EXAMPLE : SELECT dbo.[fnSplitString1] ('Auriga Building 4')** ``` CREATE FUNCTION [dbo].[fnSplitString1] ( @InputString NVARCHAR(MAX) ) RETURNS VARCHAR(50) AS BEGIN DECLARE @delimiter CHAR(1) DECLARE @start INT, @end INT DECLARE @Result NVARCHAR(MAX) DECLARE @...
Function to replace words in a inputstring based on values in a table
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "sql-server-2012", "" ]
I have two tables one parent table ``` ID Name 1 Sam 2 Ricky ``` Then i have a child table , here we have one to many relation ship like record sam has multiple address Like (Child Table) ``` ID Parent_ID Address 1 1 Newyork 2 1 Chicago ``` Now what i wanna do is to write a query where i will g...
Using `INNER JOIN` and `PIVOT` u can get the result. Try this.. ``` CREATE TABLE #par ( ID INT, Name VARCHAR(100) ) INSERT #par VALUES (1,'Sam'), (2,'Ricky') CREATE TABLE #chil ( ID INT, Parent_ID INT, Addresss VARCHAR(100) ) INSERT #chil VALUES( 1,1,'Newyork'), ...
should be something like ``` select * from parent inner join child on child.parent_id = parent.id ``` but that is simple joining. maybe i missed your question?
Joint Parent and child table in a sql statement to get the records of the both the table
[ "", "mysql", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to find a way to add a count to the output of my query: ``` SELECT * FROM (SELECT id, 'Event Location' AS name, venueName AS snippet, venueLatLng AS coordinates, (3959 * acos(cos(radians('xx.xxxxxx')) * cos(radians(SUBSTRING(venueLatLng, 1...
Use the analytic version of `COUNT`, and make sure to put it in your *outer* query so it will respect the `WHERE distance < 30`. ``` SELECT TMP.*, COUNT(*) OVER () AS RCount FROM ( SELECT id, 'Event Location' AS name, venueName AS snippet, venueLatLng AS coordinates, (3959 * acos(cos(ra...
Count(\*) is going to make your query an aggregate and so, unless you use a group by, the result will be a single row. The error message is saying that you cant't use the other fields and still generate a single row
Adding count(*) to SQL Server query
[ "", "sql", "sql-server", "database", "record-count", "" ]
I want to select from a table but the problem is, I have a factor column that indicates how many times this row must be selected (this a sample table just for demonstration): ``` ID Factor Count ------------------------------- 1 1 235 2 2 345 ...
This should be enough: ``` SELECT A.* FROM dbo.YourTable A INNER JOIN (SELECT * FROM master.dbo.spt_values WHERE type = 'P') B ON A.Factor >= B.number+1 ``` [**Here is a sqfiddle**](http://sqlfiddle.com/#!3/0870d/1) with a demo of it. And the results are: ``` ╔════╦════════╦═══════╗ ║ ID...
If you know what the 'max' factor is. ``` SELECT [id],[count] FROM table WHERE factor > 1 UNION ALL SELECT [id],[count] FROM table WHERE factor > 2 UNION ALL SELECT [id],[count] FROM table WHERE factor > 3 . . . order by [id] ``` There's probably a way to do this with a recursive CTE. Don't know how much eff...
SQL Server: selecting a row multiple times by the given factor
[ "", "sql", "sql-server", "" ]
I have duplicate rows in my table and I want to delete duplicates in the most efficient way since the table is big. After some research, I have come up with this query: ``` WITH TempEmp AS ( SELECT name, ROW_NUMBER() OVER(PARTITION by name, address, zipcode ORDER BY name) AS duplicateRecCount FROM mytable ) -- Now Del...
I like @erwin-brandstetter 's solution, but wanted to show a solution with the `USING` keyword: ``` DELETE FROM table_with_dups T1 USING table_with_dups T2 WHERE T1.ctid < T2.ctid -- delete the "older" ones AND T1.name = T2.name -- list columns that define duplicates AND T1.address =...
If you have no other unique identifier, you can use `ctid`: ``` delete from mytable where exists (select 1 from mytable t2 where t2.name = mytable.name and t2.address = mytable.address and t2.zip = mytable.zip and ...
How to delete duplicate rows without unique identifier
[ "", "sql", "postgresql", "" ]
I have a table 'contacts' which is structured like this: * id, name, surname, etc And contacts\_related * contact\_id, name, surname One contact can have multiple related contacts (joined by contact\_id). What I would like to do is make a SELECT query on contacts that if a search input is given (example: 'John') it...
A possible solution is ``` SELECT DISTINCT C.* FROM contacts C LEFT JOIN contacts_related R ON C.id=R.contact_id WHERE C.name LIKE '%John%' OR R.name LIKE '%John%' ```
You want those contacts that are either Johns themselves or have a John relation. To look up the relations use EXISTS or IN. ``` select * from contacts where name like '%John%' or exists ( select * from contacts_related where name like '%John%' and contact_id = contacts.id ); ``` Or: ``` select * from cont...
Search in joined table with multiple records
[ "", "mysql", "sql", "join", "" ]